iterator arithmetic, + operator does not work anymore.

Hello there!
So I'm trying to compute an iterator that points to the middle element of a vector

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec(10, 333);
  vector<int>::iterator mid = (vec.end() + vec.begin()) / 2;
  return 0;
}


This is supposed to work, right?
But I'm getting the following error:

error: invalid operands to binary expression ('iterator' (aka '__wrap_iter<pointer>') and 'iterator')
vector<int>::iterator mid = (vec.end() + vec.begin()) / 2;

Is it because of my current c++ version?

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin14.5.0
Thread model: posix

This is a basic operation I'm even seeing in a C++ book, yet it won't work. Could someone please explain to me what's going on?

Thanks,
If I were you, I would do it this way, it is much simpler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec(10, 333);
  
  for (int i=0;i<vec.size();i++)   // using for loop to see what's in my vector
  {
   cout << vec[i] << " ";   
  }
  
  int firstNum = vec[0];       // getting the first element of vector
  int lastNum = vec[vec.size()-1];    // getting the last element of vector
  int average = (firstNum + lastNum) / 2;      //calculating the average
  
  cout << endl;
cout << "Average is : " << average << endl;
 
  return 0;
}


Also, one more thing: You vector consists of 10 elements whose value is 333. So the average of them is the number itself which is 333. I used a for loop to print out all the elements of the vector.
Last edited on
This is supposed to work, right?

No, it's not. You can't add iterators to each other, and you can't divide iterators by some value.

On the other hand, you can subtract one from another...

vector<int>::iterator mid = vec.begin() + (vec.end() - vec.begin()) / 2;

But it's probably simper to say mid = vec.begin() + vec.size() / 2;

@newbiee999: You don't find the average of a 10 element array by averaging the first and last element. The average of the first and last in this case happens to also be the average of the array in this instance, but that isn't the case generally speaking.


Last edited on
@cire, Thank very much! Nice answer!
Topic archived. No new replies allowed.