C++ map迭代器跳转元素

标签 c++ dictionary insert iterator

我有一个关于 std::map 结构的问题: 此代码片段可以正常工作:

map<string,int> mappa;
int main(int argc, char** argv) {
mappa["b"]=1;
mappa["a"]=2;
 for(std::map<string,int>::iterator it=mappa.begin();it!=mappa.end();++it )
{
    cout<<it->first<<"\n";     
} 
return 0;
}

输出:

a
b

但如果我这样做:

map<string,int> mappa; 
std::map<string,int> getList(){
return mappa;
}

int main(int argc, char** argv) {
mappa["b"]=1;
mappa["a"]=2;
for(std::map<string,int>::iterator it=getList().begin();it!=getList().end();++it )
 {
    cout<<it->first<<"\n";   
 } 
return 0;
}

我的输出只是

b

为什么? 谢谢!

最佳答案

在 for 循环中,您从 mappa 的 2 个单独拷贝中获取 begin() 和 end(),因为 getList() 按值而不是引用返回。您需要更改 getList() 函数以通过引用返回。

按预期工作的代码:

#include <iostream>
#include <string>
#include <map>

using namespace std;

map<string,int> mappa; 

std::map<string,int>& getList() { // returning reference now
  return mappa;
}

int main(int argc, char** argv) {
  mappa["b"]=1;
  mappa["a"]=2;
  for(std::map<string,int>::iterator it=getList().begin();it!=getList().end();++it )
  {
    cout<<it->first<<"\n";   
  } 
  return 0;
}

关于C++ map迭代器跳转元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300360/

相关文章:

c++ - 如何保证两个线程中的两个类写同一个变量线程安全?

c++ - 从 C++ 更改 QML 对象值

c++ - 重建字符串删除标点符号的问题

c# - 如何在 C# 中向字典添加多个值?

sql - 对多行使用 SELECT INTO

c++ - 将临时对象作为 LValues 传递

python - 如何在 Python 中初始化空列表字典?

python - 防止评估现有键的dictionary.get或dictionary.setdefault中的默认函数

php - 插入然后更新内部循环

c++ - 为什么 std::vector::insert 是一个带有空初始化列表的无操作?