在循环中对向量进行排序

时间:2014-02-14 09:14:37

标签: c++ sorting gcc vector mingw

有时我非常喜欢c ++,有时会陷入我不理解的事情中。 我想在向量中的向量中对值进行排序。

工作原理:

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

什么行不通:

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

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

最后两个不起作用,我不知道为什么

我正在使用mingw64, c++11;

以下是完整示例:

#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;
}

输出:

i  vec1   vec2
0  1 5    2 4    
1  5 1    4 2    
2  5 1    4 2    

1 个答案:

答案 0 :(得分:10)

两个不起作用的版本是制作载体的副本,并对它们进行排序,保持外部矢量不变。您可以改为使用引用:

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

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