修改引用返回的向量
modifying vector returned by reference
为什么下面的向量大小是0?
#include <iostream>
#include<vector>
using namespace std;
class A
{
public:
vector<int> T;
const vector<int>& get(){
return T;
}
void print(){
cout<< " size is "<<T.size();
// cout<<" nelements are %d "<<T[0];
}
};
int main()
{
cout << "Hello World" << endl;
A ob;
vector<int> temp = ob.get();
temp.clear();
temp.push_back(3);
temp.push_back(5);
ob.print();
return 0;
}
这是因为它什么也没发生。它仍然是空的。
您在 temp
中创建了向量的副本,并且修改了副本,而不是原始类成员。您应该使用引用:
vector<int> &temp = ob.get();
由于您要从 get()
返回引用,因此必须将其分配给引用。如果你不这样做,你只是在复制对象。
编辑:另外,更改get()
以返回可变引用,而不是const
引用。
您没有修改A
类内部的vector
。 get()
返回一个 (const!) 引用,然后您将其分配给非引用变量,因此正在创建vector
的副本。 然后,您正在修改副本,但打印出原始副本。
您需要改为执行以下操作:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
vector<int> T;
vector<int>& get(){
return T;
}
void print(){
cout << " size is " << T.size();
// cout << " nelements are %d " << T[0];
}
};
int main()
{
cout << "Hello World" << endl;
A ob;
vector<int> &temp = ob.get();
temp.clear();
temp.push_back(3);
temp.push_back(5);
ob.print();
return 0;
}
两个问题。
首先,A::get()
方法返回对其成员的 const 引用。不能通过常量引用修改向量。
其次,您正在修改 temp
向量,该向量只是返回值的副本。
相关文章:
- 矩阵向量乘法(cublasDgemv)返回零
- C++中函数的向量返回类型引发错误
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 从 std<Derived>::shared_ptr 的向量返回 std::shared_ptr<Base>
- 从对象的向量返回某个类的对象
- C++ 将向量中出现 n 次的所有元素作为向量返回
- 向量返回负大小 c++
- 如何从向量返回给定类型的元素?
- 将对象的向量返回到函数
- 尝试从向量返回对象时出现"没有可行的重载运算符 [] 错误
- 调用函数时,如何通过向量返回类型
- 向量返回/加法算法的问题
- 在向量返回上移动语义行为
- 从int c++的向量返回一个无符号长
- 向量返回空 C++
- 从融合向量的std向量返回列,无需复制
- C++为空向量上的向量返回什么::back()
- 函数的向量返回
- 如何用适当的OO有效地将100万的私有向量返回给其他几个类