#include <iostream>
#include <vector>
#include <algorithm>
#include <functional> //排序时greater/less 的头文件
using namespace std;
void func1()
{
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
v.push_back(5);
v.push_back(4);
vector<int>::iterator it; //作用域解析符
for(it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
int ret=count(v.begin(),v.end(),3);
cout<<"3的个数: "<<ret<<endl;
sort(v.begin(),v.end(),greater<int>());//默认是递增的
for(it=v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
class Student
{
public:
Student(int age,char *name)
{
this->age=age;
this->name=name;
}
void print()
{
printf ("age = %d, name = %s\n", age, name);
}
private:
int age;
char *name;
};
void fun2()
{
vector<Student> v;
Student s1(10, "小明");
Student s2(11, "小明");
Student s3(12, "小明");
Student s4(13, "小明");
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
vector<Student>::iterator it = v.begin();
while (it != v.end())
{
it->print();
it++;
}
}
void fun3()
{
vector<Student*> v;
Student *s1=new Student(10, "小明");
Student *s2=new Student(11, "小明");
Student *s3=new Student(12, "小明");
Student *s4=new Student(13, "小明");
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
vector<Student*>::iterator it = v.begin();
while (it != v.end())
{
(*it)->print();//类指针
it++;
}
}
int main()
{
func1();
cout<<endl;
fun2();
cout<<endl;
fun3();
cout<<endl;
return 0;
}
STL六大组建 容量 迭代器 算法
最新推荐文章于 2022-07-27 16:15:43 发布