I have a list of vectors from STL. They have different lengths and I want to sort them by the first element of each vector. For example, I have the vectors: 4 4 5 6 10, 1 8, 2 2 3 and 3 1 7 9. The first number is the size of each vector and it is followed by the vector's elements. I want to display the vectors in a file, sorted by the first element. In this example, my vectors should display in this order: 3 1 7 9, 2 2 3, 4 4 5 6 10 and 1 8.
Here is my code:
ofstream fout ("retele.out");
fout << T << '\n';
for (i=1; i<=T; i++)
fout << sol[i].size() << ' ';
for (j=0; j<sol[i].size(); j++)
fout << sol[i][j] << ' ';
fout << '\n';
A small clarification for other answers: the
std::vector<T> already has
operator< with exactly the same behavior as you described (cplusplus description).
template < class T, class Alloc > bool operator < (const vector<T, Alloc>& lhs, const vector<T, Alloc>& rhs);
The less-than comparison (operator<) behaves as if using algorithm lexicographical_compare, which compares the elements sequentially using operator< in a reciprocal manner (i.e., checking both a < b and b < a) and stopping at the first occurrence.
So, you can just write
UP: It's written in the comments that you have an array of
std::list<std::vector>. The array has no methods
end(), so this exact code will not work. The solution is
sort(sol, sol + SIZE);
SIZE is size of the part of the array you want to sort.