Search code examples
c++vectorerase

C++ How can I delete -1 from my vector?


I currently have this code that does bubble sort:

#include <iostream>
#include <vector>
using namespace std;

void bubbleSort(vector<int>& numbers){
    bool notFin = true;
    int temp = 0;
    while(notFin){
        notFin = false;
        for (int i = 0; i< numbers.size(); i++) {
            if (numbers[i]>numbers[i+1] ){
                temp = numbers[i];
                numbers[i] = numbers[i+1];
                numbers[i+1] = temp;
                notFin = true;
            }
        }
    }
}

void printVector(vector<int>& numbers){
    for (int i=0;  i<numbers.size();  i++) {
        cout<<numbers[i]<<" ";
    }
  cout<<endl;
}

int main() {
    vector<int> numbers;
    int n = 0;

    cout << "enter integers to bubble sort end with -1\n";
    while (n != -1) {
        cin >> n;
        numbers.push_back(n);
    }
    numbers.pop_back();

    printVector(numbers);
    bubbleSort(numbers);
    printVector(numbers);
}

How ever when i output the results i still see -1 at the front and the highest value disappears. How can I delete -1 from the vector so that it does not output after the second print and push out the highest value in the vector?


Solution

  • You're accessing outside the vector. When you get to the last iteration of the for loop in bubbleSort(), numbers[i] is the last element of the vector, and numbers[i+1] is outside. This results in undefined behavior, and in your case it happens to access the -1 that you initially put in the vector and then popped out.

    Change the loop to use i < numbers.size()-1 as the repeat test.

    You can also fix your input loop so you don't put -1 in the vector in the first place.

    while (cin >> n && n != -1) {
        numbers.push_back(n);
    }