简体   繁体   English

C ++按列排序2d向量

[英]C++ sort 2d vector by column

Can someone tell me the best way to sort a 2d vector by column in C++ without using boost. 有人能告诉我在不使用boost的情况下用C ++中的列对2d向量进行排序的最佳方法。 I've done some searching and I can't find a good answer. 我做了一些搜索,我找不到一个好的答案。

Thanks 谢谢

To answer this, I have to make assumptions, meaning you could have given us more information. 要回答这个问题,我必须做出假设,这意味着你可以给我们更多的信息。

Assumption 1: What you call "2D vector" is a vector of vectors, eg a vector<vector<int>> . 假设1:你所谓的“2D矢量”是矢量矢量,例如vector<vector<int>>

Assumption 2a: the inner vectors are the rows, which means, you want to sort the outer vector by eg the second element of its inner vectors. 假设2a:内部向量是行,这意味着,您希望通过例如其内部向量的第二个元素对外部向量进行排序。 In that case std::sort kicks in, which has an overload that takes a comparator as its third argument. 在那种情况下, std::sort启动,它有一个重载,它将比较器作为其第三个参数。 The only thing you have to do is to write a comparator (ie a function, function object, lambda etc.), that takes two vectors and compares them by their N-th element. 你唯一要做的就是编写一个比较器(即函数,函数对象,lambda等),它采用两个向量并将它们与第N个元素进行比较。 Should not be too hard. 不应该太难。

Assumption 2b: the inner vectors are the columns , ie you want to sort one of the inner vectors and apply the reorderings to each other row as well. 假设2b:内部向量是 ,即您想要对其中一个内部向量进行排序,并将重新排序应用于每个其他行。 That's a bit more complicated, eg you could make another vector of indices 0 through N and sort that with a comparator that, given two indices i and j compares them by actually comparing column[i] and column[j] . 这有点复杂,例如你可以制作索引0到N的另一个向量,并用比较器对其进行排序,给定两个索引ij通过实际比较column[i]column[j]比较它们。 After you have sorted that vector, you can accordingly reorder all the columns. 对该向量进行排序后,可以相应地重新排序所有列。

The sort() Function in STL can do it for you. STL中的sort()函数可以为您完成。 You just need to write a function to compare 2 cases in your vector. 您只需要编写一个函数来比较矢量中的2个案例。

http://www.cplusplus.com/reference/algorithm/sort/ http://www.cplusplus.com/reference/algorithm/sort/

After, it depends the type of sort you need, you can sort the columns one by one, then the first row. 之后,它取决于您需要的排序类型,您可以逐列排序,然后排序第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM