我对在 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++) {
不确定我在这里做错了什么 - 不过这应该是一个简单的修复。
最佳答案
您输入错误的类型(您使用了空格而不是
::
)。Map 迭代器给你一个键值对——而你的键是一对!所以你有一对和一对作为成员。这是一个大致可以完成您想做的事情的示例。
#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; }
关于c++ - 遍历 3 个元素的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40445862/