In C I got this error:
main.cpp:34:15: error: type 'list<std::string>' (aka 'list<basic_string<char>>') does not provide a subscript operator
cout << code[0];
~~~~^~
1 error generated.
make: *** [<builtin>: main.o] Error 1
Why? I thought square brackets were meant to get the data of an item of an list by index.
(code
is an list)
CodePudding user response:
list does not provide a subscript operator
That's correct, std::list
does not provide operator[]
. (std::vector
and std::array
both do so.)
It would have been possible for std::list
to provide an indexing operator, so that lst[10]
gives you the 10th (counting from 0) element of the list. But the operation would be O(N), so that lst[100]
would take about 10 times as long as lst[10]
, because it would have to traverse the list from the beginning to find the requested element. It would allow you to write code that's very inefficient while hiding the inefficiency.
If you're going to need indexing, use a std::vector
, std::array
, or something similar.
The C standard library provides an indexing operator only when the element can be accessed directly, without traversing the container.