stl疑问二: stl 中for_each, mem_fun, bind1st 的具体用法。

 对于容器的操作,例如循环,以前总是习惯自己写,这样就有可能很容易错,所以我要尽量使用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

这个解释的会更清楚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值