Home > Back-end >  How to push back a vector into a map<int, vector<int>>
How to push back a vector into a map<int, vector<int>>

Time:09-26

What I want to do here is to create a map like this:

0 -> 0,1,...,4;
1-> 0,1,...,4;
...
9 -> 0,1,...,4;
int main(){
    map<int, vector<int>> m;
    for(int i=0; i<10; i  ){
        vector<int> temp;
        for(int j=0; j<5; i  ){
            temp.push_back(j);
        }
        m.insert({i, m.push_back(temp)});
    }
}

But when I try to push back temp = {0,1,2,3,4} vector, it's giving me an error.

I guess there is some problem in the syntax of the underlined line.

Can you tell me how to solve this error?

Screenshot of the code

CodePudding user response:

Note: for(int j=0; j<5; i ){ - Here i should be j , so to fix it:

#include <vector>
#include <map>

int main(){
    std::map<int, std::vector<int>> m;

    for(int i=0; i<10; i  ) {
        std::vector<int> temp;

        for(int j=0; j<5; j  ) { // not i  
            temp.push_back(j);
        }

        m.insert({i, temp}); // not  m.insert({i, m.push_back(temp)});
    }
}

You could however create one vector<int> that you copy into the map:

#include <map>
#include <numeric>
#include <vector>

int main(){
    std::vector<int> tmp(5);
    
    std::iota(tmp.begin(), tmp.end(), 0); // 0,1,2,3,4

    std::map<int, std::vector<int>> m;
    
    for(int i = 0; i < 10;   i) {
        m.emplace(i, tmp);
    }
}

CodePudding user response:

std::map does not have a push_back() method. You need to insert the vector itself that you prepared, eg:

int main(){
    map<int, vector<int>> m;
    for(int i=0; i<10; i  ){
        vector<int> temp;
        for(int j=0; j<5; j  ){
            temp.push_back(j);
        }
        m.insert({i, temp});
    }
}

Alternatively, use map::operator[] instead of map::insert(), let the map create each vector for you, eg:

int main(){
    map<int, vector<int>> m;
    for(int i=0; i<10; i  ){
        vector<int> &vec = m[i];
        for(int j=0; j<5; j  ){
            vec.push_back(j);
        }
    }
}
  • Related