Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator arithmetic

Tags:

c++

iterator

stl

In c++ STL, if I have an iterator it into a vector v, is it - v.begin() guaranteed to give me the index into the vector, so that *it == v[it - v.begin()]? If so, is this true for all random access iterators?

like image 258
Baruch Avatar asked Jul 01 '12 08:07

Baruch


People also ask

What is an iterator in C++?

An iterator is an object that can iterate over elements in a C++ Standard Library container and provide access to individual elements.

What is the datatype of iterator?

The type of it is map<string,int>::iterator , which is a class with a bunch of operators overloaded. For some container types, Container::iterator may be a raw pointer type.

What is an iterator in vector?

Vector's iterators are random access iterators which means they look and feel like plain pointers. You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [] . std::vector<int> vec(10); std::vector<int>::iterator it = vec.

Can we use iterator in vector?

Use an iterator vector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence.


1 Answers

Yes, it is, and it is true for all RA iterators.

like image 147
Puppy Avatar answered Oct 04 '22 01:10

Puppy