【发布时间】:2018-05-15 10:56:17
【问题描述】:
我有以下结构:
#include <string>
#include <vector>
struct A {
std::string name;
int id;
};
还有一个包含A元素的向量:
std::vector<A> a_vector;
我正在尝试将一个元素附加到向量并使用以下内容更改其值:
void test()
{
A a;
get_a(a);
//Up to this point I thought modifying this a object would mean modifying the back element of the vector. But it doesn't work as planned, doing this:
a.id = 2; //Doesn't modify the id of the element in the vector.
}
其中 get_a 定义为:(代码被简化,在实际中我确实需要传递 a 作为参数而不是返回)
void get_a(A& a) //This function normally assigns a in different ways
{
a_vector.emplace_back();
a = a_vector.back();
}
如何使 a 元素与向量中的元素相同?我真的必须使用指针吗?
【问题讨论】:
-
因为你正在复制它 A a;说。使用参考:A &a = a_vecotr.back();
-
为什么投反对票?我们是否以显而易见的理由投票?这个问题写得很好。
-
@hamzakeurti:我个人不同意对这个问题的反对意见,正如我已经提到的那样。但是您可以通过编写一个可编译的示例来改进它。
-
@hamzakeurti:你应该在这里做,在你之前问过的任何问题中。也不要实质性地更改问题(就像您在最近的编辑中所做的那样),因为这会使答案无效。
-
这是一个很好的例子,为什么
...在minimal reproducible example 中没有位置;)。为什么要预先声明引用a并将其传递给其他函数,而无论如何您以后想将最后一个元素分配给它?似乎您想对两个不相关的事情使用相同的变量,只是不要这样做。
标签: c++ vector reference c++14