Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I reference a vector from a map's value?

#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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading