C ++: how to exclude symmetric pairs in a for loop

I wrote a program that sums the first and last indices of a vector. That is, it prints v1[k] + v1[v1.size() - 1 - k]

where it k

iterates over the indices. If the user enters a vector of even size, I select symmetrical pairs; for example, the program will print v1[0] + v1[last]

and v1[last] + v1[0]

, but those two are exact, so I would like to exclude them. The code I wrote is:

#include <vector>
#include <iostream>

using std::vector;
using std::cin;
using std::cout;
using std::endl;

int main(int argc, char *argv[]) {
  vector<int> v1;  // initialize v1 as an empty int vector
  int i = 0;       // initialize i as int 0
  // prompt user for inputs
  cout << "Enter in a set of integers:" << endl;
  while (cin >> i) {
    v1.push_back(i);  // at run time populate the vector with ints
  }
  for (unsigned k = 0; k != v1.size() && k != v1.size() - 1 - k; ++k) {
    cout << "The sum of the " << k << " and " << v1.size() - 1 - k
         << " indices are:" << v1[k] + v1[v1.size() - 1 - k] << endl;
  }
  return 0;
}

      

After the prompt, if I go into 1,2,3,4

and press crtl+ dto end the loop while

, the output is:

The sum of the 0 and 3 indices are:5
The sum of the 1 and 2 indices are:5
The sum of the 2 and 1 indices are:5
The sum of the 3 and 0 indices are:5

      

+3


source to share


1 answer


Instead of iterating over the entire vector, just iterate to the middle.



for (unsigned k = 0; k < (v1.size() + 1) / 2; ++k) {
    cout << "The sum of the " << k << " and " << v1.size() - 1 - k
         << " indices are:" << v1[k] + v1[v1.size() - 1 - k] << endl;
}

      

+2


source







All Articles