[英]Vector with index and iterator
I just wanted to ask what is happening here, where am I going wrong? 我只是想问一下这里发生了什么,我哪里出错了?
vector<int> a(5);
for(int i=0; i<5; i++) cin>>a[i]; //Input is 1 2 3 4 5
for(int i=0; i<5; i++) cout<<a[i]<<" "; //Prints correct, 1 2 3 4 5
cout<<endl;
for(VI::iterator it = a.begin(); it!=a.end(); ++it) {
cout<<a[*it]<<" "; //Prints incorrect output
}
cout<<endl;
Looks like, the last element in the incorrect output is a[*(a.end()-1)]
and the first element is missing from what it should actually be. 看起来,错误输出中的最后一个元素是
a[*(a.end()-1)]
并且第一个元素缺少实际应该是什么。
correct way to print is 正确的打印方式是
cout<<*it<<" ";
*it gives value pointed by vector. *它给出了矢量指向的值。 In your case a[*it] = a[1] for first iteration, a[2] for second iteration ans so on.
在你的情况下,[* it] = a [1]用于第一次迭代,a [2]用于第二次迭代,依此类推。 at end invalid number will be printed.
最后将打印无效的号码。 Its the reason for missing first number.
它是缺少第一个号码的原因。 Your trying to print a[1] a[2], a[3],a[4],
你试图打印[1] a [2],[3],a [4],
By calling *it
you are getting the value at that iterator (which is what I think you want to output). 通过调用
*it
您将获得该迭代器的值(我认为您想要输出)。 You're current code is actually doing: 你现在的代码实际上在做:
a[1]
a[2]
a[3]
a[4]
a[5] // not an element in the vector - undefined behaviour
What I think you actually want is: 我认为你真正想要的是:
cout<<*it<<" ";
What happens here 这里发生了什么
for(VI::iterator it = a.begin(); it!=a.end(); ++it) {
cout<<a[*it]<<" "; // *it is 1, 2, 3, 4, 5
}
is that it
is an iterator to each element of the vector, and *it
dereferences the iterator, giving the value of the element. it
是向量的每个元素的迭代器, *it
取消引用迭代器,给出元素的值。 Since the indices and the values stored are almost the same in this case, this almost works. 由于在这种情况下存储的索引和值几乎相同,所以这几乎可以工作。 You are looping from a[1] to a[5], missing the first element, and then going out of bounds.
你正在从[1]循环到[5],缺少第一个元素,然后走出界限。
Iterator is not an index to a vector. 迭代器不是向量的索引。 It is an object that points to an element of the vector and has overloaded dereference operator that yields the value of the element pointed by that iterator.
它是一个指向向量元素的对象,它具有重载的解引用运算符,它产生迭代器指向的元素的值。
When you do a[*it]
, you essentially use the value of an element stored in the vector (pointed by it
) as an index to that array. 当你执行
a[*it]
,你基本上使用存储在向量中的元素的值(由it
指向)作为该数组的索引。 In other words, you are referencing elements 2 though 6, and also invoke undefined behavior because there is no 6th element in your vector. 换句话说,您正在引用元素2到6,并且还调用未定义的行为,因为向量中没有第6个元素。
You have probably meant to write cout<<*it<<" ";
你可能打算写
cout<<*it<<" ";
instead of cout<<a[*it]<<" ";
而不是
cout<<a[*it]<<" ";
. 。 Or, alternatively, given your data set in that vector, you could do
cout<<a[*it - 1]<<" ";
或者,或者,给定您在该向量中的数据集,您可以执行
cout<<a[*it - 1]<<" ";
in order to access elements 1 through 5 by using index 0 through 4. 为了使用索引0到4访问元素1到5。
Hope it helps. 希望能帮助到你。 Good Luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.