繁体   English   中英

在列表向量中访问结构

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM