sort set c++ code example
Example 1: c++ sort
int arr[]= {2,3,5,6,1,2,3,6,10,100,200,0,-10};
int n = sizeof(arr)/sizeof(int);
sort(arr,arr+n);
for(int i: arr)
{
cout << i << " ";
}
Example 2: array sort c++
#include <iostream>
2 #include <array>
3 #include <string>
4 #include <algorithm>
5
6 using namespace std;
7
8 int main(){
9 array<string, 4> colours = {"blue", "black", "red", "green"};
10 for (string colour : colours){
11 cout << colour << ' ';
12 }
13 cout << endl;
14 sort(colours.begin(), colours.end());
15 for (string colour : colours){
16 cout << colour << ' ';
17 }
18 return 0;
19 }
66
20
21
Example 3: c++ set sort order
struct cmpStruct {
bool operator() (int const & lhs, int const & rhs) const
{
return lhs > rhs;
}
};
std::set<int, cmpStruct > myInverseSortedSet;
Example 4: merge sort c++
#include "tools.hpp"
std::vector<int> sort(size_t start, size_t length, const std::vector<int>& vec)
{
if(vec.size()==0 ||vec.size() == 1)
return vec;
vector<int> left,right;
size_t mid_point = vec.size()/2;
for(int i = 0 ; i < mid_point; ++i){left.emplace_back(vec[i]);}
for(int j = mid_point; j < length; ++j){ right.emplace_back(vec[j]);}
left = sort(start,mid_point,left);
right = sort(mid_point,length-mid_point,right);
return merge(left,right);
}
vector<int> merge(const vector<int>& a, const vector<int>& b)
{
vector<int> merged_a_b(a.size()+b.size(),0);
int i = 0;
int j = 0;
int k = 0;
int left_size = a.size();
int right_size = b.size();
while(i<left_size && j<right_size)
{
if(a[i]<b[j])
{
merged_a_b[k]=a[i];
i++;
}
else
{
merged_a_b[k]=b[j];
j++;
}
k++;
}
while(i<left_size)
{
merged_a_b[k]=a[i];
i++;
k++;
}
while(j<right_size)
{
merged_a_b[k]=b[j];
j++;
k++;
}
return merged_a_b;
}