我们如何在 c++ 中使用 std::sort 对 2D 字符串数组进行排序
How do we sort a 2D string array using std::sort in c++?
我已经使用以下代码段尝试过,但它给出了一个错误。但是,同一段代码在 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;
}
实时代码
相关文章:
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 为什么 std::unique 不调用 std::sort?
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 对字符串进行排序时,在c++中处理sort()
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- std::sort()函数无法对向量的一部分进行排序
- 四边形的 2D 旋转
- 打印第二列时的2d字符矢量打印空间
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 通过 std::sort 对 C 2D 数组进行排序
- 在指向 2D 数据的指针上C++"std::sort"而不复制
- 我们如何在 c++ 中使用 std::sort 对 2D 字符串数组进行排序
- 使用 std::sort(基于列)对 2d 数组进行排序
- 在c++中使用Sort()对2D字符数组进行排序
- std::sort for a 2D vector in c++