虽然我使用像这样的迭代器,
//include header files
using namespace std;
int main()
{
map<int,int> intIntMap;
map<int,int>::iterator pos;
pos = intIntMap.begin();
intIntMap[0] = 1;
intIntMap[3] = 5;
intIntMap[4] = 9;
intIntMap[5] = 5;
//??
cout << (*pos).first << endl;
while( pos != intIntMap.end() )
{
cout << pos->first << " <---> " << pos->second << endl;
pos++;
}
}
Run Code Online (Sandbox Code Playgroud)
输出为4;
但是我使用像这样的迭代器:
//include header file
using namespace std;
int main()
{
map<int,int> intIntMap;
map<int,int>::iterator pos;
intIntMap[0] = 1;
intIntMap[3] = 5;
intIntMap[4] = 9;
intIntMap[5] = 5;
//??
pos = intIntMap.begin();
cout << (*pos).first << endl;
while( pos != intIntMap.end() )
{
cout << pos->first << " <---> " << pos->second << endl;
pos++;
}
}
Run Code Online (Sandbox Code Playgroud)
输出是我想要的;
我想知道迭代器的使用之间的区别是什么,当我插入新的键值对时,第一个迭代器的位置是什么?谢谢!
addtion:编译是使用gcc 4.1.2,感觉比较困惑,像这样:

Jer*_*fin 10
由于您begin()在容器为空时调用,因此您得到的迭代器等于end()(§23.1/ 7:"如果容器为空,则begin()== end()").
将项目插入容器并没有改变,所以你仍然有pos == intIntMap.end().
然后,您执行循环的零迭代,因为pos==end(),并且您只执行循环pos != end().
在第二个示例中,pos()在插入数据后进行设置,以便获取集合中的第一个项目,并迭代到最后一个项目.
编辑:就打印出地图的内容而言,我可能更喜欢这样做:
std::ostream &operator<<(std::ostream &os, std::pair<int, int> const &d) {
return os << d.first << " <---> " << d.second;
}
// ...
std::copy(intIntMap.begin(), intIntMap.end(),
std::ostream_iterator<std::pair<int, int> >(std::cout, "\n"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
792 次 |
| 最近记录: |