【发布时间】:2017-03-19 15:45:04
【问题描述】:
我对在 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
, int>::iterator i 吗? map , int> iterator i 没有意义......您一次声明了两个变量(iterator 和 i) -
在需要冒号的地方使用空格。
-
谢谢大家!这解决了问题!
-
但现在我有另一个问题:
error: no match for ‘operator<<’在线:cout << i->first << " " << i->second << "\n";我认为这与原始问题无关。 -
@RockAndaHardPlace 因为
i->first是一对.. 那么你将如何打印一对呢?看到这个stackoverflow.com/questions/19228994/…
标签: c++ syntax iterator scope-resolution