I am trying to add the elements from a map
to a pair vector
, and then sort the vector according to the value, but i dont want to add elements that have the same value, and i can't figure out how to make such an if statement.
The map contains the amount of times a word was repeated in the input in main()
and the word itself, and i want to sort the vector that has the map elements, but i dont want to repeat words that have been repeated the same amount of times.
This is what i have so far:
bool compara(pair<string, unsigned int>& a,
pair<string, unsigned int>& b)
{
return a.second > b.second;
}
void sortP(map<string, unsigned int> &M, unsigned int x)
{
vector<pair<string, unsigned int> > A;
for (auto& it : M) {
if(find(A.begin(), A.end(), it.second) == A.end()) // this is the part that
A.push_back(it); // doesn't work
}
sort(A.begin(), A.end(), compara);
for (auto& it : A) {
cout << it.second << "\t"
<< it.first << endl;
}
cout << endl << endl;
// this is where i want to output the element of the vector that appears on the 'x'
// position, after it was sorted
}
I apologize if the terminology isn't exactly correct, i have just started getting accustomed to working with maps
and pairs
.
CodePudding user response:
Since you are searching through a vector
of pair
s, you need to use std::find_if()
instead of std::find()
to find a vector
element that matches a particular field of the pair
, eg:
for (auto& it : M) {
if (find_if(A.begin(), A.end(), [&](pair<string, unsigned int>& p){ return p.second == it.second; }) == A.end())
A.push_back(it);
}
Alternatively, you could just use another map
instead of a vector
, using it.second
as the key type, and letting the map
handle the sorting and duplicate handling for you.