1 year ago

#356905

test-img

Benjamin Chen

sorting vector leads to vector subscript out of range

I'm trying to sort the elements in a vector from smallest to biggest. My algorithm:

  1. Find the smallest number in the vector using least()
  2. Find all occurrences of the smallest number in the vector and copy them into another vector named result
  3. Delete those occurrences from the original vector
  4. Repeat until all elements from the original vector have been deleted

As the title suggests, I'm getting vector subscript out of range error. I tried debugging by printing out the indexes, but they seem correct.

An example you could input could be: 5 5 5 4 3 2 1 2

The program should output: 1 2 2 3 4 5 5

Here's my code:

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

int least(vector<int> groups) {
    int lowest = groups[0];
    for (int i = 0; i < groups.size(); i++) {
        //cout << i << endl;
        if (groups[i] < lowest) {
            lowest = groups[i];
        }
    }
    return lowest;
}

vector<int> sort(vector<int> groups) {

    vector<int> result;

    while (groups.size() != 0) {
        int smallest = least(groups);
        //cout << smallest << endl;
        for (int i = 0; i < groups.size(); i++) {
            if (groups[i] == smallest) {
                result.push_back(smallest);
            }
            //cout << i + " " + groups.size();
        }
        groups.erase(remove(groups.begin(), groups.end(), smallest), groups.end());
    }

    return result;
}

int main() //sort from least to greatest
{
    int t, n, taxiCount = 0, numOfChildren = 0;
    cin >> t;
    vector<int> groups, result;

    for (int i = 0; i < t; i++) {
        cin >> n;
        groups.push_back(n);
    }

    result = sort(groups);
    //cout << result.size();
    for (int i : result) {
        cout << i + " ";
    }
}

I know there are better ways to sort through a vector, but I'd like to stick to my way for now.

c++

sorting

stdvector

0 Answers

Your Answer

Accepted video resources