为什么列表不像 C++ 中的数组那样工作

why list doesn't work similar like array in c++

为什么我的代码没有在 l[0] 中打印值 2?

#include <bits/stdc++.h>
using namespace std;
list<int> l;
int main()
{
    l.push_back(2);
    cout<<l[0];
    return 0;
}

在 C++ 中,List 容器被实现为 doubly-linked 列表。它们 excel 在插入和移动元素时表现出色,但必须遍历它们。他们无法通过位置直接访问元素。

您可能更希望拥有 vector。向量允许直接访问:

vector<int> l;
int main()
{
    l.push_back(2);
    cout << l[0];
    return 0;
}