【问题标题】:Accessing structs in a vector of lists访问列表向量中的结构
【发布时间】:2018-09-21 22:09:32
【问题描述】:

我有一个名为 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 [] ()
  • 如果你需要直接访问,也许你需要一个vector的vector
  • 警惕 std::list。它实际上从来都不是向量的更好选择,即使向量导致 O(n) 惩罚的操作并不少见。 youtube.com/watch?v=YQs6IC-vgmo 链接的视频有 C++ 的创始人支持这个理由。

标签: c++ list vector struct


【解决方案1】:

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);
    }
}

【讨论】:

    【解决方案2】:

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

    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);
        }
    }
    

    【讨论】:

    • 啊哈,谢谢。是的,我刚刚意识到我不能像数组一样访问列表。必须使用迭代器
    • 你首先得到了答案。干得好!
    【解决方案3】:

    根据this somewhat dated referencelist 没有[] 运算符。相反,请尝试使用iterator

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

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 2010-11-13
      • 2018-04-04
      • 2012-01-14
      • 1970-01-01
      • 2014-06-26
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多