讓字符串向量首先按字符串長度進行排序,長度短的在前,長的在後。如果長度相等則按字典序排序,並移除重復的字符串。
去重復並按字典序排序:
void elimDumps(vector&words) { // 按字典序排序 sort(words.begin(), words.end()); // unique重排輸入范圍,使得每個單詞只出現一次 // 並排列在范圍的前部,返回指向不重復區域之後一個位置的迭代器 auto end_unique = unique(words.begin(), words.end()); // 刪除重復單詞 words.erase(end_unique, words.end()); }
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
int _tmain(int argc, _TCHAR* argv[])
{
// 創建並初始化字符串向量
vector words{ "aaa", "c", "eeee", "b", "cccc", "c" };
// 移除重復單詞並按字典序排序
elimDumps(words);
// 將向量按字符串大小排序,使用穩定排序算法保持相同長度的單詞按字典序排列
stable_sort(words.begin(), words.end(), isShorter);
for (auto &s : words)
{
cout << s << endl;
}
return 0;
}
