C++ 查找vector容器中元素
#include<iostream>#include<vector>#include<algorithm>#include<functional>#include<string>using namespace std;void test01() {vector<int> v1;for (int i = 1; i <= 1
·
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<string>
using namespace std;
void test01() {
vector<int> v1;
for (int i = 1; i <= 10; ++i) {
v1.push_back(i);
}
vector<int>::iterator pos = find(v1.begin(), v1.end(), 5);
if (pos != v1.end()) {
cout << "find:" << *pos << endl;
}
}
class person {
friend void test02();
friend class myCompare;
private:
string name;
int age;
public:
person(string name, int age) :name(name), age(age) {}
bool operator==(person p) {
return this->name == p.name && this->age == p.age;
}
};
class myCompare:public binary_function<person, person, bool> {
public:
bool operator()(person p1, person p2)const {
return p1.age > p2.age;
}
};
void test02() {
vector<person> v2;
person p1("Tom", 21);
person p2("Andy", 23);
person p3("Tim", 25);
person p4("Jack", 28);
person p5("Lucy", 22);
person p6("David", 27);
person p7("John", 20);
v2.push_back(p1);
v2.push_back(p2);
v2.push_back(p3);
v2.push_back(p4);
v2.push_back(p5);
v2.push_back(p6);
v2.push_back(p7);
vector<person>::iterator pos = find(v2.begin(), v2.end(), p2);
cout << pos->name << " " << pos->age << endl;
pos = find_if(v2.begin(), v2.end(), bind2nd(myCompare(),p2));
cout << pos->name << " " << pos->age << endl;
}
//adjacent_find算法 查找相邻重复元素
void test03() {
vector<int> v3;
v3.push_back(3);
v3.push_back(3);
v3.push_back(46);
v3.push_back(21);
v3.push_back(27);
v3.push_back(35);
v3.push_back(46);
v3.push_back(46);
v3.push_back(3);
vector<int>::iterator res=adjacent_find(v3.begin(),v3.end());
if (res != v3.end()) {
cout << *res << endl;
}
}
void test04() {
vector<int> v4;
for (int i = 1; i <= 10; ++i) {
v4.push_back(i);
}
//必须是有顺序的
bool res = binary_search(v4.begin(), v4.end(), 2);
cout << res << endl;
if (res) {
cout << "find !" << endl;
}
}
class coutIf {
public:
bool operator()(int val) const
{
return val > 5;
}
};
void test05() {
vector<int> v5;
for (int i = 1; i <= 10; ++i) {
v5.push_back(i);
}
v5.push_back(6);
v5.push_back(6);
v5.push_back(6);
v5.push_back(6);
int res=count(v5.begin(), v5.end(), 6);
cout << "6的个数为: " << res << endl;
res = count_if(v5.begin(), v5.end(), coutIf());
cout << "cout_if: " << res << endl;
}
int main() {
test01();
cout << "-----------------------" << endl;
test02();
cout << "-----------------------" << endl;
test03();
cout << "-----------------------" << endl;
test04();
cout << "-----------------------" << endl;
test05();
system("pause");
return EXIT_SUCCESS;
}
find:5
-----------------------
Andy 23
Tim 25
-----------------------
3
-----------------------
1
find !
-----------------------
6的个数为: 5
cout_if: 9
请按任意键继续. . .
更多推荐
已为社区贡献2条内容
所有评论(0)