如何对忽略某些数字的 std::vector 进行排序?

How to sort std::vector ignoring certain numbers?

本文关键字:vector std 排序 数字      更新时间:2023-10-16

我试图对数字向量进行排序并忽略某个数字,即将其保留在原位。这个答案实际上并没有离开找到它的元素。

例如,如果我有以下内容

std::vector<int> test{5, 3, 8, 4, -1, 1, 11, 9, 6};
std::sort(test.begin(), 
std::partition(test.begin(), test.end(), [](int n)
{return n != -1;}));

test分类为1 3 4 5 6 8 9 11 -1。我搜索了几个小时,并修改了自定义比较器和std::partition,但我无法提出将test向量分类为1 3 4 5 -1 6 8 9 11的解决方案。 这实际上非常困难吗?

根据@Bathsheba在他的回答中提到的补救措施,并愚弄std::sort()的谓词,可以得到如下解决方案:

演示

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> test{5, 3, 8, 4, -1, 1, 11, 9, 6};
// get the position of -1
auto itr = std::find(test.begin(), test.end(), -1);
// sort all elements so that -1 will be moved to end of vector
std::sort(test.begin(), test.end(), [](const int& lhs, const int& rhs )
{
if( lhs == -1 ) return false;
if( rhs == -1 ) return true;
return lhs < rhs;
});
test.erase(test.end()-1);   //  now erase it from end
test.insert(itr, -1);       //  insert to the earlier position
for(const auto& it: test)   std::cout << it << " ";
return 0;
}

是的,使用std::sort执行此操作很棘手:您必须以某种方式欺骗您的比较器将不变数插入正确的位置,如果不事先检查其他元素,这很困难。

一个简单的补救措施是使用插入排序;当你到达它时省略不合适的数字(但记录位置(,并在记录位置的末尾手动插入它。

给定一个向量。

  • 找到要离开的元素的位置。
  • 把它换到最后。
  • 对向量进行部分排序(没有最后一个元素( - 所选位置之前的所有元素都将被排序,之后将有一个随机顺序。
  • 元素交换回找到的位置
  • 对向量的其余部分进行排序

代码:

std::vector< int > data{ 5, 3, 8, 4, -1, 1, 11, 9, 6 };
auto chosen_iter = std::find( data.begin(), data.end(), -1 );
std::swap( *chosen_iter, *( data.end() - 1 ) );
std::partial_sort( data.begin(), chosen_iter, data.end() - 1 );
std::swap( *chosen_iter, *( data.end() - 1 ) );
std::sort( chosen_iter + 1, data.end() );

不将元素交换到末尾:

  • 查找元素的位置。
  • 使用使该元素
  • 大于矢量的其他元素的比较器对向量进行部分排序,直到并排除此位置,以便该元素不会出现在部分排序部分中。
  • 使用比较器
  • 对矢量的其余部分从此位置到末尾进行排序,该比较器使该元素小于矢量其余部分的其他元素,这会将此元素重新放在此位置。

法典:

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
constexpr int ignored_number = 100;
int main()
{
vector<int> test{5, 3, 8, 4, ignored_number, 1, 11, 9, 6};
auto it = find(test.begin(), test.end(), ignored_number);
partial_sort(test.begin(), it, test.end(), [](int lhs, int rhs) {
return lhs == ignored_number ? false :
(rhs == ignored_number ? true : lhs < rhs);
});
sort(it, test.end(), [](int lhs, int rhs) {
return rhs == ignored_number ? false :
(lhs == ignored_number ? true : lhs < rhs);
});
for (const auto& x: test) {
cout << x << ' ';
}
cout << endl;
}
相关文章: