#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
vector<string> examplevector {"one", "two", "three"};
map<string, vector<string>> examplemap {{"vector1", examplevector}};
examplemap["vector1"][0] = "eight";
cout << examplemap["vector1"][0] << endl; // prints "eight"
cout << examplevector[0] << endl; // prints "one". I was expecting "eight".
}
Is there a way to alter the values within examplevector via examplemap["vector1"]?
>Solution :
No, C++ does not work this way, this is not how objects work in C++. This is how objects work in Java and C#, but C++ is not Java or C#. Objects that are stored in some container, a vector, a map, or any other container, are distinct objects of their own and have nothing to do with any other object.
map<string, vector<string>> examplemap {{"vector1", examplevector}};
This effectively makes a copy of the examplevector and stores it in the map. Changes to the object in the map have no effect on the original examplevector. Similarly:
string abra="cadabra";
std::vector<std::string> examplevector{"hocuspocus", abra};
// ...
examplevector[1]="abracadabra";
This modifies the object in the vector. abra is still cadabra.
It’s possible to store a map or a container of pointers, or perhaps std::reference_wrappers. Then, modify the pointed-to object, or wrapped reference, will modify the underlying object. But that introduces its own kind of complexity, in terms of managing the lifetime of all objects, correctly.