begin()、end()和cbegin()、cend()有什么区别?

13

虽然当我们遍历begin(), end()和cbegin(),cend()时,它们给我们相同的结果。但它们之间有什么区别呢?

#include<iostream>
#include<map>
using namespace std;
int main()
{
    map<char,int>mp;
    mp['a']=200;
    mp['b'] = 100;
    mp['c']=300;
    for(auto it =mp.cbegin();it!=mp.cend();it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }
cout<<endl;
     for(auto it =mp.begin();it!=mp.end();it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }

    return 0;
}

1
cbegin() 总是返回 const_iterator 类型,而 begin() 则可能会或者不会——这取决于调用者是否为 const。 - gchen
3
mp.begin()->second = 42 would work, mp.cbegin()->second = 42 would not. c is for const - Igor Tandetnik
2个回答

9

有两个相关的不同之处。

第一个区别在于cbegin没有重载,它是const限定的,而begin有两个函数的重载,其中一个是const限定的,另一个则没有。

第二个区别在于它们所返回迭代器的类型。根据文档,cbegin返回const_iterator,而begin的一个重载返回iterator,另一个则返回const_iterator(就像cbegin一样)。


9

5
如果变量是常量,beginend也会返回一个const_iterator - apokaliptis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接