我有一个要遍历的元素映射。当然,标准的方法是使用 for 循环和
for (map<string, int> iterator it = myMap.begin(); it != myMap.end(); ++it) {
string thisKey = it->first;
int thisValue = it->second;
}
但是如果我尝试使用 OpenMP 的 parallel for 构造使这个循环并行运行,它就不起作用,这(显然)是一个已知问题,因为它不识别这种类型循环构造。
因此,我的备份计划是使用整数索引迭代器,并按索引访问键和值列表,就像我在 C# 中所做的那样:
for (int i = 0; i < myMap.Count; ++i) {
string thisKey = myMap.Keys[i];
string thisValue = myMap.Values[i];
}
...但我似乎无法在 C++ 中找到等效的方法。有没有我不知道的在 C++ 中执行此操作的方法?
最佳答案
我对OpenMP一无所知,所以我不知道它是否会优化以下内容。但是你可以使用 std::advance
,像这样:
#include <map>
#include <string>
#include <iterator>
#include <iostream>
typedef std::map<std::string, int> Map;
int main() {
Map m;
m["one"] = 1;
m["two"] = 2;
for(int i = 0; i < m.size(); ++i) {
Map::iterator it = m.begin();
std::advance(it, i);
std::string thiskey = it->first;
int thisValue = it->second;
std::cout << thiskey << "\n";
}
}
但请注意 std::advance
是 O(n),因此您的(单线程)复杂度是 O(n^2)。
编辑:如果您将 map 元素复制到 vector ,请意识到您可以在一个声明中执行此操作:
std::vector<Map::value_type> v(m.begin(), m.end());
因此:
#include <map>
#include <string>
#include <iterator>
#include <iostream>
#include <vector>
typedef std::map<std::string, int> Map;
int main() {
Map m;
m["one"] = 1;
m["two"] = 2;
int i = 0;
for( std::vector<Map::value_type> v(m.begin(), m.end());
i < v.size(); ++i) {
std::string thiskey = v[i].first;
int thisValue = v[i].second;
std::cout << thiskey << "\n";
}
}
关于c++ - 我可以通过整数索引访问 C++ std::map 中的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919140/