如何对std :: vector进行排序,但不使用std :: sort更改特定元素? [英] How to sort std::vector but do not change specific elements using std::sort?

查看:63
本文介绍了如何对std :: vector进行排序,但不使用std :: sort更改特定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含正整数和-1的向量.我的问题是我想对向量进行排序,但不要仅通过使用 std :: sort (我知道其他解决方法)来触摸 -1元素.

I have a vector which contains positive integers and -1. My problem is I want to sort the vector but dont touch -1 elements by just using std::sort(I know other approaches to solve it).

例如:

输入:[-1、150、190、170,-1,-1、160、180]

Input: [-1, 150, 190, 170, -1, -1, 160, 180]

输出:[-1、150、160、170,-1,-1、180、190]

Output: [-1, 150, 160, 170, -1, -1, 180, 190]

这是我要解决的想法,但是没用:

This is my idea to solve it but it didnt work:

sort(myVector.begin(), myVector.end(), [&](const int& a,const int& b)->bool {
        if (a == -1 || b == -1)
            return &a < &b;
        return a < b;
    });

我的输出是:[-1、150、170、190,-1,-1、160、180]

My output is: [-1, 150, 170, 190, -1, -1, 160, 180]

输出应为:[-1、150、160、170,-1,-1、180、190]

The output should be: [-1, 150, 160, 170, -1, -1, 180, 190]

有什么想法可以通过使用 std :: sort 来解决吗?

Is there any idea to solve it by using std::sort ?

推荐答案

std :: sort 无法做到这一点.它按照严格的弱排序对一系列元素进行排序.您定义的排序不是严格弱.而且没有办法定义严格弱的排序,这样某些值仍保留在当前位置.因此,如果尝试按这种顺序使用 sort ,则会出现未定义的行为.

std::sort cannot do that. It sorts a range of elements in accord with a strict, weak ordering. The ordering you define is not strict-weak. And there's no way to define an ordering that is strict-weak, such that certain values remain in their current positions. And therefore, if you attempt to use sort with such an ordering, you get undefined behavior.

因此,您将不得不编写自己的排序功能.或者,您可以删除-1(记录其位置),对列表进行排序,然后重新插入.

So you're going to have to write your own sorting function. Or you can remove the -1's (recording their positions), sort the list, then reinsert them.

这篇关于如何对std :: vector进行排序,但不使用std :: sort更改特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆