C++/STL Algorithms

From Wikiversity
< C++
Jump to navigation Jump to search

The STL contains functions for common algorithms within C++.

find[edit | edit source]

Finds a value within a range.

Example:

#include <set>
#include <algorithm>

using namespace std;

int main()
{
     set<int> TestContainer;
     ''// Add some elements here''
     TestContainer.insert(1);
     TestContainer.insert(5);
     TestContainer.insert(3);
     TestContainer.insert(11);
     ''// Find the 3 in the container''
     set<int>::iterator MyIterator = find(TestContainer.begin(),TestContainer.end(),3);
     if(MyIterator != TestContainer.end())
          cout<<*MyIterator;
     else
          cout<< "Error: 3 is not in the container" << endl;
}

copy[edit | edit source]

Copies a range of elements.

copy_backward reverses the order of elements.


swap[edit | edit source]

Swaps two sets.

#include <iostream>
#include <algorithm>
#include <set>

using namespace std;

int main()
{
	
	set <char> sCreatedSet1 = { '1', '2', '7', '4', '5', '6', '3', '8', '9' };
	set <char> sCreatedSet2 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };
	set<char>::iterator iter1 = sCreatedSet1.begin();
	set<char>::iterator iter2 = sCreatedSet2.begin();

	cout << "-Set elements before swap-" << endl;
	for (auto y : sCreatedSet1)
	{
		cout << *iter1 << '\t' << *iter2 << endl;
		iter1++;
		iter2++;
	}
	
	swap(sCreatedSet1, sCreatedSet2);
	iter1 = sCreatedSet1.begin();
	iter2 = sCreatedSet2.begin();

	cout << "-Set elements after swap-" << endl;
	for (auto y : sCreatedSet1)
	{
		cout << *iter1 << '\t' << *iter2 << endl;
		iter1++;
		iter2++;
	}
        return 0;
}

iter_swap[edit | edit source]

Swaps two elements pointed to by iterators.

transform[edit | edit source]

Applies a function to a range.

random_shuffle[edit | edit source]

Randomly shuffles a range.

sort[edit | edit source]

Sorts elements in a range.

A stable_sort retains the original order of equal elements. A stable_sort does not provide any advantage over a simple sort of, say, a list of integer values (if the list contains multiple values of "2", it doesn't matter which "2" comes first). However, consider the example of sorting a list of Employee objects by their first name only. Two different employees may share the same first name (which gives them the ordering relative to the rest of the list). If "Bob Smith" was before to "Bob Jones" in the list prior to the sort, then stable_sort would guarantee Smith was before Jones in the sorted list; sort does not make such a guarantee. The stable_sort algorithm is marginally less efficient due to added constraint.

binary_search[edit | edit source]

Searches a sorted range for a value.

next_permutation[edit | edit source]

Transforms a range to the next permutation.

Reversed by prev_permutation.

Lessons[edit | edit source]

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science