There is a certain class
class A { // Какой-то в меру сложный класс } In class A there are several small containers of elementary types (small - 4 - 15 elements). For A given comparison operators
bool operator==(const A& lhs, const A& rhs); // другие операторы (>, < и т.д.) There is a list (vector) of objects A
typedef std::vector<A> ListA; Important! - the maximum number of items in the list is 10 (i.e. small)
It is required to find positions of all maximal elements of the list. I solved the problem as follows:
std::vector<size_t> findHighestElements(const ListA &list) { std::vector<size_t> v; v.reserve(list.size()); v.push_back(0); for (size_t i = 1; i < list.size(); ++i) { if (list[i] > list[v[0]]) { v.clear(); v.push_back(i); } else if (list[i] == list[v[0]]) { v.push_back(i); } } return v; } In principle, the problem can be solved using STL algorithms: 1) Using std::max_element 2) Pre-sorting the list of std::sort 3) Using the initially ordered container (but you will have to save the initial positions of the elements)
The problem is that despite the small size of the list, this operation (search for maximum elements) needs to be performed many times (millions of list options). The question is, what will be faster?
PS The documentation says that std::vector<A>::clear() has linear complexity in the number of elements. If A has a complex destructor, this is understandable, you need to call destructors for all elements. And if A is an elementary type? Will the complexity be constant (it is known that clear() does not change the capacity )? Actually, in my algorithm, I am confused only by this moment (N calls clear() in the worst case).
boost::multi_indexmay be suitable - Slava Zhuyko