您的位置:首页 > 其它

【STL】for_each使用示例

2016-08-03 15:14 549 查看
[cpp] view
plain copy

print?

void myfun1(int& i)

{

std::cout << i << " ";

}

void myfun2(int i, const char* prefix)

{

std::cout << prefix << i << std::endl;

}

struct mystruct1 {

void operator() (int& i)

{

std::cout << i << " ";

}

} myobject1;

struct mystruct2 {

const char* prefix_;

mystruct2(const char* prefix): prefix_(prefix) {}

void operator() (int& i) {

std::cout << prefix_ << i << std::endl;

}

};

class myclass1

{

public:

void operator() (int& i)

{

std::cout << i << " ";

}

};

class myclass2

{

public:

const char* prefix_;

myclass2(const char* prefix): prefix_(prefix){};

void operator() (int& i)

{

std::cout << i << " ";

}

};

void test_for_each()

{

int ar[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

std::vector<int> v(ar, ar + 9);

// 一个参数的普通函数

std::cout << "myfunction1 output below: " << std::endl;

for_each(v.begin(), v.end(), myfun1);

std::cout << std::endl;

// 二个参数的普通函数

std::cout << "myfunction2 output below: " << std::endl;

for_each(v.begin(), v.end(), std::bind2nd(std::ptr_fun(myfun2), "i = "));

// 不带参的结构体

std::cout << "mystruct1 output below: " << std::endl;

for_each(v.begin(), v.end(), mystruct1());

// for_each(v.begin(), v.end(), myobject1); // 这个方法也行.

std::cout << std::endl;

// 带参的结构体

std::cout << "mystruct2 output below: " << std::endl;

for_each(v.begin(), v.end(), mystruct2("i = "));

// 不带参的类

std::cout << "myclass1 output below: " << std::endl;

for_each(v.begin(), v.end(), myclass1());

std::cout << std::endl;

// 带参的类

std::cout << "myclass2 output below: " << std::endl;

for_each(v.begin(), v.end(), myclass2("i = "));

std::cout << std::endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  for_each
相关文章推荐