I'm interested to understand why my C++ program is producing a segmentation fault. The task is to insert elements into a vector and to add the adjacent elements stored in such vector. The problem arises when there is an odd number of elements in the vector. I eventually got my program to work by changing idx != numbers.size() to idx < numbers.size() or idx <= numbers.size()-1. This allows the conditional statement for odd numbers to be passed and prints the last element instead of attempting an addition. Why does != not work in this instance and lead to the seg fault?
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
int main(){
vector<int> numbers = {1, 2, 3, 4, 5};
int tmp;
/*while(cin >> tmp){
numbers.push_back(tmp);
}*/
for(decltype(numbers.size()) idx = 0; idx < numbers.size(); idx+=2){
if((numbers.size() % 2 != 0) && (idx == numbers.size() - 1)){
cout << numbers[idx] << endl;
}
else{
cout << numbers[idx] + numbers[idx+1] << " ";
}
}
cout << endl;
return 0;
}