begin(),end()和cbegin(),cend()之间有什么区别?

Tan*_*113 4 c++ stl

虽然我们遍历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;
}
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 6

有两个区别,它们非常相关.

第一个区别是cbegin没有重载,并且它是const限定的,而begin由两个函数重载,其中一个是const限定的而另一个不是.

第二个区别在于它们返回的迭代器的类型.按照文档,cbegin返回const_iterator,而一个过载begin返回iterator和其他返回const_iterator(如cbegin).


Dav*_*ide 5

cbegin:返回指向容器中第一个元素的 const_iterator。
begin:返回指向序列中第一个元素的迭代器。
cend:返回指向容器中最后一个元素的 const_iterator。
end:返回指向序列中最后一个元素的迭代器。

http://www.cplusplus.com/reference/map/map/cbegin/ http://www.cplusplus.com/reference/iterator/begin/?kw=begin http://www.cplusplus.com/reference/地图/地图/cend/ http://www.cplusplus.com/reference/iterator/end/?kw=end

  • 如果变量是常量,“begin”和“end”也会返回一个“const_iterator”。 (5认同)