[英]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.