首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ vector 排序:長度優先再字典序並去重

     編輯:關於C++

需求

對字符串向量先按長度升序,長度相同按字典序排序,並移除重複字符串。

實現步驟

  1. 去重並字典序排序:用 sort + unique + erase。
  2. 穩定排序按長度:用 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

運行結果截圖

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved