Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vector::back() to modify vector element

I have the following struct:

#include <string>
#include <vector>

struct A {
    std::string name;
    int id;
};

And a vector containing A elements:

std::vector<A> a_vector;

I am trying to append an element to the vector and change its values using the following:

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. 
}

where get_a is defined as : (The code is simplified, in the real one I really need to pass a as argument and not get it as return)

void get_a(A& a) //This function normally assigns a in different ways
{
    a_vector.emplace_back();
    a = a_vector.back();
}

How can I do to have the a element be the same as the one in the vector? Do I really have to use pointers?

like image 392
hamza keurti Avatar asked Jun 22 '26 04:06

hamza keurti


1 Answers

A a;
a = a_vector.back();

Here you're copy-assigning a_vector.back() to a. This is not a reference, so modifying a will not modify the element inside the vector.

You want this instead:

A& a = a_vector.back();

If you cannot immediately initialize your reference with a_vector.back(), consider using a pointer...

A* a;

// ...

a = &a_vector.back();

// ... 

something(*a);

...or an index:

std::size_t a_idx;

// ...

a_idx = a_vector.size() - 1;

// ... 

something(a_vector[a_idx]);
  • The pointer will work fine if you know that the vector won't get resized. If the vector resize, iterators and pointers will be invalidated.

  • The index will work fine even if the vector gets resized, as long as the elements are not removed/shifted around.

like image 119
Vittorio Romeo Avatar answered Jun 23 '26 19:06

Vittorio Romeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!