Algorithm (C++)
Appearance
C++ Standard Library |
---|
Containers |
C standard library |
In the C++ programming language, algorithms are components that perform algorithmic operations on containers and other sequences.[1]
The C++ standard provides some standard algorithms collected in the <algorithm> standard header. All algorithms are in the std
namespace.
A few of the most commonly used algorithms are:
void copy(ForwardIterator source_begin, ForwardIterator source_end, ForwardIterator destination_begin)
void fill(ForwardIterator destination_begin, ForwardIterator destination_end, T value)
ForwardIterator find(ForwardIterator begin, ForwardIterator end, T search_object)
(returns an iterator the found object orend
if the object isn't found)T max(T a, T b)
returns the greater of the two argumentsForwardIterator max_element(ForwardIterator begin, ForwardIterator end)
finds the maximum element of a rangeT min(T a, T b)
returns the smaller of the two argumentsForwardIterator min_element(ForwardIterator begin, ForwardIterator end)
finds the minimum element of a range
Usage
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v1(3, 42); // Create an array of three integers, all equal to 42.
vector<int> v2(5, 0); // Create an array of five integers, all zero.
copy(v1.begin(), v1.end(), v2.begin()); // Copy all three elements from v1 to v2.
// Now v2 contains { 42, 42, 42, 0, 0 }.
fill(v1.begin(), v1.end(), 100); // Replace every element of v1 with "100".
// Now v1 is { 100, 100, 100 }.
if (find(v1.begin(), v1.end(), 0) == v1.end()) {
// find() ends up at the last element of v1 since no results found
// thus find() == vi.end()
cout << "v1 doesn't contain a 0." << endl; // This will be the case.
} else {
cout << "v1 contains a 0." << endl; // This won't be the case since v1 is all 100s.
}
cout << "The bigger of 12.9 and 56.7 is " << max(12.9, 56.7) << "." << endl;
// etc.
return 0;
}
References
- ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §25 Algorithms library [lib.algorithms] para. 1