Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert insert into a map of <string, vector<pair:: <string, string>> > in C++?

I am trying to create a symbol table where the key to the map is an identifier and the vector it returns contains pairs of strings representing type and scope, respectively. I am able to get a map with a string key return a vector of single strings to work, but when I try pairs, I get an error.

#include <iostream>
#include <utility>
#include <vector>
#include <map>
#include <string>
using namespace std; //using std namespace for readibility for this question

int main() {
    string key = "myKey";
    string string1 = "string1";
    string string2 = "string2";
    pair <string, string> stringPair = make_pair (string1, string2);

    map<string, vector<std::pair <string, string>>> myMap;
    myMap.insert( make_pair (key,  make_pair (string1, string2) )); //insert key into map, create empty vector
                                    //this is where I get th error

    myMap[key].push_back(std::make_pair (string1, string2) ); //use key, push strings into vector<string, string>

    return 0;
}

error C2664: 'std::pair<_Ty1,_Ty2> std::_Tree<_Traits>::insert(std::pair<const _Kty,_Ty> &&)' : cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &&'

I could get a vector of single strings to work, but that seems like more of a workaround than having true pairs for each instance of an identifier. Any help is appreciated!

like image 795
Johnny Avatar asked Aug 31 '25 22:08

Johnny


1 Answers

Here is a very simple C++11 version that work but might be hard to read later, depends on the people:

#include <iostream>
#include <utility>
#include <vector>
#include <map>
#include <string>
using namespace std; //using std namespace for readibility for this question

int main() {
    string key = "myKey";
    string string1 = "string1";
    string string2 = "string2";
    map<string, vector<std::pair <string, string>>> myMap;

    myMap.insert( { key, {{ string1, string2 }} } ); 

    return 0;
}

Tested there: http://coliru.stacked-crooked.com/ (GCC4.8)

Of course if you want to add to the vector that contain the strings, you need to first check if the vector already exists. Here I am not checking if the vector already exists so if it does, there will be no insersion.

like image 60
Klaim Avatar answered Sep 03 '25 13:09

Klaim