访问列表向量中的结构
Accessing structs in a vector of lists
我有一个名为 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 [] ()
您可以使用基于范围的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 的元素,但是你可以使用迭代器来迭代列表:
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);
}
相关文章:
- 将结构向量排序为子组
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 如何在 c++ 中创建结构向量的映射
- 带unique_ptr的结构向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么
- C++对结构向量进行排序
- 在C++中对结构向量进行排序时出现问题
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 搜索并替换结构向量中的值
- 在结构向量中查找最接近的值
- 清除结构向量时会发生什么?
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 对结构向量进行两次排序
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 如何二进制搜索结构向量并在适当的索引处插入
- 结构向量中自定义结构函数的内存使用
- C++11-在结构向量中修改结构的成员
- 我正在尝试找到一个特定的结构成员,该成员是使用 lambda 函数的结构向量
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员