在这里插入代码片
- vector结构
- 容器可以自定义数据,类。但是用for_each调用类方法还没学会
- 容器嵌入容器,*iterator取值,类似指针
- 友元函数访问私有变量
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
//容器vector,【v.begin和end指向哪儿,第一个的前一个,和最后一个的后一个】
void test01()
{
vector<int >v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
void myPrint(int val);//先声明,下面要先用,后定义
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<*it<<endl;
}
for_each(v.begin(),v.end(),myPrint);
}
void myPrint(int val)
{
cout <<val<<" ";
}
//容器可以自定义数据
class Person
{
friend void myPerson(Person& ob);
public:
Person(string name,int age) {
this->name=name;
this->age=age;
}
void Print(Person &ob);
private:
string name;
int age;
};
void Person::Print(Person &ob)
{
{
cout<<ob.age<<ob.name;
}
}
void myPerson(Person& ob)
{
cout<<"name="<<ob.name<<", age="<<ob.age<<endl;
}
void test02()
{
Person ob1("的吗",15);
Person ob2("的de 吗",25);
Person ob3("的dse 吗",35);
Person ob4("的dwdfg吗",45);
//ob1.myPerson(ob1);
vector<Person>v;
v.push_back(ob1);
v.push_back(ob2);
v.push_back(ob3);
v.push_back(ob4);
// for_each(v.begin(),v.end(),mem_fun1_ref_t(&Person::Print));//err
// for_each(v.begin(),v.end(),Person::show());
for_each(v.begin(),v.end(),myPerson);//正
}
//【问题,for_each如何调用类内部方法】//*****************************
//嵌套容器
void test03(){
vector<int >v1;
vector<int>v2;
vector<int>v3;
v1.push_back(10);
v1.push_back(20);
v1.push_back(30);
v2.push_back(100);
v2.push_back(200);
v2.push_back(300);
v3.push_back(1000);
v3.push_back(2000);
v3.push_back(3000);
//容器装容器
vector< vector<int> >v;
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
for(vector<vector<int>>::iterator it=v.begin();it!=v.end();it++)
{//*it==vector<int>v1,v2,v3
for(vector<int>::iterator mit=(*it).begin();mit!=(*it).end();mit++)
//*mit==int
cout<<*mit<<" ";
cout<<endl;
}
}
//string的字符存取
//char& operator[](int n);
//通过[]方式取字符
//char& at(int n);
//通过at方法获取字符
void test04()
{
string str1="hello string";
cout<<str1[1]<<endl;
cout<<str1.at(1)<<endl;
try
{
str1.at(1000)='g';
str1[1000]='g';//不抛
}
catch(exception &e)
{
cout<<"异常:"<<e.what()<<endl;
}
}
int main(int argc, char *argv[])
{
// test01();
//test02();
//test03();
test04();
return 0;
}