【问题标题】:sort a string array using string length with std::vector in cpp在 cpp 中使用带有 std::vector 的字符串长度对字符串数组进行排序
【发布时间】:2021-09-14 11:35:59
【问题描述】:

我在 cpp 中有一个函数,我想用它来根据每个字符串的单独长度对字符串数组进行排序,我试图将特定索引处元素的长度与驻留在中的元素的长度进行比较下一个索引。如果下一个索引的长度小于第一个索引中字符串的长度,那么我将较短长度的字符串推送到具有较高长度的字符串的索引。我尝试的代码如下所示,我在我的 main 中使用它时遇到问题,编译器生成的错误指出 :[Error] could not convert '{"Mario", "Bowser", "Link"}' from '<brace-enclosed initializer list>' to 'std::vector<std::basic_string<char> >'.

#include <iostream>
#include <ctype.h>
#include <vector>

//below is my sort according to length function
using namespace std;
std::vector<std::string> sortByLength(std::vector<std::string> arr) {

    for(int k=0;k<arr.size();k++){
        if(arr[k+1].size()<arr[k].size()){
            //push the shorter string to the lower index
            arr[k]=arr[k+1];
        }
    }
    return arr;
}
//below is the main function
int main(){
//this line below generates compile error
std::vector<string> myarr=sortByLength({"Mario", "Bowser", "Link"})<<endl;
cout<<myarr<<endl;

return 0;
}

【问题讨论】:

  • 我不确定sortByLength 做了什么,但它肯定不会对向量进行排序。考虑std::sort
  • 会按照string length排序吗?
  • 它可以按照您想要的任何严格的弱排序进行排序。该链接包含三个使用std::sort 的非默认排序标准的示例。
  • std::sort(myarr.begin(), myarr.end(), [](auto&amp; lhs, auto&amp; rhs){ return lhs.size() &lt; rhs.size(); });
  • @JohnFilleau,检查一下

标签: c++ arrays sorting std


【解决方案1】:

给你。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
void printVec(std::vector<std::string>& vec) {
    for(auto&& v:vec) {
        std::cout<<v<<std::endl;
    }
}
int main() {
    std::vector<std::string> vec {"abc","ab","a","abcd"};
    printVec(vec);
    std::sort(vec.begin(), vec.end(), [](std::string& a, std::string& b) {
        return a.length() > b.length();
    });
    printVec(vec);
    return 0;
}

注意:适用于 c++11 或更高版本。

【讨论】:

    【解决方案2】:

    作为排序的替代方法,您可以将字符串移动到已排序的容器中:

    #include <iostream>
    #include <set>
    #include <string>
    #include <vector>
    
    struct StringLengthComparer
    {
        bool operator ()(std::string left, std::string right) const 
        {
            return left.length() < right.length();
        }
    };
    
    using StringMultiset = std::multiset<std::string, StringLengthComparer>;
    
    using std::cout;
    
    StringMultiset sortByLength(std::vector<std::string> arr) 
    {
        return StringMultiset{arr.begin(), arr.end()};
    }
    
    int main()
    {
        auto myset = sortByLength({"Mario", "Bowser", "Link"});
    
        for(auto item : myset)
        {
            cout << item<< '\n';
        }
    
        return 0;
    }
    

    【讨论】:

    • 出现错误,StringMultiset 没有命名类型
    猜你喜欢
    • 2016-04-23
    • 2015-01-16
    • 1970-01-01
    • 2016-02-09
    • 2017-06-21
    • 2021-01-13
    • 2011-06-04
    • 1970-01-01
    • 2013-11-05
    相关资源
    最近更新 更多