差不多有24天没写推送了。。。。一直干活,期间好几晚都没回宿舍,太惨了,净在干些没啥用的事情。
虽然不想干,但确实学到了一些东西(大半个月没找工作了,更想找工作来着)。
如下图所示,我有一个 1 * n 的cell数组,这个cell的每一个元素是一个 1 * 2 的向量,表示一个坐标点(x, y):
现在要根据坐标的 x 值对这个 cell 数组进行排序!
我本来以为可以和C++ STL中的sort算法一样 指定一下排序方法就行。但是查看MATLAB的帮助文档,发现他们的sort函数没法用在我这个cell数组上!
直接放解决办法吧:
先把cell数组(coors)中的每个小单元的第一个元素拿出来,就是把所有的x坐标拿出来,放到一个行或者列向量中,记为 x 。
[~, ind] = sort(x); 获取排序后的索引(把这些索引对应的元素排起来就是有序的)。还是看MathWorks给的解释吧:[B,I] = sort(_) also returns a collection of index vectors for any of the previous syntaxes. I is the same size as A and describes the arrangement of the elements of A into B along the sorted dimension. For example, if A is a vector, then B = A(I).
coors = coors(ind); 这样就对coors这个cell数组排序了
输出:
我就直接写代码了,也没啥可比性。实际就是创建一个:
vector<pair<double, double>> coors;这样就类似于上面MATLAB中的那个cell了。
#include <iostream> #include <vector> #include <utility> /// for pair #include <algorithm> #include <iomanip> using namespace std; using COOR = pair<double, double>; /// 定义 COOR 的输出 ostream& operator<<(ostream& os, pair<double, double>& c) { os << "(" << c.first << ", " << c.second << ")"; return os; } /// 定义比较函数,根据 x 的值比较 bool MySortFunc(const COOR& c1, const COOR& c2) { return c1.first < c2.first; } int main() { vector<COOR> coors{{180, 37}, {60, 39}, {120, 38}, {0, 40}, {420, 32}, {300, 35}}; /// 打印 原始坐标 for (auto ele : coors) cout << setw(10) << ele; cout << endl; /// 排序 坐标vector sort(coors.begin(), coors.end(), MySortFunc); /// 打印 排序后的vector for (auto ele : coors) cout << setw(10) << ele; cout << endl; }