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

Time:08-29

#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"]?

CodePudding user response:

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.

CodePudding user response:

If you want to alter the values of examplevector via your map you should declare your map as a map of strings associated to vector pointers, therefore you can alter the original vector using the its reference in the map.

Adapting your code, it will become like:

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
  vector<string>* examplevector = new vector<string>({"one", "two", "three"});
  map<string, vector<string>*> examplemap = {{"vector1", examplevector}};

  examplemap["vector1"]->at(0) = "eight";

  cout << examplemap["vector1"]->at(0) << endl; // prints "eight"
  cout << examplevector->at(0) << endl; // prints "eigth", as expected.

}
  •  Tags:  
  • c
  • Related