Sort (C++)

sort.cpp

#include <iostream>
#include <vector>
#include <algorithm>

bool compar(const int& a, const int& b);
void fillVector(std::vector<int>& v);
void printVector(std::vector<int>& v);

int main ()
{
  std::vector<int> testVector;
  
  fillVector(testVector);
  
  std::cout << "Before sorting : " << std::endl;
  printVector(testVector);
  
  // Notice that you can leave the 3rd argument with the
  // default value if that fits your needs. See documentation
  // for details.
  std::sort(testVector.begin(), testVector.end(), compar);
  
  std::cout << std::endl << "After sorting : " << std::endl;
  printVector(testVector);

  return 0;
}
/** Comparison function object that, taking two values of the same 
 * type.
 * @param a First element.
 * @param b Second element.
 * @return rue if the first 
 * argument goes before the second argument in the specific strict 
 * weak ordering it defines, and false otherwise.
 */
bool compar(const int& a, const int& b)
{
    return (a < b) ? true : false;
    
}

/**
 * Fills the vector with arbitrary data.
 * @param v The vector to be filled.
 */
void fillVector(std::vector<int>& v)
{
    for (int i=0 ; i < 5 ; i++)
      v.push_back(10 - i);
}

/**
 * Prints the vector.
 * @param v The vector to be printed.
 */
void printVector(std::vector<int>& v)
{
    for (std::vector<int>::iterator it = v.begin() ; it != v.end() ; it++)
        std::cout << *it << ' ';
    std::cout << std::endl;
}

This code was developed by me, G. Samaras.

We used a function pointer as third parameter of sort. More on function pointers.
Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

One thought on “Sort (C++)

  1. Pingback: sorting an array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s