+ 2

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

5th Dec 2020, 11:35 PM
inxanedev!
inxanedev! - avatar
4 odpowiedzi
+ 3
To find the max element...I'd be using max_element from the <algorithm> header file...(just remember to de-reference it as you assign in to a variable)...then just loop through your vector as you've done, compare and push_back as necessary.
6th Dec 2020, 12:32 AM
rodwynnejones
rodwynnejones - avatar
+ 2
6th Dec 2020, 4:16 AM
Ipang
+ 2
Flash looks alright but as I mentioned I can't sort the values because I'm using an std::unordered_map. I got my code working and a little better though, so thanks for your contribution.
6th Dec 2020, 9:15 AM
inxanedev!
inxanedev! - avatar
+ 1
inxanedev! not that elegant #include <iostream> #include <vector> #include <algorithm> #include <functional> std::vector<int>& m(std::vector<int>& in, std::vector<int>& out) { std::sort(in.begin(), in.end(), std::greater<>()); int e = in.at(0); for (int& i : in) { if (i == e) { out.push_back(i); } else { break; } } return out; } std::ostream& operator<<(std::ostream& os, std::vector<int>& v) { for (auto& i : v) { os << i << ' '; } os << '\n'; return os; } int main() { std::vector<int> in{ 2,1,4,5,4,4,5,3,5,4}; std::vector<int> out{}; std::cout << m(in, out); return 0; } https://code.sololearn.com/cULtnX1t8xrM/?ref=app
6th Dec 2020, 2:57 AM
Flash