Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting vectors in a loop

Sometimes I like c++ very much and sometimes get stuck in things I do not understand. I want to sort values in a vector in vectors.

What is working:

for (unsigned int i = 0; i < myVectors.size(); i++) {
    sort(myVectors[i].begin(), myVectors[i].end());
}

What does not work:

for (unsigned int i = 0; i < myVectors.size(); i++) {
    vector<int> vec = myVectors[i];
    sort(vec.begin(), vec.end());
}

and:

for (auto vec : myVectors) {
    sort(vec.begin(), vec.end());
}

The last two don't work and I don't know why

I am using mingw64, c++11;

Here is the full example:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    cout << "i  vec1   vec2" << endl;
    for (int i = 0; i < 3; i++) {

        // create vectors
        vector<int> vec1;
        vec1.push_back(5);
        vec1.push_back(1);

        vector<int> vec2;
        vec2.push_back(4);
        vec2.push_back(2);

        vector<vector<int>> myVectors;
        myVectors.push_back(vec1);
        myVectors.push_back(vec2);

        switch(i) {
        case 0:
            for (unsigned int i = 0; i < myVectors.size(); i++) {
                sort(myVectors[i].begin(), myVectors[i].end());
            }
            break;
        case 1:
            for (unsigned int i = 0; i < myVectors.size(); i++) {
                vector<int> vec = myVectors[i];
                sort(vec.begin(), vec.end());
            }
            break;
        case 2:
            for (auto vec : myVectors) {
                sort(vec.begin(), vec.end());
            }
            break;
        }

        cout << i << "  ";
        for (auto vec: myVectors) {
            for (int i : vec) {
                cout << i << " ";
            }
            cout << "   ";
        }
        cout << endl;

    }
    return 0;
}

Output:

i  vec1   vec2
0  1 5    2 4    
1  5 1    4 2    
2  5 1    4 2    
like image 238
Viatorus Avatar asked May 08 '26 16:05

Viatorus


1 Answers

The two versions that don't work are making copies of the vectors, and sorting these, leaving your outer vector unchanged. You can use references instead:

for (unsigned int i = 0; i < myVectors.size(); i++) {
    vector<int>& vec = myVectors[i];
    sort(vec.begin(), vec.end());
}

and

for (auto& vec : myVectors) {
    sort(vec.begin(), vec.end(), pointCompare);
}
like image 149
juanchopanza Avatar answered May 11 '26 07:05

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!