Finding max element in a list, but handle duplicates?
Suppose I have a vector/list of integers. What is the best way to get another list which contains the max number in that list, but include the duplicates? For example: max([1, 2, 3, 3, -6]) -> [3, 3] max([1, 3, 1]) -> [3] This is my code: std::vector<int> max(std::vector<int>& vec) { std::vector<int> result; int max = vec[0]; for (auto& v : vec) { if (v > max) { result.clear(); result.push_back(v); max = v; } else if (v == max) { result.push_back(v); } } return result; } Basically I'm going over the vector, checking if the current value is bigger than max, and if it is, I reset the result vector, push the new value and set the new max. If it is the same as the current max, i push back the current value. Is this the best way to do it? I'm sure there are other ways... P.S my actual code doesn't work with a vector as the input but with an unordered map, doesn't matter though