Reputation: 459
I have a vector of lists of structs named Edge
so,
vector<list<Edge>> adjA;
and my struct looks like:
struct Edge {
int weight;
...
}
Assuming my adjA is already filled with Edges, how would I accessing those edges' variables?
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
}
}
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);
Thanks in advance
Upvotes: 0
Views: 338
Reputation: 6125
std::list
doesn't have an operator [] ()
You can use range-based for
loops:
for (const auto &edges : adjA)
{
for (const auto &edge : edges)
{
weights.push_back(edge.weight);
}
}
Or iterators:
for (auto it = adjA.begin(); it != adjA.end(); it++)
{
for (auto jt = it->begin(); jt != it->end(); jt++)
{
weights.push_back(jt->weight);
}
}
Upvotes: 3
Reputation: 7980
According to this somewhat dated reference, list
doesn't have a []
operator. Instead, try using an iterator
:
for(std::list<Edge>::iterator it = adjA[i].begin(); it != adjA[i].end(); ++it)
{
weights.push_back(it->weight);
}
Upvotes: 0
Reputation: 3775
You can not access elements of stl list with [] operator, however you can use iterators to iterate 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);
}
}
Upvotes: 2