C 2D数组排序
C++ 2D Array Sorting
我正在尝试对2D数组中的元素进行类似的方式:
338 640 723.771 62.1603
364 804 882.56 65.642
199 664 693.179 73.3166
我需要对它们进行对第三列和第4列的疑问。
例如第三列:
199 664 693.179 73.3166
338 640 723.771 62.1603
364 804 882.56 65.642
对于第四列:
338 640 723.771 62.1603
364 804 882.56 65.642
199 664 693.179 73.3166
我希望我可以解释我想做什么。已经感谢您的帮助..
答案:
我找到了需要什么。我将这些代码放在这里,也许对别人有帮助。
这是列的比较函数:
bool Compare(vector<double> A, vector<double> B) {
return (A[2] < B[2]); // 2 means which column that you want to compare
}
这是排序代码:
std::sort(dots.begin(), dots.end(), &Compare); // "dots" needs to be a vector. in this case its a 2d double vector
来源是:https://stackoverflow.com/a/37516971/5331586
使用STD ::与您自己的比较器进行排序。我会这样解决:
#include <algorithm>
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
class Comparate2DArrayByColumn {
public:
Comparate2DArrayByColumn(int column)
: column(column)
{
}
template <typename T>
bool operator()(const std::vector<T>& array1, const std::vector<T>& array2)
{
// do not use [] here, it will be UB
return array1.at(column) > array2.at(column);
}
private:
int column;
};
void printArray(const std::vector<std::vector<double> >& array)
{
for (auto& line : array) {
for (auto val : line) {
cout << val << " ";
}
cout << endl;
}
}
int main()
{
std::vector<std::vector<double> > array = {
{ 33, 640, 723.771, 62.1603 },
{ 364, 804, 882.56, 65.642 },
{ 199, 664, 693.179, 73.3166 },
};
printArray(array);
cout << endl
<< endl;
std::sort(array.begin(), array.end(), Comparate2DArrayByColumn(2));
printArray(array);
return 0;
}
相关文章:
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C 集合构建器中类成员数组的2D数组大小
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- 用另一个1D数组替换2D数组的整个行
- 如何使用C样式在C 中正确复制抽象类数组的2D数组
- 从 1D 数组创建 2D 数组
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- 如何使用object.get()将文本读取到一个参数比文本大的2D数组中(2D数组有更多的行和列)
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组