簡體   English   中英

在 C++ 中使用 sort 對從第二個字符到最后一個字符的字符串進行排序

[英]using sort in C++ to sort a string starting from 2nd character to last character

我想對從第二個字符到最后一個字符的字符串進行排序。 目前我可以根據我的要求對字符串進行排序,但我想在 C++ 中使用sort function 來實現相同的目的

樣本輸入:

san test van best

樣品 output:

san van test best

我現在的程序

for (int i1 = 0; i1 < n; ++i1) {
    for (int j1 = i1 + 1; j1 < n; ++j1) {
        temp5 = arr[j1].substr(1, arr[j1].length() - 1);
        temp6 = arr[i1].substr(1, arr[i1].length() - 1);
        if (temp6.compare(temp5) > temp5.compare(temp6)) {
            a = arr[i1];
            arr[i1] = arr[j1];
            arr[j1] = a;
        }
    }
}
std::sort(std::begin(arr), std::end(arr),
    [](std::string_view const & l, std::string_view const & r){
        return l.substr(1) < r.substr(1);
    }
);

完整的工作示例:

在線嘗試!

#include <string_view>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

int main() {
    std::string arr[] = {"san", "test", "van", "best"};
    std::sort(std::begin(arr), std::end(arr),
        [](std::string_view const & l, std::string_view const & r){
            return l.substr(1) < r.substr(1);
        }
    );
    for (auto const & s: arr)
        std::cout << s << " ";
}

Output:

san van test best

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM