[英]Access the first element of vector by vector.begin() command
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.我想了解 begin() 和 end() 命令的作用。 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.有人可以帮我理解上面的代码行以及 begin() 和 end() 命令的作用。
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. .begin()
返回一个迭代器,而不是元素或对元素的引用。 It's not the same as printing vec_name[i]
or using vec_name::front()
which returns a reference.它与打印vec_name[i]
或使用返回引用的vec_name::front()
。 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.所以要打印返回值,需要声明一个迭代器,它接收vec_name.begin()
的返回值,然后打印迭代器。
**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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.