【问题标题】:C++ Error project.cpp:11:20: error: no match for 'operator[]' (operand types are 'std::__cxx11::list<int>' and 'int')C++ 错误 project.cpp:11:20: error: no match for 'operator[]' (operand types are 'std::__cxx11::list<int>' and 'int')
【发布时间】:2021-04-04 09:39:23
【问题描述】:

好的,所以我对 c++ 比较陌生,我正在尝试通过 youtube 教程和网站进行自学。我要做的是列出一个列表,然后在列表中添加内容。在我尝试在列表中获取某些内容之前,这一直很好。我收到错误 project.cpp:11:20: error: no match for 'operator[]' (操作数类型是 'std::__cxx11::list' 和 'int')。不知道为什么会这样。

这是我的代码

#include <iostream>
#include <list>

using namespace std;

int main(){
    list <int> numbers;
    for (int i = 0;i < 10; i++){
        numbers.push_back(i);
}
cout << numbers[0];

return 0;
}

【问题讨论】:

  • std::list 不是随机访问,因此它没有 std::list::operator[] - 如果您想要随机访问,请改用 std::vector
  • list 不提供运算符[]。编译器会准确地告诉你。也许您正在寻找vector
  • 使用std::list front() b 获取列表的第一个元素(需要先检查它是否为空,否则可能会崩溃)
  • 既然你是自学c++,那你最好多看点书,有需要的时候查一下en.cppreference.com/w

标签: c++


【解决方案1】:

在 c++ 中,STL list 不支持 operator[]。这样做的原因是它被实现为一个喜欢的列表。这意味着每个项目只知道它之前和之后的元素在哪里。 list 看起来像 this

您不想通过大括号符号访问列表的给定部分,而是希望使用循环遍历列表,直到到达您想要的位置。

int count = 0;
for(auto iterator = list.begin(); iterator != list.end(); iterator++)
{
    if(count == inputNum)
    {
        // Do whatever you need, or save the iterator to perform operations on
        break;
    }
}

您也可以使用STL 方法advance。它接受一个迭代器和你想要移动它的距离:

std::list<int>::iterator iterator = list.begin();
std::advance(iterator, numPositions);

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2020-07-12
    相关资源
    最近更新 更多