C++ Sort Vector

Spread the love

The C++ sort vector does a remarkable job of sorting though it doesn’t guarantee the sort order of items that started with the same value.

myVector = {102,30, 298, 2, 42};

sort( myVector.begin(),myVector.end() );

// Example program
#include <iostream>
#include <string>
#include <algorithm>  // sort is not going to run without this

int main()
{
  std::vector<int> sortMyValues = {3,5,1,200,103,45,78,5,35,31,4,2 };
  std::sort(sortMyValues.begin(),sortMyValues.end());
  
  for (int value:sortMyValues )
    std::cout << value << std::endl; 
}

C++ Sort Vector with Lambda

What is a Lamba?

You can think of it as a function within a function. Let’s have a look at how it works.

// Example program
#include <iostream>
#include <string>
#include <algorithm>  // sort is not going to run without this
#include <functional>

int main()
{
  std::vector<int> sortMyValues = {3,5,1,200,103,45,78,5,35,31,4,2 };
  std::sort(sortMyValues.begin(),sortMyValues.end(),[]( int a, int b)
  {
      return a > b;
  });
  
  for (int value:sortMyValues )
    std::cout << value << std::endl; 
}

Lambda right here in blue

std::sort(sortMyValues.begin(),sortMyValues.end(),[]( int a, int b)
{
return a > b;
});

The results of the c++ sort vector code above is the output below. The internal lambda function produced a descending order type algorithm as you can see from the example below

Results of the c++ vector sort with lambda

So, that was a self serving c++ sort Lambda, huh?

Yeah, admittedly, we have to walk before we run right. Ok, look at the code below and tell us if you understand a bit more of the power of a Lambda

In particular look at line 17 to 22

// Example program
#include <iostream>
#include <string>
#include <algorithm>  // sort is not going to run without this
#include <functional>

int main()
{
  std::vector<int> sortMyValues = {3,5,1,200,103,45,78,5,35,31,4,2 };
  std::sort(sortMyValues.begin(),sortMyValues.end(),[]( int a, int b)
  {
      if ( a==1 )
        return false;
      if ( b == 1 )
        return true;
        
      return a < b;
      });
  
  for (int value:sortMyValues )
    std::cout << value << std::endl; 
}

What do you think the output of the above program with its odd looking Lambda should be? Think about the actual data that the Lambda is set to work on.

It would appear that when the value of a is equal to 1, something really funky happens.

What is that? Look at the results below. Let us know in the comments if you get it.

In this sort, the user written lambda function was able to affect the c++ sort function such that some of the data caused the sort to act a little crazily.
OMG, what is the 1 doing at the bottom of the sorted list?

Top