Home > code, STL > stl Sort in C++; simple code for sorting the array of structures

stl Sort in C++; simple code for sorting the array of structures

Simple Code that shows how to use the C++ STL function sort()


<blockquote>
#include <iostream>
#include <algorithm>

using namespace std;

struct Numb{
double num;
int pos1;

bool operator &lt;(const Numb &amp;n1){
return num &lt; n1.num;
};
};
////////////////////////////////
void main(void){

Numb numb[10];

for(int i=0; i &lt; 10; i++){
numb[i].num = rand();
numb[i].pos1 = i;
}
cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;
for(int i=0; i &lt; 10; i++){
cout &lt;&lt; " " &lt;&lt; "(" &lt;&lt; numb[i].pos1 &lt;&lt; ") " &lt;&lt; numb[i].num;
}
cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;

std::sort( numb, numb+10);
cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;
for(int i=0; i &lt; 10; i++){
cout &lt;&lt; " " &lt;&lt; "(" &lt;&lt; numb[i].pos1 &lt;&lt; ") " &lt;&lt; numb[i].num;
}

cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;

}
Advertisements
Categories: code, STL Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: