点击(此处)折叠或打开
-
#ifndef ALGOSTUFF_H
-
#define ALGOSTUFF_H
-
-
#include <iostream>
-
#include <vector>
-
#include <list>
-
#include <deque>
-
#include <set>
-
#include <map>
-
#include <string>
-
#include <algorithm>
-
#include <functional>
-
#include <numeric>
-
-
//print all the elements
-
template <class T>
-
inline void PRINT_ELEMNTS(const T &col,const char *optcstr = " ")
-
{
-
typename T::const_iterator pos;
-
cout << optcstr;
-
for(pos = col.begin();pos != col.end();++pos)
-
cout << *pos << " ";
-
cout << endl;
-
}
-
-
//insert values from first to last into the collection
-
template <class T>
-
inline void INSERT_ELEMENTS(T &col,int first,int last)
-
{
-
for(int i = first;i <= last;++i)
-
col.insert(col.end(),i);
-
}
-
- #endif
find算法
点击(此处)折叠或打开
-
template<class InputIterator, class T>
-
InputIterator find ( InputIterator first, InputIterator last, const T& value )
-
{
-
for ( ;first!=last; first++) if ( *first==value ) break;
-
return first;
- }
返回区间[first,end)中第一个值等于value的元素的位置。
如果没有找到匹配元素,则返回end。
点击(此处)折叠或打开
-
list<string> Fruit;
-
list<string>::iterator FruitIterator;
-
-
Fruit.push_back("Apple");
-
Fruit.push_back("Pineapple");
-
Fruit.push_back("Star Apple");
-
-
FruitIterator = find (Fruit.begin(), Fruit.end(),"Pineapple");
-
-
//如果没找到,则返回end
-
if (FruitIterator == Fruit.end()) {
-
cout << "Fruit not found in list" << endl;
-
}
-
else {
-
cout<< *FruitIterator <<endl;
- }
find_if()算法
template<class InputIterator, class Predicate>InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred ) 、
{
for ( ; first!=last ; first++ ) if ( pred(*first) ) break;
return first;
for ( ; first!=last ; first++ ) if ( pred(*first) ) break;
return first;
}
它在区间[first,end)中搜寻使一元判断式pred为true的第一个元素。
如果没找到,返回end。
点击(此处)折叠或打开
-
#include "algostuff.h"
-
-
using namespace std;
-
-
int main()
-
{
-
vector<int> intVec;
-
-
INSERT_ELEMENTS(intVec,1,9);
-
-
vector<int>::iterator pos;
-
pos = find_if(intVec.begin(),intVec.end(),
-
not1(bind2nd(modulus<int>(),3)));
-
-
if(pos != intVec.end())
-
cout << "The value divided by 3 exists,and the first value's position is " <<
-
distance(intVec.begin(),pos) + 1 << endl;
-
else
-
cout << "The value divided by 3 not found!" << endl;
- }