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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With