EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto
. This is my current favorite solution
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
ORIGINAL ANSWER:
Just use a custom comparator (it's an optional 3rd argument to std::sort
)
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
If you're using a C++11 compiler, you can write the same using lambdas:
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
EDIT: in response to your edits to your question, here's some thoughts ...
if you really wanna be creative and be able to reuse this concept a lot, just make a template:
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
then you can do this too:
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
or even
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
You don't have to write a completely new container class. You can stick with your STL containers, but change the second parameter of for example std::vector
to give it your custom allocator which allocates from a stack-buffer. The chromium authors wrote an allocator just for this:
https://chromium.googlesource.com/chromium/chromium/+/master/base/stack_container.h
It works by allocating a buffer where you say how big it is. You create the container and call container.reserve(buffer_size);
. If you overflow that size, the allocator will automatically get elements from the heap (since it is derived from std::allocator
, it will in that case just use the facilities of the standard allocator). I haven't tried it, but it looks like it's from google so i think it's worth a try.
Usage is like this:
StackVector<int, 128> s;
s->push_back(42); // overloaded operator->
s->push_back(43);
// to get the real std::vector.
StackVector<int, 128>::ContainerType & v = s.container();
std::cout << v[0] << " " << v[1] << std::endl;
Best Answer
std::remove
does not actually erase the element from the container, but it does return the new end iterator which can be passed tocontainer_type::erase
to do the REAL removal of the extra elements that are now at the end of the container: