![](/img/trans.png)
[英]Why can I access C++ map elements with a for loop but not individually?
[英]Can I access the elements in a c++ std::map by an integer index?
我有一個我想要迭代的元素圖。 當然,標准的方法是使用for循環
for (map<string, int> iterator it = myMap.begin(); it != myMap.end(); ++it) {
string thisKey = it->first;
int thisValue = it->second;
}
但是如果我嘗試使用OpenMP的並行構造使這個循環並行運行,它就不起作用,這顯然是一個已知的問題,因為它不能識別這種循環結構。
所以,我的備份計划是使用整數索引迭代器,並按索引訪問鍵和值列表,就像我在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)。
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"; } }
以下是一些相對無痛的選項。
為數組訪問保留std::vector
或std::deque
,以及單獨的值映射。 確保它們一致的腿部工作是你的問題。
使用boost :: multi_index來確保兩個索引結構之間的一致性。 作為警告,使用此選項的編譯時間相當長。 如果你走這條路,請考慮使用pimpl習語 。
我沒有使用OpenMP的經驗,所以我不能推測這些選項中的任何一個在實踐中是否值得。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.