在STL映射中使用vector作为参数

问题描述 投票:-1回答:1

我一直在尝试将2个值与1个键相关联,我找到的一种方法是使用向量来执行相同操作。我写了以下代码

#include<iostream>
#include<vector>
#include<map>
#include<stdlib.h>

using namespace std; 

map<int,vector<int> map1;

void insertInMap(int q,int a,int b)
{
    vector<int> v1;
    v1.push_back(a);
    v1.push_back(b);
    map1.insert(q,v1);
}
int main()
{
    return 0;
}

insertinmap函数用于创建矢量作为地图的参数。我正在初始化列表时遇到错误

错误 - 模板2参数无效,模板4参数无效。

c++ vector stl containers stdmap
1个回答
3
投票

在地图中,insert()期望作为参数插入一个元素。地图元素是由键和值组成的对。所以:

map1.insert(make_pair(q,v1));

在地图中插入元素的更方便的方法是将赋值运算符与索引结合使用:

map1[q] = v1; 

注意:你在地图的定义中忘记了关闭>,但我猜这是一个错字

© www.soinside.com 2019 - 2024. All rights reserved.