I am trying to understand a part of a code in which
(*this).bond.assign(mck.bond.begin(), mck.bond.end())
I want to understand the role of begin() and end () command. I read at different places that it is an iterator index but i couldn't understand its meaning. I tried to understand it by writing a short code but it is not working. Can someone please help me to understand the above line of the code and the role of begin() and end() command.
int main()
{
vector<int> vec_name;
vec_name.push_back(10);
vec_name.push_back(20);
vec_name.push_back(30);
vec_name.push_back(40);
cout << vec_name.size() <<endl;
cout << vec_name.begin() <<endl;
}
.begin()
returns an iterator, not the element or a reference to the element. It's not the same as printing vec_name[i]
or using vec_name::front()
which returns a reference. So to print the returned value, you need to declare an iterator which receives the return value of vec_name.begin()
and then print the iterator.
**EDIT: ** Using your example code, it would be something like this:
int main()
{
vector<int> vec_name;
vector<int>::iterator it;
vec_name.push_back(10);
vec_name.push_back(20);
vec_name.push_back(30);
vec_name.push_back(40);
cout << vec_name.size() <<endl;
//cout << vec_name.begin() <<endl; //cannot print iterators directly
it = vec_name.begin(); //Pass return value to iterator.
cout << *it << endl; //Print dereferenced iterator
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.