访问列表向量中的结构

Accessing structs in a vector of lists

本文关键字:结构 向量 列表 访问      更新时间:2023-10-16

我有一个名为 Edge 的结构列表向量

所以

vector<list<Edge>> adjA;

我的结构看起来像:

struct Edge {
int weight;
... 
}

假设我的 adjA 已经填充了边缘,我将如何访问这些边缘的变量?

vector<int>weights;
for(uint i = 0; i < adjA.size(); i++) //iterating through vector
{  for(uint j = 0; j < adjA[i].size(); j++) //iterating through list
{
weights.push_back(adjA[i][j].weight); //compiler error
} 
}

错误:

no match for ‘operator[]’ (operand types are ‘__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::list<Edge> > >::value_type {aka std::__cxx11::list<Edge>}’ and ‘uint {aka unsigned int}’)
weights.push_back(adjA[i][j].weight);

提前致谢

std::list没有operator [] ()

您可以使用基于范围的for循环:

for (const auto &edges : adjA)
{
for (const auto &edge : edges)
{
weights.push_back(edge.weight);
}
}

或迭代器:

for (auto it = adjA.begin(); it != adjA.end(); it++)
{
for (auto jt = it->begin(); jt != it->end(); jt++)
{
weights.push_back(jt->weight);
}
}

你不能用 [] 运算符访问 stl list 的元素,但是你可以使用迭代器来迭代列表:

vector<int>weights;
for(uint i = 0; i < adjA.size(); i++) //iterating through vector
{  
for (std::list<Edge>::iterator it = adjA[i].begin(); it != adjA[i].end(); ++it)
{
weights.push_back(it->weight);
}
}

根据这个有点过时的参考,list没有[]运算符。相反,请尝试使用iterator

for(std::list<Edge>::iterator it = adjA[i].begin(); it != adjA[i].end(); ++it)
{
weights.push_back(it->weight);
}