C++ vector sorting put simply
Ok, I have a vector< vector < long >>
, and I want to sort the innermost vectors from smallest to largest - i.e. I expect to have so开发者_开发技巧rted vector < long >
looking like 3,7,21 when sorted.
This has been asked before, but I want to do this very simply so that non-programmers can understand. I've seen that I can create a function or functor to sort as in this question. Is there a way to do this without creating an extra sorting function? I'm doing this as part of a class, and I'm hoping for a way to do this without having to have people hunting all over my code for the simple sorting function.
One possibility is that there may be some way to define the sorting function inside the class function, but this may not be allowed in C++.
Getting back to the point: I've seen several ways to do this, I'm wondering what the simplest way(s) are to sort a vector of integers. Any help is greatly appreciated, as this will probably help out much more than it may seem.
The std::sort function uses the std::less<T>
function for the default ordering. To get reverse order, explicitly use the std::greater<T>
function instead.
I'd just use a loop to go through the outer vector, then sort each inner vector separately. Unless I'm misunderstanding the question.
If you want only the internal vectors sorted, then you can simply use the default sorting order:
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<vector<long>> v;
for (auto i = v.begin(); i != v.end(); ++i)
sort(i->begin(), i->end());
return 0;
}
This example uses the latest version of the standard. An example for older C++ compilers would be a little more verbose.
You can't define functions in-line in C++03. The newest versions of GCC and MSVC support C++0x lambda functions, which you can use for this purpose.
I think this should be pretty close
#include <vector>
#include <algorithm>
std::vector< std::vector < long >> list;
std::vector< std::vector < long >>::iterator i;
for ( i = list.begin(); i != list.end(); ++i )
std::sort( (*i).begin(), (*i).end() );
精彩评论