I want to define an array of vectors in c++. Normally I can do it like this:
vector <pair<int,int> > G[100];
I have a function that read data from a file.
My first problem is that I want to define G with size V that read from a file and G should define in main but calling a function with an uninitialized pointer can't work.
My Second problem is when I define G like this:
vector <pair<int, int> > *G;
G = new vector <pair<int, int>>[10];
it doesn't read data correctly (it doesn't work correctly).
Here is my code:
void readData(vector <pair<int, int> > *G)
{
int V, E;
ifstream file("input.txt");
file >> V >> E;
//G = new vector <pair<int, int>>[V]; //my problem
for (int i = 0; i < E; i++)
{
int u, v, w;
file >> u >> v >> w;
G[u - 1].push_back(make_pair(v - 1, w));
G[v - 1].push_back(make_pair(u - 1, w));
}
file.close();
}
int main() {
vector <pair<int, int> > *G;
G = new vector <pair<int, int>>[10]; // my problem
MST = new vector <pair<int, int>>;
readData(G);
}
Example data:
5 6
1 3 4
1 2 3
2 4 6
4 3 5
4 5 20
5 2 21
and this code is working correctly and read data from console:
const int N=10;
vector <pair<int,int> > G[N];
int main() {
cin >> V>>E;
for(int i=0; i<E; i++){
int u,v,w;
cin >>u>>v>>w;
G[u-1].push_back(make_pair(v-1,w));
G[v-1].push_back(make_pair(u-1,w));
}
}
Vectoras pointer, but instead use a reference. * Why should one create an array of vecs? Could you give please the usecase for this? Use a hashmap if you want a key-value relationship, or astd::arrayfor a fixed array.std::vector<std::vector<std::pair<int,int>>> G;.G.G.data()to pass the internal array that the vector manages.