我们如何在 c++ 中使用 std::sort 对 2D 字符串数组进行排序

How do we sort a 2D string array using std::sort in c++?

本文关键字:2D sort 字符串 数组 排序 std c++ 我们      更新时间:2023-10-16

我已经使用以下代码段尝试过,但它给出了一个错误。但是,同一段代码在 2D 整数数组上运行良好。

法典:sort(str[i], str[i]+4(;i 是字符串的循环迭代器

错误:

[错误] 与"运算符+"不匹配(操作数类型为"std::string {aka std::basic_string}' 和 'int'(

根据文档标准::排序

按升序对区域 [第一个、最后一个( 中的元素进行排序。不保证保持相等元素的顺序。

定义

template< class ExecutionPolicy, class RandomIt, class Compare > void sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp )

参数

第一个最后一个 - 要排序的元素范围

comp - 比较函数对象(即满足比较要求的对象(,如果第一个参数小于(即在第二个参数之前排序(,则返回 true。

复杂度 O(N·log(N))其中 N = std::distance(first, last)

注意:使用vector比使用array更好,特别是在您的情况下(2D 字符串(。

例:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printTwoDString(vector< vector<string> > twodString){
    for(int i = 0; i < twodString.size(); i++){
        for(int j = 0; j < twodString[i].size(); j++)
            cout<<twodString[i][j]<<" ";
        cout<<endl;
    }
}
int main() {
    vector< vector<string> > twodString = {
        {"chandler", "joey", "janice"},
        {"gunther", "richard", "rachel"},
        {"monika", "phoebe", "ross"}
    };
    // sort the whole string
    std::sort(twodString.begin(), twodString.end());
    printTwoDString(twodString);
    // sort a single row (should sort second row to gunther rachel richard )
    std::sort(twodString[1].begin(), twodString[1].end());
    printTwoDString(twodString);
    return 0;
}

实时代码