[英]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].
我正在处理一个教授代码,她正在分配一个向量数组[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.现在我希望能够为数组的每个元素的每个向量分配顶点 1、2 和权重。 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
:如果要将新元素插入向量中,则需要使用
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).或者,您可以预先分配给定数量的元素(通过将元素数量传递给 ctor)。
Note that C++ vectors are 0-indexed in the std
library.请注意,C++ 向量在
std
库中的索引为 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.