std::vector的结构是什么?
What is the structure of a std::vector?
我已经用递归的方式打印一个向量的所有元素,但它 returns 胡说八道!它抛出了一个非常奇怪的异常:
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
在指针算法中将 4 批 sizeof(std::vector<int>)
添加到 foo
。该位置没有 std::vector
,因此 printVec(foo + 4)
的行为未定义。
表达式 (*foo)[0]
正在 std::vector
上调用重载的 []
运算符,它访问向量中的第一个元素。如果该位置没有元素,则程序的行为未定义。
What is the mistake I have made?
您正在使用指向单个向量的指针并将其视为指向 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());
}
What is the structure of a std::vector?
你不需要知道也不需要关心。如果要迭代元素,请使用迭代器。如果要访问底层数组,请使用 .data()
.
我已经用递归的方式打印一个向量的所有元素,但它 returns 胡说八道!它抛出了一个非常奇怪的异常:
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
在指针算法中将 4 批 sizeof(std::vector<int>)
添加到 foo
。该位置没有 std::vector
,因此 printVec(foo + 4)
的行为未定义。
表达式 (*foo)[0]
正在 std::vector
上调用重载的 []
运算符,它访问向量中的第一个元素。如果该位置没有元素,则程序的行为未定义。
What is the mistake I have made?
您正在使用指向单个向量的指针并将其视为指向 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());
}
What is the structure of a std::vector?
你不需要知道也不需要关心。如果要迭代元素,请使用迭代器。如果要访问底层数组,请使用 .data()
.