accumulate 1.
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main ()
{
int arr[] = { 1,2,3,4,5 };
vector<int> v(arr,arr+5);
// 1+2+3+4+5 and + 0
int sum = accumulate(v.begin(), v.end(), 0);
cout << "sum = " << sum << endl;
return 0;
}
OUTPUT:
// sum = 15
accumulate 2.
#include <iostream>
#include <numeric>
using namespace std;
int main ()
{
int x[] = {1,2,3,4,5};
int sum = accumulate(x, x+5, 10); // 1+2+3+4+5+ 10
cout << "sum = " << sum << endl;
return 0;
}
OUTPUT:
// sum = 25
accumulate 3.
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int mult (int initial_, int element_)
{
return initial_ * element_;
}
//-----------------------------------
int main ()
{
vector <int> v(5);
for ( int i = 0; i < v.size(); i++ )
v[i] = i + 1;
// 1 * 2 * 3 * 4 * 5
int prod = accumulate(v.begin(), v.end(), 1, mult);
cout << "prod = " << prod << endl;
return 0;
}
OUTPUT:
// prod = 120
accumulate 4.
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
int main ()
{
int x[] = {1,2,3,4,5};
// 1 * 2 * 3 * 4 * 5 and * 1
int sum = accumulate(x, x+5, 1, multiplies<int>());
cout << "sum = " << sum << endl;
// 1 * 2 * 3 * 4 * 5 and * 2
sum = accumulate(x, x+5, 2, multiplies<int>());
cout << "sum = " << sum << endl;
// 2 * 3 * 4 and * 10
sum = accumulate(x+2, x+4, 10, multiplies<int>());
cout << "sum = " << sum << endl;
return 0;
}
OUTPUT:
// sum = 120
// sum = 240
// sum = 120
adjacent_difference 1.
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
int main ()
{
vector i(10);
vector result( i.size() );
for ( int j = 0; j < 10; j++ )
i[j] = (j+1);
adjacent_difference(i.begin(), i.end(),
result.begin(), multiplies<int>());
ostream_iterator iter (cout, " ");
cout << "vector i : ";
copy (i.begin(), i.end(), iter);
cout << endl;
cout << "vector result : ";
copy (result.begin(), result.end(), iter);
cout << endl;
return 0;
}
// like with accumulate but each result of multiplications
OUTPUT:
// vector i : 1 2 3 4 5 6 7 8 9 10
// vector result : 1 2 6 12 20 30 42 56 72 90
adjacent_difference 2.
#include <iostream>
#include <algorithm>
#include <stl.h>
using namespace std;
int main ()
{
vector i(10);
vector result( i.size() );
for ( int j = 0; j < 10; j++ )
i[j] = (j+1) * 2;
adjacent_difference(i.begin(),i.end(),result.begin());
ostream_iterator iter (cout, " ");
copy (i.begin(), i.end(), iter);
cout << endl;
copy (result.begin(), result.end(), iter);
cout << endl;
return 0;
}
OUTPUT:
// 2 4 6 8 10 12 14 16 18 20
// 2 2 2 2 2 2 2 2 2 2
adjacent_difference 3.
#include <iostream>
#include <algorithm>
#include <stl.h>
using namespace std;
int main ()
{
int x[]={12,6,10,110,200};
int difference[5];
adjacent_difference(x,x+5,difference);
for ( int i = 0; i < 5; i++ )
cout << x[i] << ' '; cout << endl;
// start from second element
for ( int i = 1; i < 5; i++ )
cout << difference[i] << ' '; cout << endl;
return 0;
}
OUTPUT:
// 12 6 10 110 200
// -6 4 100 90
adjacent_find 1.
#include <algorithm>
#include <iostream>
using namespace std;
void main()
{
const int ARRAY_SIZE = 8 ;
int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
int *location;//stores the position for the first pair
//of matching consecutive elements.
// print content of IntArray
cout << "IntArray { " ;
for(int i = 0; i < ARRAY_SIZE; i++)
cout << IntArray[i] << ", " ;
cout << " }" << endl ;
// Find the first pair of matching consecutive elements
// in the range [first, last + 1)
// This version performs matching using operator==
location = adjacent_find(IntArray, IntArray +
ARRAY_SIZE);
//print the matching elements if any were found
if (location != IntArray + ARRAY_SIZE)// matching
// consecutive elements found
cout << "Found adjacent pair of matching "
<< "elements: ("
<< *location << ", " << *(location + 1) << "), "
<< "at location " << location - IntArray << endl;
else // no matching consecutive elements were found
cout << "No adjacent pair of matching elements were"
<< " found" << endl; cout << endl; cout << endl;
}
OUTPUT:
// IntArray { 1, 2, 3, 4, 4, 5, 6, 7, }
// Found adjacent pair of matching elements:
// (4, 4), at location 3
advance 1.
#include <stl.h>
int main ()
{
vector<int> v(5);
for ( int i = 0; i < 5; i++ )
v[i] = (i+1)*3;
vector<int>::iterator it = v.begin();
cout << "At the beginning it is " << *it << endl;
advance(it, v.size() - 1);
cout << "At the end iterator is " << *it << endl;
return 0;
}
OUTPUT:
// At the beginning it is 3
// At the end iterator is 15
binary_search 1.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v;
for ( int i = 0; i < 10; i++ )
v.push_back(i);
cout << "vector v :";
for_each(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// check existence of element with value 7
if (binary_search(v.begin(), v.end(), 7)) {
cout << "7 is present" << endl;
}
else {
cout << "7 is not present" << endl;
}
// check existence of element with value 100
if (binary_search(b.begin(), b.end(), 100)) {
cout << "100 is present" << endl;
}
else {
cout << "100 is not present" << endl;
}
}
OUTPUT:
// vector v : 0 1 2 3 4 5 6 7 8 9
// 7 is present
// 100 is not present
copy 1.
#include <algorithm>
#include <vector>
#include <list>
using namespace std;
int main()
{
int ary[] = { 1, 2, 3, 4, 5 };
vector<int> v(ary,ary+5);
list<int> li;
// copy elements of v into li
copy (v.begin(), v.end(), // source range
back_inserter(li)); // destination range
// print elements of li
copy (li.begin(), li.end(), // source range
ostream_iterator<int>(cout," "));
// destination range
cout << endl;
// copy elements of v into li in reverse order
copy (v.rbegin(), v.rend(), // source range
li.begin()); // destination range
// print elements of li again
copy (li.begin(), li.end(), // source range
ostream_iterator(cout," "));
// destination range
cout << endl;
}
OUTPUT:
// 1 2 3 4 5
// 5 4 3 2 1
copy_backward 1.
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
// initialize source with ``..........abcdef..........''
vector<char> source(10,'.');
for (int c='a'; c<='f'; c++) {
source.push_back(c);
}
source.insert(source.end(),10,'.');
// print source
for (int i = 0; i < source.size(); i++ )
cout << source[i]; cout << endl;
// copy all letters three elements in front of the 'a'
vector<char> c1(source.begin(),source.end());
copy (c1.begin()+10, c1.begin()+16, // source range
c1.begin()+7); // destination range
copy (c1.begin(),c1.end(),
ostream_iterator<char>(cout,""));
cout << endl;
// copy all letters three elements behind the 'f'
vector<char> c2(source.begin(),source.end());
copy_backward (c2.begin()+10, c2.begin()+16,
// source range
c2.begin()+19); // destination range
copy (c2.begin(),c2.end(),
ostream_iterator<char>(cout,""));
cout << endl;
}
OUTPUT:
// ..........abcdef..........
// .......abcdefdef..........
// ..........abcabcdef.......
unique_copy 1.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
vector<string> v;
// read all words from the standard input
copy (istream_iterator<string>(cin),
// start of source
istream_iterator<string>(), // end of source
back_inserter(v)); // destination
copy (v.begin(),v.end(),
ostream_iterator<string>(cout," "));
// sort elements
sort (v.begin(), v.end());
// print all elements without duplicates
unique_copy (v.begin(), v.end(),// source
ostream_iterator<string>(cout,"\n"));
// destination
}
OUTPUT:
// Denis Anatoliy Anatoliy Wood Wood Lorens
// Anatoliy
// Denis
// Lorens
// Wood
count 1.
#include <stl.h>
int main ()
{
int a[] = {2,4,5,7,3,2,4,8,2};
int N = 0;
count (a, a + (sizeof(a) / sizeof(a[0])),
2, // patterm
N); // must be initialazed as const
cout << "Array consists " << N << " 2's" << endl;
return 0;
}
OUTPUT:
// Array consists 3 2's
count_if 1.
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
using namespace std;
// Return true if string str starts with letter 'S'
int MatchFirstChar( const string& str)
{
string s("S") ;
return s == str.substr(0,1) ;
}
//---------------------------------------------------
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of strings
typedef vector<string > StrVector ;
// Define an iterator for template class vector
// of strings
typedef StrVector::iterator StrVectIt ;
StrVector NamesV(VECTOR_SIZE);
//vector containing names
StrVectIt start, end, it ;
int result = 0 ; // stores count of elements
// that match value.
// Initialize vector NamesV
NamesV[0] = "She" ;
NamesV[1] = "Sells" ;
NamesV[2] = "Sea" ;
NamesV[3] = "Shells" ;
NamesV[4] = "by" ;
NamesV[5] = "the" ;
NamesV[6] = "Sea" ;
NamesV[7] = "Shore" ;
start = NamesV.begin() ; // location of first
// element of NamesV
end = NamesV.end() ; // one past the location
// last element of NamesV
// print content of NamesV
cout << "NamesV { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// Count the number of elements in the range
// [first, last +1) that start with letter 'S'
result = count_if(start, end, MatchFirstChar);
// print the count of elements that start
// with letter 'S'
cout << "Number of elements that start"
<< " with letter \"S\" = "
<< result << endl ;
}
OUTPUT:
// NamesVect { She Sells Sea Shells by the Sea Shore }
// Number of elements that start with letter "S" = 6
equal 1.
#include <iostream>
#include <algorithm>
#include <vector>
#include <cctype>
using namespace std;
bool notCase ( char ch1, char ch2 )
{
return tolower(ch1) == tolower(ch2);
}
//--------------------------------------
int main ()
{
char ar1[] = "anatoliy";
char ar2[] = "ANATOLIY";
vector<char> v1(ar1,ar1+strlen(ar1));
vector<char> v2(ar2,ar2+strlen(ar2));
cout << "v1 : ";
for ( int i = 0; i < v1.size(); i++ )
cout << v1[i]; cout << endl;
cout << "v2 : ";
for ( int i = 0; i < v2.size(); i++ )
cout << v2[i]; cout << endl;
if ( equal(v1.begin(),v1.end(),// first range
v2.begin()) )// second reange
{
cout << "v1 and v2 are equal" << endl;
}
else
cout << "v1 and v2 are not equal" << endl;
if ( equal(v1.begin(),v1.end(),// first range
v2.begin(), // second reange
notCase)) // compare function
{
cout << "v1 and v2 are equal" << endl;
}
else
cout << "v1 and v2 are not equal" << endl;
return 0;
}
OUTPUT:
// v1 : anatoliy
// v2 : ANATOLIY
// v1 and v2 are not equal
// v1 and v2 are equal
equal_range 1.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int ary[] = {1,2,3,4,5};
vector<int> v(ary,ary+5);
vector<int>::iterator It = v.begin();
while ( It != v.end() )
{
cout << *It++ << " ";
}
cout << endl;
// add to v copy of itself
copy (v.begin(),v.end(),back_inserter(v));
It = v.begin();
while ( It != v.end() )
{
cout << *It++ << " ";
}
cout << endl;
// sort the vector v
sort (v.begin(),v.end());
It = v.begin();
while ( It != v.end() )
{
cout << *It++ << " ";
}
cout << endl;
// print first and last position 5 could get inserted
pair::iterator,
vector::iterator> range;
range = equal_range (v.begin(),v.end(),5);
cout << "5 could get position from "
<< distance(v.begin(),range.first) + 1
<< " up to "
<< distance(v.begin(),range.second) + 1
<< " without breaking the sorting" << endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5
// 1 2 3 4 5 1 2 3 4 5
// 1 1 2 2 3 3 4 4 5 5
// 5 could get position from 9 up to 11 without
// breaking the sorting
min max 1.
#include <stl.h>
int main ()
{
int i = min ( 5, min(10,2));
cout << "min (5,10,2) = " << i << endl;
i = max ( 5, max (10,2));
cout << "max (5,10,2) = " << i << endl;
return 0;
}
OUTPUT:
// min (5,10,2) = 2
// max (5,10,2) = 10
min_element max_element 1.
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
bool absoluteLess (int elem1, int elem2)
{
return abs(elem1) < abs(elem2);
}
//----------------------------------------------
int main()
{
deque de;
for ( int i = -10; i < 10; i+=4 )
de.push_back(i);
copy (de.begin(),de.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// process and print minimum and maximum
cout << "minimum: "
<< *min_element(de.begin(),de.end())
<< endl;
cout << "maximum: "
<< *max_element(de.begin(),de.end())
<< endl;
// process and print minimum and maximum of
// absolute values
cout << "minimum of absolute values: "
<< *min_element(de.begin(),de.end(),
absLess)
<< endl;
cout << "maximum of absolute values: "
<< *max_element(de.begin(),de.end(),
absoluteLess)
<< endl;
}
OUTPUT:
// -10 -6 -2 2 6
// minimum: -10
// maximum: 6
// minimum of absolute values: 2
// maximum of absolute values: 10
sort 1.
#include <algorithm>
#include <iostream>
#include <string>
int main ()
{
vector<string> s;
s.push_back("Deny");
s.push_back("Zifrid");
s.push_back("Andry");
s.push_back("Arnold");
sort(s.begin(), s.end());
ostream_iterator<string> it (cout, "\n");
copy(s.begin(), s.end(), it);
return 0;
}
OUTPUT:
// Andry
// Arnold
// Deny
// Zifrid
sort 2.
// sort array of doubles in backward order,
// uses greater<>() function object
#include <iostream>
#include <algorithm> // for sort()
#include <functional> // for greater<>
using namespace std;
double fdata[] = { 19.2, 58.4, 88.0, 623.76, 45.7, 6.09 };
int main ()
{
sort (fdata, fdata+6, greater<double>() );
for (int j=0; j<6; j++)
cout << fdata[j] << ' ';
cout << endl;
return 0;
}
OUTPUT:
// 623.76 88 58.4 45.7 19.2 6.09
fill 1.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template <class T>
class Print
{
public:
void operator () (const T& t)
{
cout << t << ' ';
}
};
//-----------------------------------------------
int main ()
{
Print<int> DoPrint;
vector<int> vInt(10);
fill (vInt.begin(), vInt.begin()+5, 1 );
fill (vInt.begin() + 5, vInt.end(), 5 );
for_each (vInt.begin(), vInt.end(), DoPrint);
cout << "\n\n";
return 0;
}
OUTPUT:
// 1 1 1 1 1 5 5 5 5 5
fill_n 1.
#include <iostream>
#include <list>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
// print five times 7.7
fill_n(ostream_iterator<float>(cout, " "),
// beginning of destination
5, // count
7.5); // new value
cout << endl;
list<string> coll;
// insert "hello" three times
fill_n(back_inserter(coll),
// beginning of destination
5, // count
"hello"); // new value
list<string>::iterator It = coll.begin();
while ( It != coll.end )
cout << *It++ << " "; cout << endl;
// overwrite all elements with "again"
fill(coll.begin(), coll.end(), // destination
"again");
// new value
It = coll.begin();
while ( It != coll.end )
cout << *It++ << " "; cout << endl;
// replace all but two elements with "hi"
fill_n(coll.begin(), // beginning of destination
coll.size()-2, // count
"hi");
// new value
It = coll.begin();
while ( It != coll.end )
cout << *It++ << " "; cout << endl;
return 0;
}
OUTPUT:
// 7.5 7.5 7.5 7.5 7.5
// hello hello hello hello hello
// again again again again again
// hi hi hi again again
find 1.
#include <iostream>
#include <algorithm>
int arr[] = { 11, 22, 33, 44, 55, 66, 77, 88 };
int main ()
{
int *ptr;
ptr = find(arr, arr+8, 33); // find first 33
cout << "First object with value 33 found at offset "
<< (ptr-arr) << endl;
return 0;
}
OUTPUT:
// First object with value 33 found at offset 2
find_end 1.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
{
int ary[] = { 1,2,3,4,5,6,2,3,4,5,6 };
vector<int> v1(ary,ary+11);
vector<int> v2(ary+2,ary+4);
for ( int i = 0; i < v1.size(); i++ )
cout << v1[i] << " "; cout << endl;
for ( int i = 0; i < v2.size(); i++ )
cout << v2[i] << " "; cout << endl;
vector<int>::iterator pos;
pos = find_end(v1.begin(),v1.end(), // range
v2.begin(),v2.end()); // subrange
cout << "Position of last subrange of subrange "
<< "(2,4) found starting with element "
<< distance(v1.begin(),pos) + 1
<< endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5 6 2 3 4 5 6
// 3 4
// Position of last subrange of subrange (2,4)
// found starting with element 8
find_first_of 1.
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
vector<int> V;
list<int> searchV;
for ( int i = 1; i < 11; i++ )
{
V.insert(V.end(),i % 5);
}
for ( int i = 2; i < 5; i++ )
{
searchV.insert(searchV.end(),i);
}
copy(V.begin(),V.end(),
ostream_iterator(cout," "));
cout << endl;
copy(searchV.begin(),searchV.end(),
ostream_iterator(cout," "));
cout << endl;
// search first occurrence of an element of
// searchV in V
vector<int>::iterator pos;
pos = find_first_of (V.begin(), V.end(),// range
searchV.begin(), // beginning of search set
searchV.end()); // end of search set
cout << "first element of searchV in V is element "
<< distance(V.begin(),pos) + 1
<< endl;
// search last occurrence of an element of
// searchV in V
vector<int>::reverse_iterator rpos;
rpos = find_first_of (V.rbegin(), V.rend(), // range
searchV.begin(), // beginning of search set
searchV.end()); // end of search set
cout << "last element of searchV in V is element "
<< distance(V.begin(),rpos.base())
<< endl;
return 0;
}
OUTPUT:
// 1 2 3 4 0 1 2 3 4 0
// 2 3 4
// first element of searchV in V is element 2
// last element of searchV in V is element 9
find_if 1.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
//------------------------------------------------------
bool isDon (string name) // return true if name=Don
{
return name == "Don";
}
//------------------------------------------------------
string names[] = { "George", "Estelle", "Don", "Mike" };
int main ()
{
string* ptr;
ptr = find_if (names, names+4, isDon);
if (ptr == names+4)
cout << "Don is not on the list.\n";
else
cout << "Don is element "
<< (ptr - names)
<< " on the list.\n";
return 0;
}
OUTPUT:
// Don is element 2 on the list.
for_each 1.
#include <iostream>
#include <algorithm>
using namespace std;
void inch_to_cm (double in)
{
cout << ( in * 2.54 ) << ' ';
}
//-------------------------------------------------------
int main ()
{
// array of inches values
double inches[] = { 3.5, 6.2, 1.0, 12.87, 4.35 };
// output as centimeters
for_each (inches, inches+5, inch_to_cm);
cout << endl;
return 0;
}
OUTPUT:
// 8.89 15.748 2.54 32.6898 11.049
generate 1.
#include <cstdlib>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
list li;
// insert five random numbers
generate_n (back_inserter(li),
//beginning of destination range
5, // count
rand); // new value generator
copy(li.begin(),li.end(),
ostream_iterator<int>(cout," "));
// overwrite with five new random numbers
generate (li.begin(), li.end(), // destination range
rand); // new value generator
copy(li.begin(),li.end(),
ostream_iterator<int>(cout," "));
return 0;
}
OUTPUT:
// 41 18467 6334 26500 19169
// 15724 11478 29358 26962 24464
includes 1.
// includes - Search for one sequence in another.
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#include <deque>
using namespace std;
void main()
{
const int VECTOR_SIZE = 5 ;
// Define a template class vector of strings
typedef vector<string > StringVector ;
// Define an iterator for template class vector
// of strings
typedef StringVector::iterator StringVectorIt ;
// Define a template class deque of strings
typedef deque<string > StringDeque ;
// Define an iterator for template class deque
// of strings
typedef StringDeque::iterator StringDequeIt ;
StringVector CartoonVector(VECTOR_SIZE) ;
StringDeque CartoonDeque ;
StringVectorIt start1, end1, it1 ;
StringDequeIt start2, end2, it2 ;
// Initialize vector Vector1
CartoonVector[0] = "Aladdin" ;
CartoonVector[1] = "Jasmine" ;
CartoonVector[2] = "Mickey" ;
CartoonVector[3] = "Minnie" ;
CartoonVector[4] = "Goofy" ;
start1 = CartoonVector.begin(); // location of first
// element of CartoonVector
end1 = CartoonVector.end(); // one past the location
// last element of CartoonVector
//Initialize list CartoonDeque
CartoonDeque.push_back("Jasmine");
CartoonDeque.push_back("Aladdin");
CartoonDeque.push_back("Goofy");
start2 = CartoonDeque.begin(); // location of first
// element of CartoonDeque
end2 = CartoonDeque.end(); // one past the location
// last element of CartoonDeque
//sort CartoonVector and CartoonDeque alphabetically
//includes requires the sequences
//to be sorted.
sort(start1, end1) ;
sort(start2, end2) ;
// print contents of CartoonVector and CartoonDeque
cout << "CartoonVector { " ;
for(it1 = start1; it1 != end1; it1++)
cout << *it1 << ", " ;
cout << " }\n" << endl ;
cout << "CartoonDeque { " ;
for(it2 = start2; it2 != end2; it2++)
cout << *it2 << ", " ;
cout << " }\n" << endl ;
// Is CartoonDeque a subset of CartoonVector?
if(includes(start1, end1, start2, end2) )
cout << "CartoonVector includes CartoonDeque"
<< endl ;
else
cout << "CartoonVector does not include "
<< "CartoonDeque" << endl ;
}
OUTPUT:
// CartoonVector { Aladdin, Goofy, Jasmine,
// Mickey, Minnie, }
// CartoonDeque { Aladdin, Goofy, Jasmine, }
// CartoonVector includes CartoonDeque
inner_product 1.
#include <iostream>
#include <list>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
list<int> li;
for ( int i = 1; i <= 6; i++ )
li.push_back(i);
copy(li.begin(),li.end(),
ostream_iterator<int>(cout," "));
cout << endl;
/* process sum of all products
* (0 + 1*1 + 2*2 + 3*3 + 4*4 + 5*5 + 6*6)
*/
cout << "inner product: "
<< inner_product
(li.begin(), li.end(), // first range
li.begin(), // second range
0) // initial value
<< endl;
/* process sum of 1*6 ... 6*1
* (0 + 1*6 + 2*5 + 3*4 + 4*3 + 5*2 + 6*1)
*/
cout << "inner reverse product: "
<< inner_product
(li.begin(), li.end(), // first range
li.rbegin(), // second range
0) // initial value
<< endl;
/* process product of all sums
* (1 * 1+1 * 2+2 * 3+3 * 4+4 * 5+5 * 6+6)
*/
cout << "product of sums: "
<< inner_product
(li.begin(), li.end(), // first range
li.begin(), // second range
1, // initial value
multiplies(), // inner operation
plus<int>()) // outer operation
<< endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5 6
// inner product: 91
// inner reverse product: 56
// product of sums: 46080
iota 1.
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
vector<int> V(10);
iota(V.begin(), V.end(), 1);
copy(V.begin(), V.end(),
ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5 6 7 8 9 10
inplace_merge 1.
/*
inplace_merge : Merge two sorted sub-sequences in
place into a single sorted list.
begin - Returns an iterator that points to the first
element in a sequence.
end - Returns an iterator that points one past the
end of a sequence.
*/
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
// Define an iterator for template class vector
// of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt start, end, it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
cout << "Before calling inplace_merge\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//merge the elements of Numbers in place
inplace_merge(start, start + 3, end) ;
cout << "After calling inplace_merge\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
OUTPUT:
// Program Output is:
// Before calling inplace_merge
// Numbers { 4 10 70 10 30 69 96 100 }
// After calling inplace_merge
// Numbers { 4 10 10 30 69 70 96 100 }
iter_swap 1.
#include <iostream>
#include <cassert>
#include <algorithm>
using namespace std;
int main ()
{
int x = 1;
int y = 2;
assert(x == 1 && y == 2);
cout << "x = " << x << " y = " << y << endl;
iter_swap(&x, &y);
assert(x == 2 && y == 1);
cout << "x = " << x << " y = " << y << endl;
return 0;
}
OUTPUT:
// x = 1 y = 2
// x = 2 y = 1
lexicographical_compare 1.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A1[] = {3, 1, 4, 1, 5, 9, 3};
int A2[] = {3, 1, 4, 2, 8, 5, 7};
int A3[] = {1, 2, 3, 4};
int A4[] = {1, 2, 3, 4, 5};
const int N1 = sizeof(A1) / sizeof(int);
const int N2 = sizeof(A2) / sizeof(int);
const int N3 = sizeof(A3) / sizeof(int);
const int N4 = sizeof(A4) / sizeof(int);
bool C12 = lexicographical_compare
(A1, A1 + N1, A2, A2 + N2);
bool C34 = lexicographical_compare
(A3, A3 + N3, A4, A4 + N4);
cout << "A1[] < A2[]: " << (C12 ? "true" : "false")
<< endl;
cout << "A3[] < A4[]: " << (C34 ? "true" : "false")
<< endl;
return 0;
}
OUTPUT:
// A1[] < A2[]: true
// A3[] < A4[]: true
lower_bound 1.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = { 1, 2, 3, 3, 3, 5, 8 };
const int N = sizeof(A) / sizeof(int);
for (int i = 1; i <= 10; ++i) {
int* p = lower_bound(A, A + N, i);
cout << "Searching for " << i << ". ";
cout << "Result: index = " << p - A << ", ";
if (p != A + N)
cout << "A[" << p - A << "] == " << *p << endl;
else
cout << "which is off-the-end." << endl;
}
return 0;
}
OUTPUT:
// Searching for 1. Result: index = 0, A[0] == 1
// Searching for 2. Result: index = 1, A[1] == 2
// Searching for 3. Result: index = 2, A[2] == 3
// Searching for 4. Result: index = 5, A[5] == 5
// Searching for 5. Result: index = 5, A[5] == 5
// Searching for 6. Result: index = 6, A[6] == 8
// Searching for 7. Result: index = 6, A[6] == 8
// Searching for 8. Result: index = 6, A[6] == 8
// Searching for 9. Result: index = 7,
// which is off-the-end.
// Searching for 10. Result: index = 7,
// which is off-the-end.
make_heap 1.
/* A heap is a particular way of ordering the elements
in a range of Random Access Iterators (f, l).
The reason heaps are useful (especially for sorting,
or as priority queues) is that they satisfy two
important properties. First, *f is the largest element
in the heap. Second, it is possible to add an element
to a heap (using push_heap), or to remove *f, in
logarithmic time. Internally, a heap is simply a tree
represented as a sequential range. The tree is
constructed so that that each node is less than or
equal to its parent node.
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(int);
make_heap(A, A+N);
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
sort_heap(A, A+N);
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
OUTPUT:
// 8 5 7 4 1 2
// 1 2 4 5 7 8
merge 1.
#include <iostream>
#include <algorithm>
using namespace std;
int src1[] = { 2, 3, 4, 6, 8 };
int src2[] = { 1, 3, 5 };
int dest[8];
int main ()
{
merge(src1, src1+5, src2, src2+3, dest);
for (int j = 0; j < 8; j++)
cout << dest[j] << ' ';
cout << endl;
return 0;
}
OUTPUT:
// 1 2 3 3 4 5 6 8
mismatch 1.
/* Mismatch finds the first position where the two ranges
(first1, last1) and (first2, first2 + (last1 - first1))
differ. The two versions of mismatch use different
tests for whether elements differ.
The first version of mismatch finds the first
iterator i in (first1, last1) such that *i !=
*(first2 + (i - first1)). The return value is a pair
whose first element is i and whose second element is
*(first2 + (i - first1)). If no such iterator i
exists, the return value is a pair whose first
element is last1 and whose second element is
*(first2 + (last1 - first1)).
The second version of mismatch finds the first
iterator i in (first1, last1) such that binary_pred(
*i, *(first2 + (i - first1)) is false. The return
value is a pair whose first element is i and whose
second element is *(first2 + (i - first1)). If no
such iterator i exists, the return value is a pair
whose first element is last1 and whose second element
is *(first2 + (last1 - first1)).
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
int A1[] = { 3, 1, 4, 1, 5, 9, 3 };
int A2[] = { 3, 1, 4, 2, 8, 5, 7 };
const int N = sizeof(A1) / sizeof(int);
pair<int*, int*> result =
mismatch(A1, A1 + N, A2);
cout << "The first mismatch is in position "
<< result.first - A1 + 1 << endl;
cout << "Values are: " << *(result.first)
<< ", " << *(result.second) << endl;
return 0;
}
OUTPUT:
// The first mismatch is in position 4
// Values are: 1, 2
next_permutation 1.
/* Next_permutation transforms the range of elements
(first, last) into the lexicographically next greater
permutation of the elements. There is a finite number
of distinct permutations (at most N!, where N is
last - first), so, if the permutations are ordered by
lexicographical_compare, there is an unambiguous
definition of which permutation is lexicographically
next. If such a permutation exists, next_permutation
transforms [first, last) into that permutation and
returns true. Otherwise it transforms (first, last)
into the lexicographically smallest permutation
and returns false.
The postcondition is that the new permutation of
elements is lexicographically greater than the old
(as determined by lexicographical_compare) if and only
if the return value is true.
The two versions of next_permutation differ in how
they define whether one element is less than another.
The first version compares objects using operator<,
and the second compares objects using a function
object comp.
*/
#include <iostream>
#include <algorithm>
using namespace std;
template <class BidirectionalIterator>
void snail_sort(BidirectionalIterator first,
BidirectionalIterator last)
{
while (next_permutation(first, last)) {}
}
//--------------------------------------------
int main ()
{
int A[] = {8, 3, 6, 1, 2, 5, 7, 4};
const int N = sizeof(A) / sizeof(int);
snail_sort(A, A+N);
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5 6 7 8
nth_element 1.
/*
Nth_element is similar to partial_sort, in that it
partially orders a range of elements: it arranges
the range (first, last) such that the element pointed
to by the iterator nth is the same as the element that
would be in that position if the entire range (first,
last) had been sorted. Additionally, none of the
elements in the range (nth, last) is less than any of
the elements in the range (first, nth).
The two versions of nth_element differ in how they
define whether one element is less than another.
The first v ersion compares objects using operator<,
and the second compares objects using a function
object comp.
The postcondition for the first version of nth_element
is as follows. There exists no iterator i in the range
(first, nth) such that *nth < *i, and there exists
no iterator j in the range (nth + 1, last) such that
*j < *nth.
The postcondition for the second version of nth_element
is as follows. There exists no iterator i in the range
(first, nth) such that comp(*nth, *i) is true, and
there exists no iterator j in the range (nth + 1, last)
such that comp(*j, *nth) is true.
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5};
const int N = sizeof(A) / sizeof(int);
nth_element(A, A + 6, A + N);
copy(A, A + N, ostream_iterator<int>(cout, " "));
return 0;
}
OUTPUT:
// 5 2 6 1 4 3 7 8 9 10 11 12
partial_sort 1.
/*
Partial_sort rearranges the elements in the range
(first,last) so that they are partially in ascending
order. Specifically, it places the smallest middle -
first elements, sorted in ascending order, into the
range (first, middle). The remaining last - middle
elements are placed, in an unspecified order, into the
range (middle, last).
The two versions of partial_sort differ in how they
define whether one element is less than another. The
first version compares objects using operator<, and
the second compares objects using a function object
comp.
The postcondition for the first version of partial_sort
is as follows. If i and j are any two valid iterators
in the range (first, middle) such that i precedes j,
and if k is a valid iterator in the range
(middle, last), then *j < *i and *k < *i will both
be false. The corresponding postcondition for the
second version of partial_sort is that comp(*j, *i)
and comp(*k, *i) are both false.
Informally, this postcondition means that the first
middle - first elements are in ascending order and that
none of the elements in [middle, last) is less than any
of the elements in (first, middle).
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5};
const int N = sizeof(A) / sizeof(int);
partial_sort(A, A + 5, A + N);
copy(A, A + N, ostream_iterator<int>(cout, " "));
return 0;
}
OUTPUT:
// 1 2 3 4 5 11 12 10 9 8 7 6
partial_sort_copy 1.
/*
Partial_sort_copy copies the smallest N elements from
the range (first, last) to the range (result_first,
result_first + N), where N is the smaller of last -
first and result_last - result_first. The elements in
(result_first, result_first + N) will be in ascending
order. The two versions of partial_sort_copy differ in
how they define whether one element is less than
another. The first version compares objects using
operator<, and the second compares objects using a
function object comp.
The postcondition for the first version of
partial_sort_copy is as follows. If i and j are any two
valid iterators in the range (result_first, result_first
+ N) such that i precedes j, then *j < *i will be
false. The corresponding postcondition for the second
version is that comp(*j, *i) will be false.
The return value is result_first + N.
*/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5};
const int N = sizeof(A) / sizeof(int);
vector V(4);
partial_sort_copy(A, A + N, V.begin(), V.end());
copy(V.begin(), V.end(),
ostream_iterator<int>(cout, " "));
return 0;
}
OUTPUT:
// 1 2 3 4
partition 1.
/*
partition - Partition a range using a predicate.
begin - Returns an iterator that points to the
first element in a sequence.
end - Returns an iterator that points one past
the end of a sequence.
bind2nd - Returns true for elements for which the
condition is true.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector IntVector ;
// Define an iterator for template class vector
// of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE); //vector containing
// numbers
IntVectorIt start, end, it;
start = Numbers.begin(); // location of first
// element of Numbers
end = Numbers.end(); // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 6
Numbers[1] = 20;
Numbers[2] = 10;
Numbers[3] = 15;
Numbers[4] = 12;
Numbers[5] = 7;
Numbers[6] = 9;
Numbers[7] = 10;
cout << "Before calling partition" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// partition the sequence such that all the elements
// less than 11 appear before all the elements
// greater than 11
it = partition(start, end, bind2nd(less<int>(),11));
cout << "After calling partition" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
return 0;
}
OUTPUT:
// Before calling partition
// Numbers { 6 20 10 15 12 7 9 10 }
//
// After calling partition
// Numbers { 6 10 10 9 7 12 15 20 }
pop_heap 1.
/*
Pop_heap removes the largest element (that is, *first)
from the heap (first, last). The two versions of
pop_heap differ in how they define whether one element
is less than another. The first version compares
objects using operator<, and the second compares
objects using a function object comp.
The postcondition for the first version of pop_heap is
that is_heap(first, last-1) is true and that
*(last - 1)
is the element that was removed from the heap. The
postcondition for the second version is that
is_heap(first, last-1, comp) is true and that
*(last - 1)
is the element that was removed from the heap.
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {1, 2, 3, 4, 5, 6};
const int N = sizeof(A) / sizeof(int);
make_heap(A, A+N);
cout << "Before pop: ";
copy(A, A+N, ostream_iterator<int>(cout, " "));
pop_heap(A, A+N);
cout << endl << "After pop: ";
copy(A, A+N-1, ostream_iterator<int>(cout, " "));
cout << endl << "A[N-1] = " << A[N-1] << endl;
}
OUTPUT:
// Before pop: 6 5 3 4 2 1
// After pop: 5 4 3 1 2
// A[N-1] = 6
power 1.
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
cout << "2 ** 30 = " << power(2, 30) << endl;
return 0;
}
OUTPUT:
// 2 ** 30 = 1073741824
prev_permutation 1.
/*
Prev_permutation transforms the range of elements
(first, last) into the lexicographically next smaller
permutation of the elements. There is a finite number
of distinct permutations (at most N!, where N is
last - first), so, if the permutations are ordered
by lexicographical_compare, there is an unambiguous
definition of which permutation is lexicographically
previous. If such a permutation exists,
prev_permutation transforms [first, last) into that
permutation and returns true. Otherwise it transforms
(first, last) into the lexicographically greatest
permutation and returns false.
The postcondition is that the new permutation of
elements is lexicographically less than the old (as
determined by lexicographical_compare) if and only if
the return value is true.
The two versions of prev_permutation differ in how they
define whether one element is less than another. The
first version compares objects using operator<, and
the second compares objects using a function object
comp.
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {2, 3, 4, 5, 6, 1};
const int N = sizeof(A) / sizeof(int);
cout << "Initially: ";
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
prev_permutation(A, A+N);
cout << "After prev_permutation: ";
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
next_permutation(A, A+N);
cout << "After next_permutation: ";
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
OUTPUT:
// Initially: 2 3 4 5 6 1
// After prev_permutation: 2 3 4 5 1 6
// After next_permutation: 2 3 4 5 6 1
replace_copy_if 1.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of integers
typedef vector<int> IntVector ;
// Define an iterator for template class vector
// of integer
typedef IntVector::iterator IntVectorIt ;
//vector containing numbers
IntVector Numbers(MAX_ELEMENTS),Result(MAX_ELEMENTS);
IntVectorIt start, end, it, last, resultIt;
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
resultIt = Result.begin() ; // location of first
// element of Result
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// copy all elements from Numbers to Result
// replacing any item that >= 10 with 30
last = replace_copy_if(start, end, resultIt,
bind2nd(greater_equal<int>(), 10), 30);
//print number of elements copied to Result
cout << "Total number of elements copied to Result = "
<< last - resultIt << endl ;
start = Result.begin() ; // location of first
// element of Result
end = Result.end() ; // one past the location
// last element of Result
// print content of Result
cout << "Result { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
OUTPUT:
// Numbers { 10 20 10 15 12 7 9 10 }
// Total number of elements copied to Result = 8
// Result { 30 30 30 30 30 7 9 30 }
push_heap 1.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
make_heap(A, A + 9);
cout << "[A, A + 9) = ";
copy(A, A + 9, ostream_iterator<int>(cout, " "));
push_heap(A, A + 10);
cout << endl << "[A, A + 10) = ";
copy(A, A + 10, ostream_iterator<int>(cout, " "));
cout << endl;
}
OUTPUT:
// [A, A + 9) = 8 7 6 3 4 5 2 1 0
// [A, A + 10) = 9 8 6 3 7 5 2 1 0 4
random_shuffle 1.
Random_shuffle randomly rearranges the elements in
the range [first, last).
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
const int N = 8;
int A[] = {1, 2, 3, 4, 5, 6, 7, 8};
random_shuffle(A, A + N);
copy(A, A + N, ostream_iterator<int>(cout, " "));
}
OUTPUT:
// The printed result might be 7 1 6 3 2 5 4 8,
// or any of 40,319 other possibilities.
remove 1.
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
list coll;
// insert elements from 6 to 1 and 1 to 6
for (int i=1; i<=6; ++i) {
coll.push_front(i);
coll.push_back(i);
}
// print all elements of the collection
cout << "pre: ";
copy (coll.begin(), coll.end(), // source
ostream_iterator<int>(cout," "));
// destination
cout << endl;
// remove all elements with value 3
remove (coll.begin(), coll.end(), // range
3); // value
// print all elements of the collection
cout << "post: ";
copy (coll.begin(), coll.end(), // source
ostream_iterator<int>(cout," "));
// destination
cout << endl;
return 0;
}
OUTPUT:
// pre: 6 5 4 3 2 1 1 2 3 4 5 6
// post: 6 5 4 2 1 1 2 4 5 6 5 6
remove_copy 1.
// Print all nonzero elements of a vector on the
// standard output.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector V;
V.push_back(-2);
V.push_back(0);
V.push_back(-1);
V.push_back(0);
V.push_back(1);
V.push_back(2);
remove_copy(V.begin(), V.end(),
ostream_iterator<int>(cout, " "),
0);
return 0;
}
OUTPUT:
// -2 -1 1 2
remove_copy_if 1.
// Fill a vector with the nonnegative elements
// of another vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
vector<int> V1;
V1.push_back(-2);
V1.push_back(0);
V1.push_back(-1);
V1.push_back(0);
V1.push_back(1);
V1.push_back(2);
vector<int> V2;
remove_copy_if(V1.begin(), V1.end(),
back_inserter(V2),
bind2nd(less<int>(), 0));
copy(V2.begin(),V2.end(),
ostream_iterator<int>(cout," "));
cout << endl;
return 0;
}
OUTPUT:
// 0 0 1 2
remove_if 1.
// Remove all even numbers from a vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
vector<int> V;
V.push_back(1);
V.push_back(4);
V.push_back(2);
V.push_back(8);
V.push_back(5);
V.push_back(7);
copy(V.begin(), V.end(),
ostream_iterator<int>(cout, " "));
vector<int>::iterator new_end =
remove_if(V.begin(), V.end(),
compose1(bind2nd(equal_to<int>(), 0),
bind2nd(modulus(), 2)));
V.erase(new_end, V.end());
copy(V.begin(), V.end(),
ostream_iterator<int>(cout, " "));
return 0;
}
OUTPUT:
// 1 4 2 8 5 7
// 1 5 7
replace_if 1.
// replace_if - Replace all elements from the sequence that
// satisfies a predicate with a specified value.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
// Define an iterator for template class vector
// of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE);
//vector containing numbers
IntVectorIt start, end, it ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
cout << "Before calling replace_if" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// replace all elements from Numbers that
// are <= 10 with 4
replace_if(start, end,
bind2nd(less_equal<int>(), 10), 4 ) ;
cout << "After calling replace_if" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
OUTPUT:
// Before calling replace_if
// Numbers { 10 20 10 15 12 7 9 10 }
// After calling replace_if
// Numbers { 4 20 4 15 12 4 4 4 }
replace 1.
// replace - Replace all elements from the sequence
// that match value with another value.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
// Define an iterator for template class vector
// of integer
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE);
//vector containing numbers
IntVectorIt start, end, it ;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
//Initialize vector Numbers
Numbers[0] = 10 ;
Numbers[1] = 20 ;
Numbers[2] = 10 ;
Numbers[3] = 15 ;
Numbers[4] = 12 ;
Numbers[5] = 7 ;
Numbers[6] = 9 ;
Numbers[7] = 10 ;
cout << "Before calling replace" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// remove all elements from Numbers that match 10
replace(start, end, 10, 35) ;
cout << "After calling replace, to replace "
<< "all 10's with 35" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
OUTPUT:
// Before calling replace
// Numbers { 10 20 10 15 12 7 9 10 }
// After calling replace, to replace all 10's with 35
// Numbers { 35 20 35 15 12 7 9 35 }
replace_copy 1.
// replace_copy - Copy the elements of a
// sequence to another
// same-size sequence replacing any elements
// that match a value with another value.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of integers
typedef vector<int > IntVector ;
// Define an iterator for template class vector
// of integer
typedef IntVector::iterator IntVectorIt ;
//vector containing numbers
IntVector Numbers(MAX_ELEMENTS),Result(MAX_ELEMENTS);
IntVectorIt start, end, it, last, resultIt;
//Initialize vector Numbers
Numbers[0] = 10;
Numbers[1] = 20;
Numbers[2] = 10;
Numbers[3] = 15;
Numbers[4] = 12;
Numbers[5] = 7;
Numbers[6] = 9;
Numbers[7] = 10;
start = Numbers.begin() ; // location of first
// element of Numbers
end = Numbers.end() ; // one past the location
// last element of Numbers
resultIt = Result.begin() ; // location of first
// element of Result
// print content of Numbers
cout << "Numbers { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// copy all elements from Numbers to Result
// replacing any item that equals 10 with 30
last = replace_copy(start, end, resultIt, 10, 30) ;
//print number of elements copied to Result
cout << "Total number of elements copied to Result = "
<< last - resultIt << endl ;
start = Result.begin() ; // location of first
// element of Result
end = Result.end() ; // one past the location
// last element of Result
// print content of Result
cout << "Result { " ;
for(it = start; it != end; it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
OUTPUT:
// Numbers { 10 20 10 15 12 7 9 10 }
// Total number of elements copied to Result = 8
// Result { 30 20 30 15 12 7 9 30 }
reverse 1.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
vector<int> v(5);
iota(v.begin(),v.end(),1);
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// reverse order of elements
reverse (v.begin(), v.end());
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// reverse order from second to last
// element but one
reverse (v.begin()+1, v.end()-1);
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// print all of them in reverse order
reverse_copy (v.begin(), v.end(), // source
ostream_iterator<int>(cout," "));
// destination
cout << endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5
// 5 4 3 2 1
// 5 2 3 4 1
// 1 4 3 2 5
rotate 1.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
vector v(10);
iota(v.begin(),v.end(),1);
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// rotate one element to the leftv
rotate (v.begin(), // beginning of range
v.begin() + 1, // new first element
v.end()); // end of range
cout << "one left: ";
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// rotate two elements to the right
rotate (v.begin(), // beginning of range
v.end() - 2, // new first element
v.end()); // end of range
cout << "two right: ";
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// rotate so that element with value 4 is
// the beginning
rotate (v.begin(), // beginning of range
find(v.begin(),v.end(),4),
// new first element
v.end()); // end of range
cout << "4 first: ";
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5 6 7 8 9 10
// one left: 2 3 4 5 6 7 8 9 10 1
// two right: 10 1 2 3 4 5 6 7 8 9
// 4 first: 4 5 6 7 8 9 10 1 2 3
rotate_copy 1.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
vector<int> v(10);
iota(v.begin(),v.end(),1);
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// print elements rotated one element to the left
vector<int>::iterator pos = v.begin();
advance(pos,1);
rotate_copy(v.begin(), // beginning of source
pos, // new first element
v.end(), // end of source
ostream_iterator<int>(cout," "));
// destination
cout << endl;
// print elements rotated two elements to the right
pos = v.end();
advance(pos,-2);
rotate_copy(v.begin(), // beginning of source
pos, // new first element
v.end(), // end of source
ostream_iterator<int>(cout," "));
// destination
cout << endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5 6 7 8 9 10
// 2 3 4 5 6 7 8 9 10 1
// 9 10 1 2 3 4 5 6 7 8
search 1.
// searches one container for a sequence in another
// container
#include <iostream>
#include <algorithm>
using namespace std;
int source[] = { 11, 44, 33, 11, 22, 33, 11, 22, 44 };
int pattern[] = { 11, 22, 33 };
int main ()
{
int* ptr;
ptr = search (source, source+9, pattern, pattern+3);
if (ptr == source+9) // if past-the- end
cout << "No match found\n";
else
cout << "Match at " << (ptr - source) << endl;
return 0;
}
OUTPUT:
// Match at 3
search_n 1.
#include <iostream>
#include <deque>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
deque<int> de(10);
iota(de.begin(),de.end(),1);
copy(de.begin(),de.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// find four consecutive elements with value 3
deque<int>::iterator pos;
pos = search_n (de.begin(), de.end(), // range
4, // count
3); // value
// print result
if (pos != de.end())
{
cout << "four consecutive elements with value 3 "
<< "start with " << distance(de.begin(),pos)+1
<< ". element" << endl;
}
else
{
cout << "no four consecutive elements with "
<< "value 3 found" << endl;
}
// find four consecutive elements with
// value greater than 3
pos = search_n (de.begin(), de.end(), // range
4, // count
3, // value
greater<int>()); // criterion
// print result
if (pos != de.end())
{
cout << "four consecutive elements with value > 3 "
<< "start with " << distance(de.begin(),pos)+1
<< ". element" << endl;
}
else
{
cout << "no four consecutive elements with "
<< "value > 3 found" << endl;
}
return 0;
}
OUTPUT:
// 1 2 3 4 5 6 7 8 9 10
// no four consecutive elements with value 3 found
// four consecutive elements with value > 3 start
// with 4. element
set_difference 1.
// Set_difference constructs a sorted range
// that is the
// set difference of the sorted ranges [first1, last1]
// and [first2, last2]. The return value is the end of
// the output range.
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
inline bool lt_nocase(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
//---------------------------------------------------
int main()
{
int A1[] = {1, 3, 5, 7, 9, 11};
int A2[] = {1, 1, 2, 3, 5, 8, 13};
char A3[] = {'a','b','b','B','B','f','g','h','H'};
char A4[] = {'A','B','B','C','D','F','F','H' };
const int N1 = sizeof(A1) / sizeof(int);
const int N2 = sizeof(A2) / sizeof(int);
const int N3 = sizeof(A3);
const int N4 = sizeof(A4);
cout << "Difference of A1 and A2: ";
set_difference(A1, A1 + N1, A2, A2 + N2,
ostream_iterator<int>(cout, " "));
cout << endl
<< "Difference of A3 and A4: ";
set_difference(A3, A3 + N3, A4, A4 + N4,
ostream_iterator<char>(cout, " "),
lt_nocase);
cout << endl;
return 0;
}
OUTPUT:
// Difference of A1 and A2: 7 9 11
// Difference of A3 and A4: B B g H
set_intersection 1.
// Set_intersection constructs a sorted range that
// is the intersection of the sorted ranges
// [first1, last1] and [first2, last2]. The return
// value is the end of the output range.
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
inline bool lt_nocase(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
//------------------------------------------
int main()
{
int A1[] = {1, 3, 5, 7, 9, 11};
int A2[] = {1, 1, 2, 3, 5, 8, 13};
char A3[] = {'a','b','b','B','B','f','h','H'};
char A4[] = {'A','B','B','C','D','F','F','H' };
const int N1 = sizeof(A1) / sizeof(int);
const int N2 = sizeof(A2) / sizeof(int);
const int N3 = sizeof(A3);
const int N4 = sizeof(A4);
cout << "Intersection of A1 and A2: ";
set_intersection(A1, A1 + N1, A2, A2 + N2,
ostream_iterator<int>(cout, " "));
cout << endl
<< "Intersection of A3 and A4: ";
set_intersection(A3, A3 + N3, A4, A4 + N4,
ostream_iterator<char>(cout, " "),
lt_nocase);
cout << endl;
return 0;
}
OUTPUT:
// Intersection of A1 and A2: 1 3 5
// Intersection of A3 and A4: a b b f h
set_symmetric_difference 1.
// Set_symmetric_difference constructs a sorted
// range that is the set symmetric difference of
// the sorted ranges [first1, last1) and [first2, last2].
// The return value is the end of the output range.
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
inline bool lt_nocase(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
//------------------------------------------
int main()
{
int A1[] = {1, 3, 5, 7, 9, 11};
int A2[] = {1, 1, 2, 3, 5, 8, 13};
char A3[] = {'a','b','b','B','B','f','g','h','H'};
char A4[] = {'A','B','B','C','D','F','F','H'};
const int N1 = sizeof(A1) / sizeof(int);
const int N2 = sizeof(A2) / sizeof(int);
const int N3 = sizeof(A3);
const int N4 = sizeof(A4);
cout << "Symmetric difference of A1 and A2: ";
set_symmetric_difference(A1, A1 + N1, A2, A2 + N2,
ostream_iterator<int>(cout, " "));
cout << endl
<< "Symmetric difference of A3 and A4: ";
set_symmetric_difference(A3, A3 + N3, A4, A4 + N4,
ostream_iterator<char>(cout, " "),
lt_nocase);
cout << endl;
return 0;
}
OUTPUT:
// Symmetric difference of A1 and A2: 1 2 7 8 9 11 13
// Symmetric difference of A3 and A4: B B C D F g H
set_union 1.
// Set_union constructs a sorted range that is the union
// of the sorted ranges [first1, last1] and
// [first2, last2].
// The return value is the end of the output range.
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
inline bool lt_nocase(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
//------------------------------------------
int main()
{
int A1[] = {1, 3, 5, 7, 9, 11};
int A2[] = {1, 1, 2, 3, 5, 8, 13};
char A3[] = {'a','b','B','B','f','H'};
char A4[] = {'A','B','b','C','D','F','F','h','h'};
const int N1 = sizeof(A1) / sizeof(int);
const int N2 = sizeof(A2) / sizeof(int);
const int N3 = sizeof(A3);
const int N4 = sizeof(A4);
cout << "Union of A1 and A2: ";
set_union(A1, A1 + N1, A2, A2 + N2,
ostream_iterator<int>(cout, " "));
cout << endl
<< "Union of A3 and A4: ";
set_union(A3, A3 + N3, A4, A4 + N4,
ostream_iterator<char>(cout, " "),
lt_nocase);
cout << endl;
}
OUTPUT:
// Union of A1 and A2: 1 1 2 3 5 7 8 9 11 13
// Union of A3 and A4: a b B B C D f F H h
sort_heap 1.
// Sort_heap turns a heap [first, last) into a sorted
// range. Note that this is not a stable sort: the relative
// order of equivalent elements is not guaranteed to be
// preserved
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(int);
make_heap(A, A+N);
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
sort_heap(A, A+N);
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
OUTPUT:
// 8 5 7 4 1 2
// 1 2 4 5 7 8
stable_partition 1.
// Stable_partition is an adaptive algorithm: it attempts
// to allocate a temporary memory buffer, and its run-time
// complexity depends on how much memory is available.
// Worst-case behavior (if no auxiliary memory is
// available) is at most N*log(N) swaps, where N is
// last - first, and best case (if a large enough
// auxiliary memory buffer is available) is linear in N.
// In either case, pred is applied exactly N times.
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
// Reorder a sequence so that even numbers
// precede odd numbers.
int main()
{
int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const int N = sizeof(A)/sizeof(int);
stable_partition(A, A + N,
compose1(bind2nd(equal_to<int>(), 0),
bind2nd(modulus<int>(), 2)));
copy(A, A + N,
ostream_iterator<int>(cout, " "));
return 0;
}
OUTPUT:
// 2 4 6 8 10 1 3 5 7 9
stable_sort 1.
// Stable_sort is much like sort: it sorts the elements
// in (first, last) into ascending order, meaning that
// if i and j are any two valid iterators in (first,
// last) such that i precedes j, then *j is not less
// than *i.
// Stable_sort differs from sort in two ways. First,
// stable_sort uses an algorithm that has different
// run-time complexity than sort. Second, as the name
// suggests, stable_sort is stable: it preserves the
// relative ordering of equivalent elements. That is,
// if x and y are elements in (first, last) such that x
// precedes y, and if the two elements are equivalent
// (neither x < y nor y < x) then a postcondition
// of stable_sort is that x still precedes y.
#include <iostream>
#include <algorithm>
#include <cctype>
#include <cstdio>
using namespace std;
inline bool lt_nocase(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
//-------------------------------------
int main()
{
char A[] = "fdBeACFDbEac";
const int N = sizeof(A) - 1;
stable_sort(A, A+N, lt_nocase);
printf("%s\n", A);
return 0;
}
OUTPUT:
// AaBbCcdDeEfF
swap_ranges 1.
// Swap_ranges swaps each of the elements in the range
// [first1, last1] with the corresponding element in the
// range (first2, first2 + (last1 - first1)). That is,
// for each integer n such that 0 <= n < (last1 -
// first1), it swaps *(first1 + n) and *(first2 + n).
// The return value is first2 + (last1 - first1).
#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>
int main ()
{
vector<int> V1, V2;
V1.push_back(1);
V1.push_back(2);
V2.push_back(3);
V2.push_back(4);
assert(V1[0] == 1 && V1[1] == 2 &&
V2[0] == 3 && V2[1] == 4);
swap_ranges(V1.begin(), V1.end(), V2.begin());
assert(V1[0] == 3 && V1[1] == 4 &&
V2[0] == 1 && V2[1] == 2);
copy(V1.begin(),V1.end(),
ostream_iterator<int>(cout," "));
cout << endl;
copy(V2.begin(),V2.end(),
ostream_iterator<int>(cout," "));
cout << endl;
return 0;
}
OUTPUT:
// 3 4
// 1 2
swap 1.
#include <iostream>
#include <assert>
#include $ltalgorithm>
using namespace std;
int main ()
{
int x = 1;
int y = 2;
cout << "x = " << x << " y = " << y << endl;
assert(x == 1 && y == 2);
swap(x, y);
assert(x == 2 && y == 1);
cout << "x = " << x << " y = " << y << endl;
return 0;
}
OUTPUT:
// x = 1 y = 2
// x = 2 y = 1
transform 1.
// uses transform() to change array of inches value
// to centimeters.
#include <iostream>
#include <algorithm>
using namespace std;
double inch_to_cm (double in)
{
return ( in * 2.54 );
}
//----------------------------------------------------
int main ()
{
// array of inches values
double inches[] = { 3.5, 6.2, 1.0, 12.87, 4.35 };
double centi[5];
double inch_to_cm (double);
transform (inches, inches+5, centi, inch_to_cm);
for (int j=0; j<5; j++)
cout << centi[j] << ' ';
cout << endl;
return 0;
}
OUTPUT:
// 8.89 15.748 2.54 32.6898 11.049
unique 1.
// Remove duplicates from consecutive groups
// of equal ints.
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
{
vector V;
V.push_back(1);
V.push_back(3);
V.push_back(3);
V.push_back(3);
V.push_back(2);
V.push_back(2);
V.push_back(1);
vector<int>::iterator new_end =
unique(V.begin(), V.end());
copy(V.begin(), new_end,
ostream_iterator<int>(cout, " "));
return 0;
}
OUTPUT:
// 1 3 2 1
unique 2.
// Remove all duplicates from a vector of chars,
// ignoring case. First sort the vector, then remove
// duplicates from consecutive groups.
#include <iostream>
#include <algorithm>
#include <vector>
#include <cctype>
using namespace std;
inline bool eq_nocase(char c1, char c2)
{
return tolower(c1) == tolower(c2);
}
inline bool lt_nocase(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
//------------------------------------------------
int main()
{
const char init[] =
"The Standard Template Library";
vector<char> V(init, init + sizeof(init));
sort(V.begin(), V.end(), lt_nocase);
copy(V.begin(), V.end(),
ostream_iterator<char>(cout));
cout << endl;
vector<char>::iterator new_end =
unique(V.begin(), V.end(), eq_nocase);
copy(V.begin(), new_end,
ostream_iterator<char>(cout));
cout << endl;
return 0;
}
OUTPUT:
// aaaabddeeehiLlmnprrrStTtTy
// abdehiLmnprSty
upper_bound 1.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = { 1, 2, 3, 3, 3, 5, 8 };
const int N = sizeof(A) / sizeof(int);
for (int i = 1; i <= 10; ++i) {
int* p = upper_bound(A, A + N, i);
cout << "Searching for " << i << ". ";
cout << "Result: index = " << p - A << ", ";
if (p != A + N)
cout << "A[" << p - A << "] == " << *p << endl;
else
cout << "which is off-the-end." << endl;
}
}
OUTPUT:
// The output is:
// Searching for 1. Result: index = 1, A[1] == 2
// Searching for 2. Result: index = 2, A[2] == 3
// Searching for 3. Result: index = 5, A[5] == 5
// Searching for 4. Result: index = 5, A[5] == 5
// Searching for 5. Result: index = 6, A[6] == 8
// Searching for 6. Result: index = 6, A[6] == 8
// Searching for 7. Result: index = 6, A[6] == 8
// Searching for 8. Result: index = 7,
// which is off-the-end.
// Searching for 9. Result: index = 7,
// which is off-the-end.
// Searching for 10. Result: index = 7,
// which is off-the-end.
partial_sum 1.
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> v(5);
iota(v.begin(),v.end(),1);
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
// print all partial sums
partial_sum (v.begin(), v.end(), // source range
ostream_iterator<int>(cout," ")); // destination
cout << endl;
// print all partial products
partial_sum (v.begin(), v.end(), // source range
ostream_iterator<int>(cout," "), // destination
multiplies<int>()); // operation
cout << endl;
return 0;
}
OUTPUT:
// 1 2 3 4 5
// 1 3 6 10 15
// 1 2 6 24 120