我正在嘗試將元素從 a 添加map到 a pair vector,然后根據值對向量進行排序,但我不想添加具有相同值的元素,而且我不知道如何制作這樣的 if 陳述句。
該地圖包含一個單詞在輸入中重復的次數main()和單詞本身,我想對具有地圖元素的向量進行排序,但我不想重復重復相同次數的單詞。
這是我到目前為止所擁有的:
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
}
如果術語不完全正確,我深表歉意,我剛剛開始習慣使用mapsand pairs。
uj5u.com熱心網友回復:
由于您正在搜索 a vectorof pairs,因此您需要使用std::find_if()而不是std::find()查找vector與 a 的特定欄位匹配的元素pair,例如:
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);
}
或者,您可以只使用 anothermap而不是 a vector,it.second用作鍵型別,并讓map處理為您處理排序和重復處理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441059.html
