Friday, June 27, 2008

c++ std::find algorithm example

C++ standard library has many useful features. One of which is the std::find algorithm.


Here is a simple example:
#include <iostream>
#include <algorithm>

int main() {
int data[100];
data[89] = 7;
int * where = std::find(data,data+100,7);
std::cout << *where << std::endl;
}


This will output '7'. The interesting part is the algorithm will work with any data structure not just arrays.

#include <iostream>
#include <algorithm>
#include <list>
int main() {
std::list<int> data;
data.push_back(3);
data.push_back(7);
data.push_back(9);
std::list<int>::iterator where = std::find(data.begin(),data.end(),7);
std::cout << *where << std::endl;
}


For more information I recommend the following book:
Data Structures in C++: Using the Standard Template Library (STL)

No comments: