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).

  • 2
    I would probably do it in 2 passes through the array. 1 - find the maximum. 2 - find positions. But I think it is better to write all the options, the benefit is written quickly and compare. - pavel
  • boost::multi_index may be suitable - Slava Zhuyko

1 answer 1

At first I thought that it was faster to find the maximum element with one cycle (or with a ready-made algorithm), and then with another position cycle. But I think your algorithm is the best option. It works in one pass through the array. The sorting option disappears immediately, the sorting works much longer than a single cycle cycle, and you also have to store positions other than the elements ... I also think the third option is not very good.

  • And you measure :) it is not much better ideone.com/gcH7o3 difference within the margin of error. - pavel