首页 > 解决方案 > 如何排序 std::vector 忽略某些数字?

问题描述

我正在尝试对数字向量进行排序并忽略某个数字,即将它留在原处。这个答案实际上并没有留下找到它的元素。

例如,如果我有以下

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;}));

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

标签: c++algorithmsortingc++11stdvector

解决方案


根据@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;
}

推荐阅读