[英]Sort std::vector<std::string *> overloading <
std::vector<std::string *>
上使用std::sort()
。<
。std::sort()
function 不會調用我的運算符,因為向量實際上有std::string *
作為類型而不是std::string
。 但我不確定如何指定這一點。std::sort()
中的第三個參數的情況下實現這一點#include <iostream>
#include <vector>
#include <algorithm>
bool operator<(std::string& str_1, std::string& str_2){
std::cout<<str_1[0] <<" < " << str_2[0] << std::endl;
return str_1[0] < str_2[0];
}
int main(int argc, const char * argv[]) {
std::string str1 = "abc";
std::string str2 = "def";
std::string str3 = "ghi";
std::string str4 = "bcd";
std::string str5 = "fgh";
//test the operator first
std::cout << (str1<str2) << std::endl;
std::vector<std::string *> str_vector;
str_vector.push_back(&str1);
str_vector.push_back(&str2);
str_vector.push_back(&str3);
str_vector.push_back(&str4);
str_vector.push_back(&str5);
std::sort(str_vector.begin(), str_vector.end());
for (std::vector<std::string *>::iterator it=str_vector.begin(); it!=str_vector.end(); ++it)
std::cout << ' ' << **it << std::endl;
return 0;
}
該運算符似乎實現得很好,但在std::sort()
期間從未調用過這是控制台 output:
a < d
1
fgh
bcd
ghi
def
abc
Program ended with exit code: 0
謝謝!
您為string::string
重載了operator<
,但str_vector
包含std::string *
。
由於您無法更改諸如指針之類的原始類型上的運算符的行為,因此您需要提供一個自定義比較器作為std::sort
的最后一個參數。 例如 lambda:
std::sort(str_vector.begin(), str_vector.end(),
[](const std::string *str_1, const std::string *str_2){
std::cout << (*str_1)[0] <<" < " << (*str_2)[0] << std::endl;
return (*str_1)[0] < (*str_2)[0];
});
您有一個指向std::string
類型對象的指針向量
std::vector<std::string *> str_vector;
因此,如果您在沒有指定比較 function 的情況下調用標准算法std::sort
,那么該算法將嘗試對向量進行排序,比較指針本身而不比較指向的對象。
但是,如果您要聲明std::string
對象的向量而不是指針,那么您的重載operator <
將找不到,因為 function std::sort
的定義在命名空間std
中,並且在此命名空間中將找到標准重載operator <
。
如果您將使用自己的比較 function 例如 lambda 表達式,則可以使用自己的重載operator <
對指針向量進行排序。
這是一個演示程序。
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
bool operator <( const std::string &s1, const std::string &s2 )
{
std::cout << "Bingo\n";
return s1[0] < s2[0];
}
int main()
{
std::string s[] = { "abc", "def", "ghi", "bcd", "fgh" };
std::vector<std::string *> v1;
v1.reserve( sizeof( s ) / sizeof( *s ) );
std::transform( std::begin( s ), std::end( s ), std::back_inserter( v1 ),
[]( auto &s ) { return &s; } );
std::sort( std::begin( v1 ), std::end( v1 ),
[]( const auto &p1, const auto p2 )
{
return *p1 < *p2;
} );
for ( const auto &p : v1 )
{
std::cout << *p << ' ';
}
std::cout << '\n';
return 0;
}
程序 output 是
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
abc bcd def fgh ghi
正如您所看到的,由於字符串"Bingo"
的測試 output 您的operator <
被調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.