Suppose I have a vector<int> v1 = {some set of integers} and I want to add the 0 and the last index, 1 and the last - 1 index, and so on. How can de-reference the last index?
1 2 3 4 5 6
for (auto it = v1.begin(); it != v1.begin() + (v1.end() - v1.begin())/2;
++it) {
cout << "The sum of indices " << it - v1.begin() << " and "
<< v1.end() - it << " is ";
// << *it + *(v1.end() - it) << endl;
}
The following code
v1.end() - it
prints out the last index, but I can't figure out how to de-reference it; therefore, I am unable to add the values for the specified indices.
I have made progress but haven't yet achieved the desired results.
1 2 3 4 5 6
auto j = v1.end() - v1.begin() - 1;
for (auto it = v1.begin(); it != v1.begin() + (v1.end() - v1.begin())/2;
++it) {
cout << "The sum of indices " << it - v1.begin() << " and "
<< v1.end() - it << " is " << *it + *(j - it) << endl;
}
I need to subtract j from it, but if I do, I am met with:
1 2 3
no match for ‘operator-’ (operand types are
‘longint’ and ‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’)
<< v1.end() - it << " is " << *it + *(j - it) << endl;
If I subtract it from j, there are no errors but this isn't correct. How can the operators not match when it is j - it but be okay when it is it - j?
> How can the operators not match when it is j - it but be okay when it is it - j?
Iterators have pointer like semantics.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
int a[20]{} ;
int* it = a + 10 ;
*(it-5) == 8 ; // fine: a[10-5] == 8 ;
// for pointer addition, any one of the two operands is a pointer type
// and the other operand is a numeric type
*(15-it) == 0 ; // *** error: invalid operands to binary -
// for pointer subtraction,
// the left operand must be a pointer type and the right operand a numeric type
// (or both operands must be pointers)
}
@JlBorges, this is the output from the GCC compiler when I compile the code:
1 2 3
error: no match for ‘operator-’ (operand types are
‘longint’ and ‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’)
<< v1.end() - it << " is " << *it + *(j - it) << endl;
but since I defined j as
auto j = v1.end() - v1.begin - 1;,
j will be larger than it. I want to add the last item and the first, second to last and the second, and so on. With that being the case, j - it > 0 and it - j < 0.