简体   繁体   中英

How to access the struct elements in a array of vectors of struct?

I am new to vectors, but they seem fairly straight forward. I am working off of a profs code and she is allocating an array of vectors[n]. I would like to be able to allocate the elements in the struct on each element in the array. The struct is called edge

struct edge {
   int vertex1;
   int vertex2;
   int weight;
};

Adj = new vector<edge>[n];

Now I want to be able to allocate vertex1, 2 and weight to each vector for each element of the array. I can't find the right syntax for this. something along the lines of:

Adj[1].vertex1 = 11;
Adj[1].vertex2 = 20; 
Adj[1].weight = 40;

however also specifying their location in the array. Thanks!!

If you want a new element to be inserted into the vector, you need to use push_back :

std::vector<edge> Adj;
Adj.push_back(Edge{11, 20, 40});

Either that, or you can pre-allocate a given number of elements (by passing the ctor the number of elements).

Note that C++ vectors are 0-indexed in the std library.

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