S
subramanian100in
Consider the code fragment:
vector<int> container;
container.push_back(0);
container.push_back(1);
container.push_back(2);
Now I want to iterate through the 'container'.
For this, instead of writing,
for (vector<int>::const_iterator cit = container.begin();
cit != container.end();
++cit)
// ... do something ...
I thought I should write:
const vector<int>& ref = container;
for (vector<int>::const_iterator cit = ref.begin();
cit != ref.end();
++cit)
// ... do something ...
The reason is :
in the line vector<int>::const_iterator cit = container.begin();
the 'container' is non-const. So 'container.begin()' will return
plain iterator which is copied to const_iterator. So a
conversion is involved here.
Instead, if I use ref.begin() - with 'ref' as defined above,
'begin() const' will be called on 'ref' which will directly return
a const_iterator. So no conversion is involved here.
Is my understanding correct ?
Also, kindly clarify if the line
const vector<int>& ref = container;
involves any temporary object ?
Thanks
V.Subramanian
vector<int> container;
container.push_back(0);
container.push_back(1);
container.push_back(2);
Now I want to iterate through the 'container'.
For this, instead of writing,
for (vector<int>::const_iterator cit = container.begin();
cit != container.end();
++cit)
// ... do something ...
I thought I should write:
const vector<int>& ref = container;
for (vector<int>::const_iterator cit = ref.begin();
cit != ref.end();
++cit)
// ... do something ...
The reason is :
in the line vector<int>::const_iterator cit = container.begin();
the 'container' is non-const. So 'container.begin()' will return
plain iterator which is copied to const_iterator. So a
conversion is involved here.
Instead, if I use ref.begin() - with 'ref' as defined above,
'begin() const' will be called on 'ref' which will directly return
a const_iterator. So no conversion is involved here.
Is my understanding correct ?
Also, kindly clarify if the line
const vector<int>& ref = container;
involves any temporary object ?
Thanks
V.Subramanian