简体   繁体   English

C++ 如何从我的向量中删除 -1?

[英]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.然而,当我输出结果时,我仍然会在前面看到 -1 并且最大值消失了。 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?如何从向量中删除 -1 以使其在第二次打印后不输出并推出向量中的最大值?

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.当您到达bubbleSort() for循环的最后一次迭代时, numbers[i]是向量的最后一个元素,并且numbers[i+1]在外面。 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.这会导致未定义的行为,在您的情况下,它碰巧访问了您最初放入向量中然后弹出的-1

Change the loop to use i < numbers.size()-1 as the repeat test.更改循环以使用i < numbers.size()-1作为重复测试。

You can also fix your input loop so you don't put -1 in the vector in the first place.您还可以修复您的输入循环,这样您就不会首先将-1放入向量中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM