STL 累加

/*其中的 std::plus<int>() 可以省略,因为这将是3个参数的 accumulate 的默认行为 */

 

#include "stdafx.h"

#include <string> 
#include <iostream> 
#include <numeric>
#include <vector> 
#include <algorithm> 
#include <functional> 
#include <map>

#include "boost/tuple/tuple.hpp" 
#include "boost/tuple/tuple_comparison.hpp" 
#include "boost/tuple/tuple_io.hpp" 

#include "boost/array.hpp" 
#include "boost/assign/list_of.hpp" 

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
using namespace boost::lambda;

//#include <boost/bind.hpp>

class Person
{
public:
	Person(){}
	Person(const std::string& name) : name_(name){}

	std::string& Name()
	{ return name_; }

private:
	std::string name_;
};

int main()
{
	std::vector<int> vect1(4);
	int i = 0;
	std::for_each( vect1.begin(), vect1.end(), _1 = ++var(i) );

	std::cout << "1. int Accumulate: " <<
		std::accumulate( vect1.begin(), vect1.end(), 0, std::plus<int>()) << '\n';

	std::vector<std::string> vect;
	vect.push_back("1");
	vect.push_back("2");
	vect.push_back("3");
	vect.push_back("4");

	std::cout << "2. str Accumulate: " <<
		std::accumulate( vect.begin(), vect.end(), std::string("0")) << '\n';

	std::cout << "3. str Accumulate: " <<
		std::accumulate( vect.begin(), vect.end(), std::string("0"),bind(std::plus<std::string>(),boost::ref(_1),_2+",")) << '\n';

	std::cout << "4. for_each Accumulate: ";
	std::string result("0");
	std::for_each( vect.begin(), vect.end(), result +=  "," +_1 );
	std::cout << result << '\n';

	std::cout << "-------------------------------------"<< '\n';

	std::map<int, std::string> persons;
	persons[123] = "Amy";
	persons[234] = "Ralph";
	persons[345] = "Simon";
	persons[456] = "Maggie";

	std::cout << "5. map Accumulate: " <<
	std::cout << std::accumulate( persons.begin(), persons.end(), 0,
		bind(std::plus<int>(), _1, bind(&std::map<int, std::string>::value_type::first, _2)) )
		<< '\n';

	std::cout << "6. map Accumulate: " <<
	std::cout << std::accumulate( persons.begin(), persons.end(), std::string(),
		bind(std::plus<std::string>(), _1, bind(&std::map<int, std::string>::value_type::second, _2)) +"," )
		<< '\n';

   std::cout << "-------------------------------------"<< '\n';

   std::map<int, Person> persons1;
   persons1[123] = Person("Amy");

   result = "";
   std::for_each( persons1.begin(), persons1.end(), 
	   result += bind(&Person::Name, bind(&std::map<int, Person>::value_type::second, _1)));

   std::cout << "7. map Accumulate: " <<
   std::cout << result << '\n';
	return 0;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值