using the following code:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> ivec;
for(vector<int>::size_type ix = 0; ix != 10; ix++)
{
ivec.push_back(ix);
}
vector<int>::iterator mid = (ivec.begin() + ivec.end()) / 2;
cout << *mid << endl;
return 0;
}
I get an error compiling with g++:
iterator_io.cpp: In function `int main()':
iterator_io.cpp:13: error: no match for 'operator+' in '(&ivec)->std::vector<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>]() + (&ivec)->std::vector<_Tp, _Alloc>::end [with _Tp = int, _Alloc = std::allocator<int>]()'
/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/stl_iterator.h:654: note: candidates are: __gnu_cxx::__normal_iterator<_Iterator, _Container> __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator+(const typename std::iterator_traits<_Iterator>::difference_type&) const [with _Iterator = int*, _Container = std::vector<int, std::allocator<int> >]
/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/stl_bvector.h:261: note: std::_Bit_iterator std::operator+(ptrdiff_t, const std::_Bit_iterator&)
/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/stl_bvector.h:345: note: std::_Bit_const_iterator std::operator+(ptrdiff_t, const std::_Bit_const_iterator&)
/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/stl_iterator.h:765: note: __gnu_cxx::__normal_iterator<_Iterator, _Container> __gnu_cxx::operator+(typename __gnu_cxx::__normal_iterator<_Iterator, _Container>::difference_type, const __gnu_cxx::__normal_iterator<_Iterator, _Container>&) [with _Iterator = int*, _Container = std::vector<int, std::allocator<int> >]
I know the ivec.end() can not be used as a normal vector element. But I can’t understand what the error information means…something about operator+?
You cannot add two iterators together.
operator+is not defined for two iterators, because that operation wouldn’t make sense. Iterators are a kind of generalization over pointers – they point to the specific element stored in container. At which element the sum of iterators is pointing?However, when you use a vector, you can add integers to iterators, like that:
and that is why you have
candidates are: (...)in your error message, followed by some definitions ofoperator+.In your case the best, and cleanest way will be not using the iterators, but simple getting the value from specified position: