[英]vector list initializer and assignment
For the two snippet of code, i don't understand the second one对于这两个代码片段,我不明白第二个
1st: it prints 0 1 2 as expected第一个:它按预期打印 0 1 2
vector<int> ivec;
ivec={0,1,2};
for(auto i: ivec){
cout<<ivec[i]<<endl;
}
2nd: it prints 0 0 0 5. How is this random value generated?第二:它打印 0 0 0 5。这个随机值是如何生成的?
vector<int> ivec;
ivec={0,1,2};
ivec={4,5,9,1};
for(auto i: ivec){
cout<<ivec[i]<<endl;
}
This is undefined behavior because ivec
has size 4
yet you are indexing elements such as 4
, 5
, and 9
which are out of bounds.这是未定义的行为,因为
ivec
的大小为4
但您正在索引超出范围的元素,例如4
、 5
和9
。
for(auto i : ivec){
cout << ivec[i] << endl;
}
Instead you should be printing the elements themselves相反,您应该打印元素本身
for(auto i : ivec){
cout << i << endl;
}
To be clear, in your range-based for
loop i
is the actual element not the index of the element.需要明确的是,在基于范围的
for
循环中, i
是实际元素而不是元素的索引。 If you wanted to use indices you would not use a range-based for
loop如果您想使用索引,则不会使用基于范围的
for
循环
for(std::size_t i = 0; i < ivec.size(); ++i){
cout << ivec[i] << endl;
}
this loop here:这个循环在这里:
for(auto i : ivec)
is not the same as不一样
for(int i =0; ...)
when you do当你这样做时
for(auto i: ivec){ // with ivec value to {4,5,9,1};
cout<<ivec[i]<<endl;
}
then you do:然后你做:
cout << ivec[4] << endl; // Undefined Behav...
cout << ivec[5] << endl; // Undefined Behav...
cout << ivec[9] << endl; // Undefined Behav...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.