迭代3个元素的映射
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++) {
不确定我在这里做错了什么-这应该是一个简单的修复。
-
您输入错误(您使用空格而不是
::
)。 -
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; }
你忘了::before iterator.
你也可以使用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";
}
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除映射和分割错误中的一个过去结束元素
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 访问映射向量的映射元素(c++)
- 为什么 unordered_map::equal_range upper_bound 如果键小于第一个映射元素,则返回
- 根据类成员对同一密钥的多映射元素进行排序
- C++查找并擦除多映射元素
- C++ for_each循环找不到指向映射元素
- 创建映射元素时,请避免使用值副本
- 从常量迭代器到映射向量,获取映射向量中映射元素的键和值
- c++中如何更改映射元素的值
- 传递对映射元素的引用作为参数
- 如果没有找到映射元素将返回什么
- 不能访问指针-向量映射元素
- 存储内部排序映射元素的最快方式
- 无序多映射元素插入
- 哈希映射元素的值未正确打印
- 修改所有映射元素的键
- 复制映射元素的正确方法