简体   繁体   中英

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. 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;

adjacencyType adj(5000);

Then in the main function, you call push_back , assuming pi and qi are in bounds:

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.

Alternately, you could do this if you're using a C++11 compliant compiler:

adj[pi].push_back({qi, ri});
adj[qi].push_back({pi, ri});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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