c++实例研究

从0开始

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  104 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks

原来的代码:

#include <cstdlib>
#include 
<iostream>
#include 
<vector>
using namespace std;

class trival
{
public:
    
void show(){cout<<e1<<' '<<e2<<' '<<e3<<endl;}
private:
    
int e1,e2,e3;
}
;

void show(trival& t)
{
    t.show();    
}


int main()
{
    vector
<trival> tt(5);  
    for_each(tt.begin(),tt.end(),show);
    system(
"PAUSE");
    
return 0;
}

如果我需要累加三元组的第一号元素
#include <cstdlib>
#include 
<iostream>
#include 
<vector>
using namespace std;

class trival
{
public:
    
void show(){cout<<e1<<' '<<e2<<' '<<e3<<endl;}
public:
    
int e1,e2,e3;
}
;

void show(trival& t)
{
    t.show();    
}


void inc(trival& t)
{
    t.e1
++;
}


int main()
{
    vector
<trival> tt(5);  
    for_each(tt.begin(),tt.end(),show);
    for_each(tt.begin(),tt.end(),inc);
    for_each(tt.begin(),tt.end(),show);
    system(
"PAUSE");
    
return 0;
}

问题出现了,如果我想自定义给三元组的每个元素加n呢?于是。。。
#include <cstdlib>
#include 
<iostream>
#include 
<vector>
using namespace std;

class trival
{
public:
    
void show(){cout<<e1<<' '<<e2<<' '<<e3<<endl;}
public:
    
int e1,e2,e3;
}
;

void show(trival& t)
{
    t.show();    
}


class add
{
public:
    add(
int ae1=0int ae2=0int ae3=0):adde1(ae1),adde2(ae2),adde3(ae3){}
    
void operator()(trival& t){t.e1+=adde1; t.e2+=adde2; t.e3+=adde3;}
private:
    
int adde1,adde2,adde3;
}
;

int main()
{
    vector
<trival> tt(5);  
    for_each(tt.begin(),tt.end(),show);
    for_each(tt.begin(),tt.end(),add(
1,2));
    for_each(tt.begin(),tt.end(),show);
    system(
"PAUSE");
    
return 0;
}


是不是很有意思?
posted on 2010-05-09 16:56 elprup 阅读(242) 评论(0)  编辑 收藏 引用 所属分类: c++实例

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理