C++ STL : A very simple algorithm code example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: To demonstrate a very simple C++ STL algorithm in C++ programming using find(), reverse(), sort(), max_element() and min_element() members

To show: A very simple algorithm program using find(), reverse(), sort(), max_element() and min_element() members in C++ programming

 

// C++ STL, a very simple algorithm example

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

 

int main(void)

{

// declare a vector and the iterator

vector<int> vec;

vector<int>::iterator pos;

 

// insert elements from 1 to 6 in arbitrary order, constructing vector

vec.push_back(7);

vec.push_back(4);

vec.push_back(8);

vec.push_back(0);

vec.push_back(12);

vec.push_back(9);

 

// print the vector data

cout<<"The original vec vector: ";

for(pos = vec.begin(); pos != vec.end(); pos++)

cout<<*pos<< " ";

cout<<endl;

 

// find and print minimum and maximum elements

pos = min_element(vec.begin(), vec.end());

// print the results

cout<<"\nThe minimum element's value: "<<*pos<<endl;

pos = max_element(vec.begin(), vec.end());

cout<<"\nThe maximum element's value: "<<*pos<<endl<<endl;

// sort() algorithm, sort all elements

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

// print the vector data...

cout<<"The sorted vec vector: ";

for(pos = vec.begin(); pos != vec.end(); pos++)

cout<<*pos<< " ";

cout<<endl<<endl;

// find() algorithm, find the first element with value 8

cout<<"Find value of 8, then reverse the order: ";

pos = find(vec.begin(), vec.end(), 8);

// reverse() algorithm, reverse the order of the found element with value 8 and all the following elements

reverse(pos, vec.end());

// print the result

for(pos=vec.begin(); pos!=vec.end(); ++pos)

cout<<*pos<<' ';

cout << endl;

return 0;

}

 

Output examples:

 

The original vec vector: 7 4 8 0 12 9

The minimum element's value: 0

The maximum element's value: 12

The sorted vec vector: 0 4 7 8 9 12

Find value of 8, then reverse the order: 0 4 7 12 9 8

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index