您的位置:首页 > 其它

82 stl(二)

2016-04-10 11:06 375 查看

类函数

#include<iostream>
using namespace std;

class FunObj
{
public:
void operator()()
{
cout << "hello!" << endl;
}

void operator()(int n)
{
cout << "hello2!" << endl;
}
};
int main(void)
{
FunObj fo;
fo();
fo(1);

FunObj()();
return 0;
}


Vector

#include <vector>
#include <string>
#include <iostream>
#include <algorithm>

using namespace std;

void PrintFun(int n)
{
cout << n << ' ';
}

void Add3(int &n)
{
n += 3;
}

class PrintObj
{
public:
void operator()(int n)
{
cout << n << ' ';
}

};
class AddObj
{
public:
AddObj(int number) :number_(number)
{

}
void operator()(int& n)
{
n += number_;
}
private:
int number_;
};

class GreaterObj
{
public:
GreaterObj(int number) :number_(number)
{

}
bool operator()(int n)
{
return n > 3;
}
private:
int number_;

};
int main(void)
{
int a[] = {1,2,3,4,5};
vector<int> v(a,a+5);

for_each(v.begin(), v.end(), PrintFun);
cout << endl;

for_each(v.begin(), v.end(), PrintObj());
cout << endl;

for_each(v.begin(), v.end(), Add3);
for_each(v.begin(), v.end(), PrintFun);
cout << endl;

for_each(v.begin(), v.end(), AddObj(5));
for_each(v.begin(), v.end(), PrintFun);
cout << endl;

cout << count_if(a, a + 5, GreaterObj(3)) << endl;

return 0;
}


Map

#include <map>
#include <string>
#include <iostream>

using namespace std;

struct MyGreater
{
bool operator()(int left, int right)
{
return left > right;
}
};
int main(void)
{
map<int, string,MyGreater>mapTest;
mapTest.insert(map<int, string>::value_type(1, "aaaa"));
mapTest.insert(map<int, string>::value_type(3, "cccc"));
mapTest.insert(map<int, string>::value_type(2, "bbbb"));

for (map<int, string,MyGreater>::const_iterator it = mapTest.begin(); it != mapTest.end(); ++it)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  类函数