插入到具有类型<int,矢量>的映射中<int>

Inserting into map with types <int, vector<int>>

本文关键字:gt lt int 映射 矢量 类型 插入      更新时间:2023-10-16

我有这个代码:

map< int , vector< int>> testmap;
vector<int> testvector;
testvector.push_back(10);
testmap.insert(1, testvector);

这段代码给了我一个错误,告诉我没有重载函数来匹配参数列表。

谁能告诉我为什么会这样?我正在尝试将矢量插入地图,但这种方法似乎不起作用。

没有与您

传递的参数匹配的std::map::insert重载。这将起作用:

auto p = testmap.insert(std::make_pair(1, testvector));
std::cout << std::boolalpha;
std::cout << "Did insert succeed? " << p.second << std::endl;

如果映射中没有具有键1的元素,这将成功。

testmap.insert(1, testvector);

你可能打算这样做

testmap[1] = testvector;

相反。

由于您使用的是 C++11(如您使用 >> :) 所示),因此您也可以使用 emplace .

testmap.emplace(1, testvector);

试试

testmap.insert({1, testvector});