Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to work with an object that was stored in a vector?

Coming from Java, I am confused about how to correctly access an object that was stored in a vector.

In this test case, I expected both outputs to display the same number (2):

#include <iostream>
#include <vector>

using namespace std;

class Item {
public:
  int id = 0;
  Item(int id)
  {
    this->id = id;
  }
};

int main()
{
  vector<Item> items;
  Item item = Item(1);
  items.push_back(item);

  Item itemFromVector = items.at(0);
  itemFromVector.id = 2;

  cout << "item: " << item.id << endl;
  cout << "itemFromVector: " <<  itemFromVector.id << endl;
}
// output:
// item: 1
// itemFromVector: 2
like image 583
Reto Höhener Avatar asked Dec 30 '25 01:12

Reto Höhener


1 Answers

In this case you will have item.id equal to 1.

The reason behind this is the push_back call will execute a COPY of your object in the vector (The Item in your vector and item are 2 different objects).

One way to observe what you are trying to achieve is to use pointer:

int main()
{
  vector<Item*> items; //items contains addresses of Item object
  Item item = Item(1);
  items.push_back(&item); // push address of your item

  Item* itemFromVector = items.at(0); // Pointer to item
  itemFromVector->id = 2; // Modify item id attribute

  cout << "item: " << item.id << endl; // Access item id attribute
  cout << "itemFromVector: " <<  itemFromVector->id << endl; // Access item id attribute
}
like image 168
Jérôme Avatar answered Dec 31 '25 15:12

Jérôme



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!