[英]What is the structure of a std::vector?
I have made a recursive way of printing all of the elements of a vector, but it returns nonsense!我已经用递归方式打印了一个向量的所有元素,但它返回无意义! and it throws a really strange exception:它抛出了一个非常奇怪的异常:
Exception thrown: read access violation.
std::vector<int,std::allocator<int> >::operator[](...) returned nullptr.
And it outputs: 12358000
它输出: 12358000
This is the code.这是代码。 What is the mistake I have made?我犯了什么错误?
#include <iostream>
#include <vector>
using namespace std;
int printVec(vector<int>* foo) {
if ((*foo).empty())
return 0;
else {
cout << (*foo)[0];
printVec(foo + 4);
}
}
int main() {
vector<int> ref{ 1,2,3,4,5,6,7,8,9,0 };
printVec(&ref);
}
foo
is a pointer to a std::vector<int>
. foo
是指向std::vector<int>
的指针。
foo + 4
is adding 4 lots of sizeof(std::vector<int>)
to foo
in pointer arithmetic. foo + 4
在指针算术中向foo
添加了 4 批sizeof(std::vector<int>)
。 There is not a std::vector
at that location, so the behaviour of printVec(foo + 4)
is undefined.该位置没有std::vector
,因此printVec(foo + 4)
的行为未定义。
The expression (*foo)[0]
is calling the overloaded []
operator on a std::vector
which access the first element in the vector.表达式(*foo)[0]
正在调用std::vector
上的重载[]
运算符,该运算符访问std::vector
中的第一个元素。 If there is no element at that position then the behaviour of the program is undefined.如果该位置没有元素,则程序的行为未定义。
What is the mistake I have made?我犯了什么错误?
You are using a pointer to a single vector and treat it as if it points into an array of std::vector<int>
.您正在使用指向单个向量的指针并将其视为指向std::vector<int>
数组。 It is only allowed to increment pointers that point to elements in arrays (actually you are allowed to get a pointer one past an object, but not more).只允许增加指向数组中元素的指针(实际上你可以得到一个指针超过一个对象,但不能更多)。 A single std::vector
is not an array and your code invokes undefined behavior by incrementing foo
here: printVec(foo + 4);
单个std::vector
不是数组,您的代码通过在此处增加foo
来调用未定义的行为: printVec(foo + 4);
. .
If you want to "point to" elements of the vector use iterators:如果要“指向”向量的元素,请使用迭代器:
#include <iostream>
#include <vector>
using namespace std;
template <typename IT>
void printVec(IT current, IT end) {
if (current == end) return;
else {
cout << *current;
printVec(current+1,end);
}
}
int main() {
vector<int> ref{ 1,2,3,4,5,6,7,8,9,0 };
printVec(ref.begin(),ref.end());
}
What is the structure of a std::vector? std::vector 的结构是什么?
You need not know nor care.你不需要知道也不需要关心。 If you want to iterate elements use iterators.如果要迭代元素,请使用迭代器。 If you want to access the underlying array use .data()
.如果要访问底层数组,请使用.data()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.