[英]What is the structure of a std::vector?
我已经用递归方式打印了一个向量的所有元素,但它返回无意义! 它抛出了一个非常奇怪的异常:
Exception thrown: read access violation.
std::vector<int,std::allocator<int> >::operator[](...) returned nullptr.
它输出: 12358000
这是代码。 我犯了什么错误?
#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
是指向std::vector<int>
的指针。
foo + 4
在指针算术中向foo
添加了 4 批sizeof(std::vector<int>)
。 该位置没有std::vector
,因此printVec(foo + 4)
的行为未定义。
表达式(*foo)[0]
正在调用std::vector
上的重载[]
运算符,该运算符访问std::vector
中的第一个元素。 如果该位置没有元素,则程序的行为未定义。
我犯了什么错误?
您正在使用指向单个向量的指针并将其视为指向std::vector<int>
数组。 只允许增加指向数组中元素的指针(实际上你可以得到一个指针超过一个对象,但不能更多)。 单个std::vector
不是数组,您的代码通过在此处增加foo
来调用未定义的行为: printVec(foo + 4);
.
如果要“指向”向量的元素,请使用迭代器:
#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());
}
std::vector 的结构是什么?
你不需要知道也不需要关心。 如果要迭代元素,请使用迭代器。 如果要访问底层数组,请使用.data()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.