我有一个名为Edge的结构列表的向量
所以
vector<list<Edge>> adjA;
我的结构如下:
struct Edge {
int weight;
...
}
假设我的adjA已经充满Edges,我该如何访问这些Edge的变量?
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);
预先感谢
答案 0 :(得分:3)
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);
}
}
答案 1 :(得分:2)
您无法使用[]运算符访问stl list的元素,但是可以使用迭代器来迭代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);
}
}
答案 2 :(得分:0)
根据this somewhat dated reference,list
没有[]
运算符。而是尝试使用iterator
:
for(std::list<Edge>::iterator it = adjA[i].begin(); it != adjA[i].end(); ++it)
{
weights.push_back(it->weight);
}