I have a multimap consisting of a key that is a pair of ints and the values of the keys are float numbers.
Now I want to have the 2 biggest values for all my keys.
In my example the Key (1, 1) should result in Value 5.8 and 3.7.
Key (2, 2) should result in 2.4 and 1.5.
To point it out: I don't know the number and appearance of my keys. So I don't know if key (2, 2) exists.
Here is the code:
int main(int argc, char** argv)
{
// Create some values - both vectors have the same size
// The pairs and the thetas may be unsorted
vector<pair<int, int>> pairs;
pairs.push_back(make_pair(1, 1));
pairs.push_back(make_pair(1, 1));
pairs.push_back(make_pair(1, 1));
pairs.push_back(make_pair(2, 2));
pairs.push_back(make_pair(2, 2));
pairs.push_back(make_pair(3, 3));
pairs.push_back(make_pair(3, 3));
pairs.push_back(make_pair(1, 1));
vector<float> theta;
theta.push_back(1.4);
theta.push_back(2.4);
theta.push_back(3.7);
theta.push_back(2.4);
theta.push_back(1.5);
theta.push_back(1.6);
theta.push_back(2.4);
theta.push_back(5.8);
multimap<pair<int, int>, float> similarities;
for (size_t i = 0; i < pairs.size(); i++) {
similarities.insert(make_pair(make_pair(pairs[i].first, pairs[i].second), theta[i]));
}
}
In my specific case I don't know which key pairs are defined in my multimap.
I think also that perhaps multimap is not the right choice but I am not sure what's a better type.
I have tried to keep the vector format of theta but then it is hard to keep track of the related pairs.
I hope that I got you right:
auto range = similarities.equal_range(make_pair(1,1));
size_t found = 0; float highest, second_highest;
if (range.first != similarities.end() && range.first != range.second) {
++found;
highest = (*std::max_element(range.first++, range.second)).second;
if (range.first != range.second) {
++found;
second_highest =
(*std::max_element(range.first++, range.second, [&](auto a, auto b){ return a.second < b.second && b.second < highest; })).second;
}
}
if (found > 0)
std::cout << highest<< std::endl;
if (found > 1)
std::cout << second_highest << std::endl;
The above would not give you the same value twice though.