簡體   English   中英

按字符串C ++對存儲在向量中的對象進行排序

[英]Sort objects stored in vector by string C++

想象一下帶有字符串值的類。

class Test {
public:
    string name;
};

是存儲在向量中

vector<Test> d;

我想使用sort()函數按照字母名稱值對矢量字母中的對象進行排序。 我知道sort()函數有第三個參數某種排序函數,但我不知道如何編寫這個函數。

sort(d.begin(),d.end(),comp());

comp () { ? }

您可以創建比較器

bool comp(const Test &test1, const Test &test2){
    return test1.getName() <  test2.getName();
}

或者你可以在你的班級重載operator <

bool operator < (const Test &test){
    return name < test.name;
}

請注意,如果重載operator < ,則不需要在sort函數中添加第三個參數。

comp將是一個函數,它將返回一個bool來指示兩個參數的比較。 在你的情況下,它應該看起來像:

bool compare ( const Test& s1, const Test& s2 )
{
    return ( s1.name < s2.name );
}

你的調用將是: sort ( d.begin(), d.end(), compare );

暫無
暫無

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

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