我可以访问 c++ 中的元素吗? std::map 按整数索引?
我有一张想要迭代的元素地图。当然,执行此操作的标准方法是使用 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++ 中做到这一点?
I have a map of elements that I would like to iterate through. Of course, the standard way to do that would be using a for loop with
for (map<string, int> iterator it = myMap.begin(); it != myMap.end(); ++it) {
string thisKey = it->first;
int thisValue = it->second;
}
but if I try and make this loop run parallel using OpenMP's parallel for construct, it doesn't work, and this is (apparently) a known issue, as it doesn't recognize this sort of loop construct.
So, my backup plan was to use an integer index iterator, and access the list of keys and values by index, as I would do in C# like so:
for (int i = 0; i < myMap.Count; ++i) {
string thisKey = myMap.Keys[i];
string thisValue = myMap.Values[i];
}
... yet I can't seem to find an equivalent method in C++. Is there a way to do this in C++ that I'm unaware of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对OpenMP一无所知,所以我不知道它是否会优化以下内容。但是你可以使用
std::advance
,如下所示:但是请注意,std::advance 是 O(n),因此您的(单线程)复杂度是 O(n^2)。
EDIT: If you copy the map elements to a vector, realize you can do that in one declaration:
因此:
I don't know anything about OpenMP, so I don't know if it will optimize the following or not. But you could use
std::advance
, like so:But do be aware that
std::advance
is O(n), so your (single-threaded) complexity is O(n^2).EDIT: If you copy the map elements to a vector, realize you can do that in one declaration:
thus:
这里有一些相对轻松的选项。
保留一个
std::vector
或std::deque
用于数组访问,以及一个单独的值映射。确保它们一致的跑腿工作是你的问题。使用 boost::multi_index 来保证两个索引结构的一致性。警告一下,使用此选项的编译时间相当长。如果您选择此路线,请考虑使用pimpl idiom。
我没有使用 OpenMP 的经验,因此我无法推测这些选项在实践中是否值得。
Here are a few options that are relatively painless.
Keep a
std::vector
orstd::deque
for array access, and a separate map of values. The leg work of ensuring that they are consistent is your problem.Use boost::multi_index to ensure consistency between the two index structures. As a word of warning, compile times are pretty long with this option. Consider using the pimpl idiom if you go this route.
I have no experience with OpenMP, so I cannot speculate if either of these options would be worthwhile in practice.