Algorithm (C++)


Algorithm (C++)
From Wikipedia, the free encyclopedia
Jump to: navigation, search

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 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 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
#include
#include

using namespace std;

int main() {
vector v1(3, 42); // Create an array of three integers, all equal to 42.
vector 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;
}

Tinggalkan Balasan

Please log in using one of these methods to post your comment:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s