Tudor Gălățan Tudor Gălățan - 2 months ago 4x
C++ Question

I have a list of STL vectors and I want to sort them by the first element of each vector

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';

"T" is the number of vectors. The "sort" function is for sorting each vector, and I also need an another sort for sorting the vectors as I just described.


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

sort(sol.begin(), sol.end());

UP: It's written in the comments that you have an array of std::vector, not std::list<std::vector>. The array has no methods begin() and end(), so this exact code will not work. The solution is

sort(sol, sol + SIZE);

where SIZE is size of the part of the array you want to sort.