[英]Accessing structs in a vector of lists
我有一個名為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);
提前致謝
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的元素,但是可以使用迭代器來迭代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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.