Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Sắp xếp mảng chuỗi theo độ dài trong C++

Sắp xếp danh sách chuỗi theo độ dài tăng dần. Chuỗi ngắn hơn đứng trước.

str_list = {"Hello", "ABC", "Programming", "Length", "Population"}

Sau sắp xếp: {"ABC", "Hello", "Length", "Population", "Programming"}

Tạo hàm so sánh tùy chỉnh cho std::sort.

Thuật toán

compare(str1, str2):
    Bắt đầu
        nếu độ dài str1 < độ dài str2, thì
            trả về 1
        trả về 0
    Kết thúc

Ví dụ mã C++

#include<iostream>
#include<algorithm>
using namespace std;

int compare(string str1, string str2){
    if(str1.length() < str2.length())
        return 1;
    return 0;
}

int main(){
    string str_list[] = {"Hello", "ABC", "Programming", "Length", "Population"};
    int n = 5;
    sort(str_list, str_list + n, compare);
    for(int i = 0; i < n; i++){
        cout << str_list[i] << " ";
    }
}

Kết quả đầu ra

ABC Hello Length Population Programming