the difference between : cbegin(cend) and begin(end)

本文深入探讨了C++中begin()和end()函数的使用,解释了它们如何用于访问容器的起始和结束元素,并通过实例展示了在数组中的特殊行为。文章还详细阐述了begin()函数作为数组概念的一部分而非迭代器成员函数的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cbegin(cend):

Return const_iterator to beginning
Returns a const_iterator pointing to the first element in the container.

A const_iterator is an iterator that points to const content. This iterator can be increased and decreased (unless it is itself also const), just like theiterator returned by vector::begin, but it cannot be used to modify the contents it points to, even if the vector object is not itself const.

If the container is empty, the returned iterator value shall not be dereferenced.


begin(end):

Return iterator to beginning
Returns an iterator pointing to the first character of the string.



Additional topics for the begin and end:

When the article say the begin() function in the array, we should get more attention on the begin function.. It says it's a function in the concept of "array", not the member-fucntion for the iterator.

I found there is another point we need to know.. The books don't mention it. for a instance:

#include <iostream>

#include <iterator>

using name space;

int main()

{

int ia[] = {0,1,2,3,4,5,6,7,8,9}; // ten elements in the array

int  *pbeg = begin(ia);

int *pend = end(ia):

cout << *pbeg << " " << *pend << endl;

}

if you print them, what  does your comipler tell u ? The gcc compiler told me:  0,0. The *pend doesn't point to the last element in array. why?

Let's make some change for it?

#include <iostream>

#include <iterator>

using name space;

int main()

{

int ia[] = {0,1,2,3,4,5,6,7,8,9}; // ten elements in the array

int  *pbeg = begin(ia);

int *pend = end(ia):

cout << *pbeg << " " << *pend << endl;

for (unsigned int i = 0; i != 11; ++i) // special purpose for the error..

 cout << *(pbeg+i) << " |";

}

Check it out? Holly crap, the *pend had been changed, the undefined ia[11]  is same as the *pend... What's that???

*pend pointer is stranger than I had know. But right now, i see it .

the safe usage is *(pend-1) replace the *pend.... At least , we need more thinking when we programing...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值