c++ - 我的 map 迭代器无法访问 map 的每个元素,我该如何解决?

标签 c++ string dictionary insert iterator

我需要将 map 的每个元素(每对元素的第一个和第二个)插入到一个字符串中。我查找的每个解决方案都会执行与此类似的操作:

for(map<string, int>::iterator iter = theMap.begin(); iter != theMap.end(); ++iter)
{
  myString.insert(iter->first);
  myString.insert(iter->first);
}

我一直收到错误信息 no matching function for call to 'std::basic_string<char>::insert(const std::basic_string<char>&)'

如何输出 map 的每个元素?特别是在字符串中!

最佳答案

使用 stringstream为一般人做这件事map键和值重载 operator<< .

stringstream makeMyString;
for(map<string, int>::iterator iter = theMap.begin(); iter != theMap.end(); ++iter)
{
  makeMyString << iter->first << " " <<iter->second;
}
string myString = makeMyString.str();

关于c++ - 我的 map 迭代器无法访问 map 的每个元素,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25029210/

相关文章:

c++ - multimap 与带集合的 map

c++ - OpenGL 着色器不绘制东西 :/

string - IsString 实例不会自动转换为 String

string - 反转字符串中单词中的字母

python - 如何索引到字典中?

c# - 根据字典输入生成动态方程

python - 合并缺少键的字典以创建组合字典

c++ - 从 Wii 平衡板读取数据

mysql - 仅从 mySQL 中的特定字符的左侧和右侧获取字符

c++ - MySQL FROM_UNIXTIME 命令不写入