[英]c++ - iterating through a map of 3 elements
我對在C ++中使用STL容器非常陌生。
我有一個由3個元素組成的映射(成對的2個字符串-充當鍵,而int充當值。)
map<pair<string, string>, int> wordpairs;
但是,當我嘗試像這樣遍歷它時:
for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.end(); i++) {
cout << i->first << " " << i->second << "\n";
}
編譯器拋出錯誤:
error: expected ‘;’ before ‘i’
for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.
^
error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
a7a.cpp:46:50: note: (if you use ‘-fpermissive’ G++ will accept your code)
error: cannot convert ‘std::map<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int> >}’ to ‘int’ in assignment
for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.
^
error: no match for ‘operator!=’ (operand types are ‘int’ and ‘std::map<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int> >}’)
for (map<pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.
^
error: expected ‘)’ before ‘;’ token
pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.end(); i++) {
^
error: expected ‘;’ before ‘)’ token
pair<string, string>, int> iterator i = wordpairs.begin(); i != wordpairs.end(); i++) {
不知道我在這里做錯了什么-雖然這應該是一個簡單的解決方法。
您輸入的類型錯誤(使用空格而不是: ::
。
映射迭代器為您提供了一個鍵值對-您的鍵是一對! 因此,您有一對,其中一對是成員。 這是一個大致可以完成您想做的例子。
#include <iostream> #include <map> #include <string> #include <utility> using namespace std; int main() { pair<string, string> my_key("To", "Be"); map<pair<string, string>, int> wordpairs { { {"Hello", "World"}, 33} }; for (const auto& kv : wordpairs) { cout << kv.first.first << ", " << kv.first.second << static_cast<char>(kv.second); } return 0; }
您在迭代器之前忘記了::。
您還可以使用auto關鍵字:
for (auto i = wordpairs.begin(); i != wordpairs.end(); ++i) {
cout << i->first << " " << i->second << "\n";
}
或簡單地使用基於范圍的for循環:
for (auto& i : wordpairs) {
cout << i->first << " " << i->second << "\n";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.