2
有時我非常喜歡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
你讓副本。你爲什麼期望他們工作? – Simple