如何对std :: vector进行排序,但不使用std :: sort更改特定元素?

编程入门 行业动态 更新时间:2024-10-11 13:27:26
本文介绍了如何对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更改特定元素?

本文发布于:2023-11-30 06:07:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:但不   元素   std   vector   sort

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!