简体   繁体   English

我应该如何将向量中的数据推送到带有整数键的地图中?

[英]How should I push the data in a vector into a map with integer key?

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;

}

#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.如果不存在, operator[]()将为地图创建一个新项目,如果存在则追加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM