mardi 1 mai 2018

C++ .exe has stopped working, no errors while compiling. Using vectors

I am having a problem running my code, no errors are shown while compiling. The problem seems to be with the vectors. If I comment out the second half of the code and just run the "for loop", I can create a vector up to 4 numbers without running into "exe has stopped working".

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <numeric>


using namespace std;

int main() {


    vector<int> numbersVector; 
    vector<int> numbersVector2;

    int numbers; 
    cout << "Enter your desired numbers: " << endl; 

    while (cin >> numbers) {
        numbersVector.push_back(numbers);

    }

    int n = numbersVector.size();

    for (int i = 1 ; i <= n; i += 2) {
        int x = numbersVector.at(i);
        x = x * 2;

        if (x >= 10) {
            int x1 = x % 10;
            int x2 = 1;
            int x3 = x1 + x2; 
            numbersVector2.push_back(x3);
        }
        else{     
            numbersVector2.push_back(x);
        }
    }


    for (int i = 1; i <= n; i += 2) {
        numbersVector.erase(numbersVector.begin() + i);
    }

    int sumVect2 = accumulate(numbersVector2.begin(), numbersVector2.end(), 0);
    cout << "sum: " << sumVect2 << endl; 

    for (auto i = numbersVector2.begin(); i != numbersVector2.end(); ++i)
        cout << "vTwo: " << *i << endl;

    cout << endl;

    for (auto i = numbersVector.begin(); i != numbersVector.end(); ++i)
        cout <<"v: " << *i << endl;




    return 0;
}

Aucun commentaire:

Enregistrer un commentaire