用c ++排序字符串向量

问题描述 投票:1回答:1

我正在编写c ++来对字符串向量进行排序。字符串应按其长度排序。如果长度相同,则按字典顺序排序:例如:abc <abd这是我的代码:

static bool sort_find(string& a, string& b){
         if(a.size() < b.size()){
             return true;
         }
         else if(a.size() > b.size()){
             return false;
         }
         else{
             for(int i=0;i<a.size();i++){
                if(a[i] ==  b[i] )
                  continue;
                 else if(a[i] < b[i]){
                    return true;
                  }
                 else{
                   return false;
                }
             }
             return true;
         }
     }

int main(){

 string array[13]={"m","mo","moc","moch","mocha","l","la","lat","latt","latte","c","ca","cat"};

 vector<string> svector(array,array+13);
 sort(svector.begin(),svector.end(),sort_find);
 return 0;
}

这段代码的输出是[c,l,m,ca,la,moch,mo,cat,lat,moc,latt,mocha,latte]输出对我没有意义。

欢迎大家的帮助!!

谢谢!

string vector
1个回答
1
投票

起初,我认为这很好。它对我有用。但那是纯粹的运气。

如果你查找std :: sort,并按照http://en.cppreference.com/w/cpp/concept/Compare对比较函数的要求的链接,你会发现它必须是严格的弱排序,包括要求

对于所有a,comp(a,a)== false

如果两个字符串相同,则返回true。这没有意义,因为你真的定义了less运算符。这导致std算法和数据结构的意外行为,这些算法和数据结构期望严格的弱排序。

为了解决这个问题,我建议如果长度相同,你只需返回一个<b,因为std :: string已经有了词典比较。

bool compare_length_then_string_lt(const string& a, const string& b) {
    if (a.size() < b.size())
        return true;
    else if (a.size() > b.size())
        return false;
    else
        return a < b;
}

std::sort(svector.begin(), svector.end(), compare_length_then_string_lt);

但我差点忘了。当组合多种不同的方式来比较两个结构时,通常可以使用std :: tuple或std :: tie,它们已经知道如何正确地将比较链接在一起。您只需告诉他们要按什么顺序比较哪些组件,他们会处理其余的事情:

std::sort(svector.begin(), svector.end(),
    // lambda notation
    [](const std::string &lhs, const std::string &rhs) {
        // comparator body
        return std::make_tuple(lhs.size(), lhs) < std::make_tuple(rhs.size(), rhs);
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.