[英]Sort vector of vector
I have a vector of vectors of int like this: 我有一个像这样的int向量的向量:
std::vector<std::vector<int>> vec_vec{{3,5,1,6},{2,4},...};
The results should be 结果应该是
Case1: {{1, 2, 3, 4}, {5, 6}}
Case2: {1,2,3,4,5,6}
Case3: {{1, 3, 5, 6}, {2, 4}}
I found many ways to do this, the best one I found need complexity O(n^2)
to sort them. 我找到了许多方法来做到这一点,我发现最好的方法需要复杂度O(n^2)
来对它们进行排序。
What's the best complexity for the case1
, case2
and case3
? 什么是对最好的复杂case1
, case2
和case3
?
So what's the best way to write a native (c++11,c++14) cross platform code to sort that's vector? 那么,编写本机(c ++ 11,c ++ 14)跨平台代码对向量进行排序的最佳方法是什么? is O(n^2)
is the best complexity? O(n^2)
是最好的复杂度吗? The memory is important also. 记忆也很重要。
I checked this solution here , but it seems it also took O(n^2)
to sort the vectors? 我在这里检查了此解决方案,但似乎还需要O(n^2)
对向量进行排序?
The easiest case is case 2. To solve that, make a temporary new vector, move all elements there, and sort the new vector. 最简单的情况是情况2。要解决此问题,请制作一个临时的新向量,将所有元素移到那里,并对新向量进行排序。
std::vector<int> temp;
for (const auto& vec: vec_vec)
{
std::copy(vec.begin(), vec.end(), std::back_inserter(temp));
}
std::sort(temp.begin(), temp.end());
The copying part is O(n); 复制部分为O(n); the sorting part is O(n log(n)). 排序部分是O(n log(n))。
To implement case 1, copy the elements from temp
back to vec_vec
- this should be easy. 要实现案例1,请将元素从temp
复制回vec_vec
这应该很容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.