Блог пользователя winter_s0ldier

Автор winter_s0ldier, история, 3 года назад, По-английски

I was trying to rearrange the array so that the even elements are at starting (order does not matter). I used lambda function in sort function but it is giving me segmentation error.

sort(all(arr), [](int p1, int p2){
        if(p1%2==0 && p2%2 == 0){
            
            return true;
        }
        else if(p1%2==0 && p2%2 != 0){
            
            return true;
        }
        return false;
    });

here all(x) = x.begin(), x.end() It is giving segmentation error for array size greater than 20. Can someone explain what is happening?

  • Проголосовать: нравится
  • +2
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится +12 Проголосовать: не нравится

Use this(as order doesn't matter):


stable_partition(arr.begin(), arr.end(), [](auto a) { return a % 2 == 0; });

If you want it to be sorted, just add sort() before this function.

»
3 года назад, # |
Rev. 3   Проголосовать: нравится +17 Проголосовать: не нравится

Some previous blogs on it already exists, you can go through this: https://codeforces.com/blog/entry/45084 . In short, if comp(a,b) is true then comp(b,a) must be false. Here if a is even and b is also even, then comp(a,b) and comp(b,a) both will return true. reference: https://en.cppreference.com/w/cpp/named_req/Compare