Reputation:
I have the simple code below:
#include <iostream>
#include <list>
#include <iterator>
using namespace std;
int main()
{
list<int> ints = { 3, 6, 1, 5, 8 };
int index;
index = 2;
std::list<int>::iterator it = ints.begin() + index;
cout << "Element at index " << index << " is " << *it << '\n';
return 0;
}
On compiling, it says:
error: no match for ‘operator+’ (operand types are ‘std::__cxx11::list::iterator’ {aka ‘std::_List_iterator’} and ‘int’)
std::list::iterator it = ints.begin() + index;
~~~~~~~~~~~~~^~~~~~~
I understand what the compiler is trying to say, but I am unsure how to resolve it. How do I convert the int
to an iterator
and get the element at that index? I did look for similar questions, but most of them seek the conversion in the opposite direction which can be done using std::distance
, while the remaining were for different containers.
Thanks for your help!
Upvotes: 0
Views: 2847
Reputation: 13269
Use std::next
.
If you think of distance
as the operator -
between two iterators, then next
, prev
, and advance
are respectively the +
, -
, and +=
between an iterator and an integer.
These functions are meant to treat all iterators the same way, even though the complexity of operations is different for different iterators. For a std::list
, which uses "forward iterators", these are all linear. For a std::vector
, which uses "random-access iterators", these are all constant.
Upvotes: 3
Reputation: 238411
Converting an integer to an iterator for std::list
Integers and iterators are quite separate concepts, so it is unclear what meaning such conversion would have. How does one convert a coconut into transitivity?
... and get the element at that index?
Now, this makes a bit more sense. List element do not have indices however. But presumably by index i
, you mean the i
th (zero based) successive element from beginning.
The standard library has a function for that: std::next
. What this does (with non-random access iterators) is increment the iterator for given number of repetitions in a loop. Intuitively, the asymptotic complexity of such operation is linear.
Upvotes: 1