将一对插入到映射的向量中时出现视觉C++错误

visual C++ error when inserting a pair into vector of maps

本文关键字:视觉 错误 C++ 向量 插入 映射      更新时间:2023-10-16

我正在尝试使用映射向量创建一个图。事实上,我正在看一本书中的代码,并试图将其输入到2012年的visual Studio中,这样我就可以处理图形了。但由于某种原因,它不允许我在向量中添加一对。低于的代码

创建矢量

//vector that holds a map of all adjacent vertices
vector<map<int, int> > adjList;

图类的构造函数

Graph::Graph(int n){
    map<int, int> element;
    adjList.assign(n, element);
}

将项目添加到矢量

int v1 = e.v1;
int v2 = e.v2;
int weight = e.weight;
//add the first vertix the edge connects to intto the adjList
adjList.insert(make_pair(v1, weight));
//add the second vertix the edge connects to into the adjList
adjList.insert(make_pair(v2, weight));

错误我得到的视觉工作室2012当试图编译

Error   1   error C2661: 'std::vector<_Ty>::insert' : no overloaded function takes 1 arguments  c:userselliotdocumentsvisual studio 2012projectsgraphgraph.cpp   25  1   Project1
Error   2   error C2661: 'std::vector<_Ty>::insert' : no overloaded function takes 1 arguments  c:userselliotdocumentsvisual studio 2012projectsgraphgraph.cpp   27  1   Project1

我想我可以在评论中说清楚,但让我们更详细一些。你有一个地图矢量。您正试图将一对某些值插入到一个映射向量中。当然,这是不可能的(这不是python)。你应该也可以这样做:

adjList[0].insert(make_pair(v1, weight));

或者任何其他需要插入的索引。

看看这个。

我猜如下。每个节点都是一个数字(它的id是一个整数)。所以,用这个数字,你索引一个向量,得到它的邻接列表。相邻列表是一张地图。地图中的每个条目都是另一个邻居的id,可能还有边缘的长度。例如,如果你想要ID为3的节点的邻居,你会要求adjList[2](它们可能是从0开始索引的),并获得它的邻居的映射。

insert成员函数采用两个参数:一个位置和一个值。如果您不关心指定位置,那么只需使用push_back函数。您可能还有其他问题,例如类型问题,但这是您的直接问题。

你不应该认为你的编译器在胡言乱语。它告诉你到底出了什么问题:

没有重载函数需要1个参数

快速浏览一下方便的参考资料,看看它是正确的:

iterator insert (const_iterator position, const value_type& val);
iterator insert (const_iterator position, size_type n, const value_type& val);  
template <class InputIterator>
iterator insert (const_iterator position, InputIterator first, InputIterator last); 
iterator insert (const_iterator position, value_type&& val);
iterator insert (const_iterator position, initializer_list<value_type> il);