I'm user of C++14. When I coded for sort two dimensional array using std::vector with compare fucntion. But it didn't work as I thought, finally I found something weird things. Let's see code below.
using namespace std; int n; vector<vector<int>> v; bool cmp(const vector<int>& l, const vector<int>& r){ return l[1] < r[1] ? true : l[0] < r[0]; } int main() { scanf("%d", &n); v.resize(n, vector<int>(2)); for (int i = 0; i < n; ++i) scanf("%d %d", &v[i][0], &v[i][1]); sort(v.begin(), v.end(), cmp); for(int i = 0; i < n; ++i) cout << v[i][0] << ' ' << v[i][1] << endl; return 0; } (Please ignore that I use scanf with cout. I'm doing on problem solving.) And here is input
11 1 4 3 5 0 6 5 7 3 8 5 9 6 10 8 11 8 12 2 13 12 14 I expected that output is exactly same with input without n, but the output is
0 6 1 4 2 13 3 5 3 8 5 7 5 9 6 10 8 11 8 12 12 14 Also I found the weird point when I change
v.resize(n, vector<int>(2); to
v.reserve(n); for(int i = 0; i < n; ++i) v[i].reserve(2); reserve makes code right as I wanted. I think I know the different with reserve and resize at vector but something is missing...
Would you teach me what is missing thing..?
meetingis undeclared.reservemakes code right as I wanted" - Reserving doesn't add elements to the vector, only raw memory. You are interacting with vectors that aren't there.cmpimplementation doesn't obey strict weak ordering (I don't think). That's undefined behaviour.