[英]How do I insert a pair into a specific position of vector?
I am trying to make an adjacency list for a tree using pairs and vectors.我正在尝试使用对和向量为树制作邻接列表。 However, I am running into a few problems when trying to implement it.但是,我在尝试实现它时遇到了一些问题。 This is a visualization of what I am trying to accomplish - a vector of pairs.这是我想要完成的可视化 - 对的向量。
This is my current code, based on the solution here这是我当前的代码,基于这里的解决方案
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 5000;
//Define main variables
int N, Q, pi, qi, ri;
vector<pair<int, int>> adj[MAXN];
int main(){
//Read Input
ifstream fin("mootube.in");
ofstream fout("mootube.out");
fin >> N >> Q;
for(int i=0; i<N; i++){
fin >> pi >> qi >> ri;
pi--;qi--;
adj[pi].insert(make_pair(qi, ri));
adj[qi].insert(make_pair(pi, ri));
}
return 0;
}
After declaring vector adj
with a maximum space of 5000, I am iterating through some input to construct the adjacency list.在声明了最大空间为 5000 的向量adj
之后,我正在迭代一些输入以构造邻接表。 I believe the problem I am facing is with how I insert the pairs into the vector.我相信我面临的问题是如何将对插入向量中。
When I try the above code, I am met with an error that says当我尝试上面的代码时,我遇到了一个错误,上面写着
error: request for member 'size' in 'adj', which is of non-class type 'std::vector<std::pair<int, int> > [5000]'
I have also tried我也试过
adj.insert(adj.begin() + pi, make_pair(qi, ri));
adj.insert(adj.begin() + qi, make_pair(pi, ri));
Which is quickly met with the following error -很快遇到以下错误 -
error: request for member 'size' in 'adj', which is of non-class type
Any help would be appreciated.任何帮助,将不胜感激。
First, break down your illustration into components that are easily handled:首先,将您的插图分解为易于处理的组件:
using prtype = std::pair<int, int>;
using vectPairs = std::vector<prtype>;
Now you want a vector of the above to represent the adjacency matrix:现在你想要一个上面的向量来表示邻接矩阵:
using adjacencyType = std::vector<vectPairs>;
Now you want to create 5000 rows of the adjacency matrix;现在您要创建 5000 行的邻接矩阵;
adjacencyType adj(5000);
Then in the main
function, you call push_back
, assuming pi
and qi
are in bounds:然后在main
function 中,您调用push_back
,假设pi
和qi
在范围内:
adj[pi].push_back(make_pair(qi, ri));
adj[qi].push_back(make_pair(pi, ri));
The above adds data to row pi
and qi
of the adjacency matrix.上面将数据添加到邻接矩阵的pi
和qi
行。
Alternately, you could do this if you're using a C++11 compliant compiler:或者,如果您使用的是 C++11 兼容编译器,则可以这样做:
adj[pi].push_back({qi, ri});
adj[qi].push_back({pi, ri});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.