c++ - 如何遍历 STL 映射(找到所有可能的对)

标签 c++ dictionary

如何迭代 STL map 以应对所有元素。换句话说,我想找到所有可能的对。我想要一个高效的算法(复杂性)。

如果有一个STL vector ,算法就简单了。

vector<int> vInt;
vector<pair<int, int> > vPair;
for(int i = 0; i < vInt.size(); i++) {
    for(int j = i + 1; j < vInt.size(); j++) {
        vPair.push_back(make_pair(vInt[i], vInt[j]));
    }
}

但是,如果你有像算法一样的STL图呢?

Obs:我想要所有可能的组合 map 的值(不是键)

map<int, int> map;
vector<pair<int, int> > vPair;
???

我想在 STL vector 中转换为 STL 映射,但是我会采用仅使用 STL 映射的方法

最佳答案

“我想要所有可能的组合值的映射(不是键)”

我不确定你想要什么,但如果你想完全按照你在你的例子中为 vector 所做的那样,在 map 的“值”上

你可以像下面那样做:

std::map<int, int> map;
std::map<int,int>::iterator i,j,end=m.end();  
std::vector<std::pair<int,int> > vpair;
end--;
for(i=m.begin();i!=end;++i)
{
    j=i;
    j++;
    for(;j!=m.end();++j)
        vpair.push_back(std::make_pair(i->second,j->second));
 }

关于c++ - 如何遍历 STL 映射(找到所有可能的对),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320979/

相关文章:

c++ - 如何使用 C++ 获取 XML 文件的属性值?

c++ - 为其他容器实现 std::rank

c# 字典获取最小值的键

Python,压扁一个丑陋的嵌套for循环

python - 如何在 Python 中使函数循环遍历多个字典

C++ ifstream 尝试在写入时打开文件

c++ - 进程外内存堆可在32位地址空间内工作

c++ - 我不断收到错误 : clang: error: linker command failed with exit code 1 (use -v to see invocation). 请帮助,谢谢

c - 将 OpenCL 设备与 NVAPI 设备相关联

ios - 无法将类型 '[(String)]' 的值分配给类型 'String!' 的值?