Reputation: 67
How should I push the data in a vector into a map with integer key such that I should be able to append to the existing vector at a particular key?
#include <iostream>
#include<map>
#include<vector>
using namespace std;
int main()
{
std::map<int, std::vector<double>> my_map;
std::vector<double> data;
int j=0;
data.push_back(1.0);
data.push_back(3.4);
for(int k=0; k<2;k++)
my_map.insert(j, data[k] ); // but this wont allow me to append if the same key is to be used
return 0;
}
Upvotes: 0
Views: 42
Reputation: 5192
#include <iostream>
#include <map>
#include <vector>
int main() {
std::map<int, std::vector<double>> my_map;
std::vector<double> data;
int j = 0;
data.push_back(1.0);
data.push_back(3.4);
for (int k = 0; k < 2; k++)
my_map[j].push_back(data[k]);
return 0;
}
EDIT: Simplified solution proposed. operator[]()
will create a new item for the map if it does not exist, and append if it does.
Upvotes: 1