0

I want to take iterator from const std::vector<T>, but cannot find a way to explain that to the compiler. This is how could it look like:

(const std::vector<T>)::iterator

The workaround: typedef or using

template<typename T>
using const_vec = const std::vector<T>;
const_vec::iterator ...

Update. std::vector::iterator is example. The question is about C++ syntax.

kyb
  • 7,233
  • 5
  • 52
  • 105

3 Answers3

2

The const qualifier does not change anything about the definition of the type. So the iterator type in const std::vector<T> is the same as in std::vector<T>. Just use

std::vector<T>::iterator

or, if T is a template parameter, making this a dependent name:

typename std::vector<T>::iterator

You probably don't want iterator though, because there is no function of std::vector<T> that could return an iterator on a const qualified instance. You probably want const_iterator instead.

Generally you don't need to access the iterator type aliases anyway. You can obtain the correct type from auto in a variable definition:

const std::vector<T> vec{/* ... */};
auto it = vec.begin();

or with decltype if you need the type itself:

const std::vector<T> vec{/* ... */};
using iterator = decltype(vec.begin());
walnut
  • 21,629
  • 4
  • 23
  • 59
0

You can use std::vector<int>::const_iterator like:

const std::vector<int> v{ 1, 2, 3, 4, 5 };
std::vector<int>::const_iterator it = v.begin();

or just take advantage of auto like:

const std::vector<int> v{ 1, 2, 3, 4, 5 };
auto it = v.begin();
NutCracker
  • 11,485
  • 4
  • 44
  • 68
0

You should read the documentation vector.begin()

Marcel Zebrowski
  • 947
  • 10
  • 17