Algorithm (C++)

From Wikipedia, the free encyclopedia

In the C++ programming language, algorithm is a function template that can work with (theoretically) any container containing values of any type. However, this is not always true because algorithms may have restrictions on the container/iterator category or even have requirements on the value type.

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 the found object or end if the object isn't found)
  • T max(T a, T b) returns the greater of the two arguments
  • ForwardIterator max_element(ForwardIterator begin, ForwardIterator end) finds the maximum element of a range
  • T min(T a, T b) returns the smaller of the two arguments
  • ForwardIterator min_element(ForwardIterator begin, ForwardIterator end) finds the minimum element of a range

[edit] 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;
 }

[edit] External links