對字符串向量先按長度升序,長度相同按字典序排序,並移除重複字符串。
sort + unique + erase。stable_sort 配合自定義比較函數 isShorter,保持相同長度的字典序順序。#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void elimDups(vector& words) {
sort(words.begin(), words.end());
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 main() {
vector words = {"aaa", "c", "eeee", "b", "cccc", "c"};
elimDups(words); // 去重 + 字典序
stable_sort(words.begin(), words.end(), isShorter); // 按長度穩定排序
for (const auto& s : words) cout << s << endl;
return 0;
}
b c aaa cccc eeee
