我从被调用函数返回多映射迭代器。
代码:
std::multimap<int,std::string>::iterator it = dst.begin();
for(int count = 0;count<3 && it !=dst.end();++it,++count)
std::cout<<it->second<<":"<<it->first<<std::endl;
return it;
并调用函数:
std::multimap<int,std::string>::const_iterator rec;
rec= client();
for(int count = 0;count<3 ;++count)
std::cout<<rec->second<<":"<<rec->first<<std::endl; // Prints garbage values
这里为什么我不能rec
直接打印内容?在被调用的函数std::cout<<it->second<<":"<<it->first<<std::endl;
中打印正确的值!
完整代码:
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
std::multimap<int,std::string>::iterator client()
{
std::vector<std::string> most { "lion","tiger","kangaroo",
"donkey","lion","tiger",
"lion","donkey","tiger"
};
std::map<std::string, int> src;
for(auto x:most)
++src[x];
std::multimap<int,std::string,std::greater<int> > dst;
std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()),
[] (const std::pair<std::string,int> &p) {
return std::pair<int,std::string>(p.second, p.first);
}
);
std::multimap<int,std::string>::iterator it = dst.begin();
for(int count = 0;count<3 && it !=dst.end();++it,++count)
std::cout<<it->second<<":"<<it->first<<std::endl;
return it;
}
int main()
{
std::multimap<int,std::string>::const_iterator rec;
rec= client();
for(int count = 0;count<3 ;++count,++rec)
std::cout<<rec->second<<":"<<rec->first<<std::endl;
}