对于容器的操作,例如循环,以前总是习惯自己写,这样就有可能很容易错,所以我要尽量使用stl库或者已经成熟的sdk,下面我就介绍一些stl中的for_each
今天,老大,给了个关于for_each 的用法的练习题; 结果我想了好久,都不知道,错在那儿,后来,老大的提示下。我开始试着尝试,后来才正常运行。
下面是正确实例:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
class A
{
public:
A() {}
~A() {}
void printf(std::string info)
{
std::cout << info.c_str() << std::endl;
}
void showall()
{
std::list<std::string> mylist;
mylist.push_back("hello");
// TODO: 使用for_each调用A::printf函数访问每个元素
for_each(mylist.begin(),mylist.end(),bind1st(mem_fun(&A::printf),this) );
}
};
看这段代码,你肯定很有疑惑和太多的疑问,下面我把下面的几个不常用的stl的函数做简单的介绍一下,应该就可以轻松明白这段代码了。
for_each ( 起始位置beg,结束位置end,执行函数fn)
说明:对某区间[beg,end]元素素执行某种操作(fn)。
实例:
// for_each example
#include <iostream> // std::cout
#include <algorithm> // std::for_each
#include <vector> // std::vector
void myfunction (int i) { // function:
std::cout << ' ' << i;
}
struct myclass { // function object type:
void operator() (int i) {std::cout << ' ' << i;}
} myobject;
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
std::cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);
std::cout << '\n';
// or:
std::cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
std::cout << '\n';
return 0;
}
mem_fun<成员函数的返回类型, 成员函数的类>(成员函数)
说明:成员函数转换成 函数对象
实例:
// mem_fun example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main () {
vector <string*> numbers;
// populate vector of pointers:
numbers.push_back ( new string ("one") );
numbers.push_back ( new string ("two") );
numbers.push_back ( new string ("three") );
numbers.push_back ( new string ("four") );
numbers.push_back ( new string ("five") );
vector <int> lengths ( numbers.size() );
transform (numbers.begin(), numbers.end(), lengths.begin(), mem_fun(&string::length));
for (int i=0; i<5; i++) {
cout << *numbers[i] << " has " << lengths[i] << " letters.\n";
}
// deallocate strings:
for (vector<string*>::iterator it = numbers.begin(); it!=numbers.end(); ++it)
delete *it;
return 0;
}
bind1st
这个函数,我引用:http://www.cnblogs.com/weiqubo/archive/2011/02/16/1956552.html
这个解释的会更清楚。