[英]:bad_alloc in passing vector reference to pointer to vector in constructor
[英]Updating vector by passing by reference in constructor
我試圖編寫一段代碼,在其中通過類的構造函數按引用傳遞矢量,並在該類的成員函數中更新矢量。 但是當我回到main函數時,向量中沒有更新發生:
//頭文件
class A{
private:
std::vector<T> &x;
public:
A(std::vector<T>& x_):x(x_) {}
int func();
};
// Cpp文件
int A::func() {
// process done
T temp;
x.push_back(temp);
}
// 主功能
int main() {
std::vector<T> vec;
A a(vec);
a.func();
}
我嘗試將向量更改為類中的指針而不是引用,但是函數運行后向量不會更新。 關於程序中需要更改的任何建議?
#include <iostream>
#include <vector>
using namespace std;
class A
{
std::vector<int> &x;
public:
A(std::vector<int>& x_):x(x_) {}
int func();
};
int A::func(){
int temp=0;
x.push_back(temp);
return 0;
}
int main(){
std::vector<int> vec;
A a(vec);
a.func();
return 0;
}
一切都好,vec改變了。 我認為您還有一個甚至沒有意識到的問題或錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.