我有一个关于 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/