を修正するために、ベクトル::バック()を使用する:私はに要素を追加しようとしています私は、次の構造体持っているベクトル要素
std::vector<A> a_vector;
:
#include <string>
#include <vector>
struct A {
std::string name;
int id;
};
と要素を含むベクトルをベクトルを計算し、その値を次のように変更します。
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は次のように定義されています。本当にどのように私は要素がベクトル内の1つのと同じで持つように行うことができます
void get_a(A& a) //This function normally assigns a in different ways
{
a_vector.emplace_back();
a = a_vector.back();
}
)の引数として渡すとリターンとしてそれを取得しないする必要がありますか?私は本当にポインタを使用する必要がありますか?
あなたがそのコピーを作成しているためです。それを言います。 refereneceを使用してください:A&a = a_vecotr.back(); – Ondrej
なぜdownvotes?私たちは自明性の理由で投票していますか?この質問はよく書かれています。 – Bathsheba
みんなあなたがdownvoteするときに私はしばらくの間、さらなる質問をすることを禁じています。 :/ –