const vs non-const version of begin( )

S

subramanian100in

Suppose I have

vector<int> v;
vector<int>::const_iterator citer = v.begin( );

Here which version of begin( ) is called ? const or non-const
version ?

Kindly explain

Thanks
V.Subramanian
 
K

Kai-Uwe Bux

Suppose I have

vector<int> v;
vector<int>::const_iterator citer = v.begin( );

Here which version of begin( ) is called ? const or non-const
version ?

Should be non-const ...

Kindly explain

.... because v is not const.


Best

Kai-Uwe Bux
 
G

Guest

Suppose I have

vector<int> v;
vector<int>::const_iterator citer = v.begin( );

Here which version of begin( ) is called ? const or non-const
version ?

The non-const version. The reason for this is the fact that v is not
const. Consider the following example:

#include <vector>

void foo(const std::vector<int>& v)
{
std::vector<int>::const_iterator it = v.begin();
}

int main()
{
std::vector<int> v;
std::vector<int>::iterator it = v.begin();
std::vector<int>::const_iterator cit = v.begin();

foo(v);
}

In foo() you must use a const_iterator since v is const, in main()
however you can use either since a const_iterator can be constructed
from an iterator. Notice though that I have not found anything in the
standard requiring this, so it might not be portable.
 
P

Pete Becker

Suppose I have

vector<int> v;
vector<int>::const_iterator citer = v.begin( );

Here which version of begin( ) is called ? const or non-const
version ?

As everyone else has said, non-const. If that's a problem, there are
two ways to call the const version.

((const vector<int>&)v).begin();
v.cbegin();

The latter is a recent addition to the C++0x specification, so chances
are your library doesn't have it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top