簡體   English   中英

按降序字母順序對列表進行排序並打印列表

[英]Sort the list alphabetically in descending order and print the list

一種。 在列表中存儲5個名稱。 允許用戶輸入每個名稱。
b。 將列表按字母升序排序,然后打印列表。 C。 按降序字母順序對列表進行排序並打印列表。
d。 確保您的代碼可以執行而不會出現錯誤或錯誤。

我被困在按降序排序列表,請幫助:(

下面是我的升序源代碼。

#include <iostream>
#include <set>
#include <algorithm>

void print(const std::string& item)
{
    std::cout << item << std::endl;
}

int main()
{
    std::set<std::string> sortedItems;

    for(int i = 1; i <= 5; ++i)
    {
        std::string name;
        std::cout << i << ". ";
        std::cin >> name;

        sortedItems.insert(name);
    }

    std::for_each(sortedItems.begin(), sortedItems.end(), &print);
    return 0;
}

要對列表進行排序,不需要std::set ,可以將名稱存儲在std::vector ,然后使用標頭算法中的函數std::sort 該函數還有一個帶謂詞的版本,因此您可以使用此謂詞反轉順序,指定反向比較。 看看sort的文檔。 也有在看更大的是在標題中定義的功能-這是你可以用它來反向排序順序的謂語。 看一下有關ideone的簡短示例

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;

int main() {
    vector<string> test;
    test.push_back("a");
    test.push_back("c");
    test.push_back("b");
    sort(test.begin(), test.end());
    for (unsigned i = 0; i < test.size(); ++i) {
        cout << test[i] << endl;
    }
    sort(test.begin(), test.end(), greater<string>());
    for (unsigned i = 0; i < test.size(); ++i) {
        cout << test[i] << endl;
    }
    return 0;
}

要以相反的順序顯示set ,可以使用:

std::for_each(sortedItems.rbegin(), sortedItems.rend(), &print);

暫無
暫無

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

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