回顾C++
1. 模板函数和auto关键字迭代器遍历vector容器
auto用于迭代器可以减少代码量
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
void print_vector(vector<T> v)
{
for(auto i = v.begin(); i!= v.end(); i++)
{
//cout<<typeid(i).name()<<endl;
cout<<*i<<endl;
}
}
int main(int argc, char const *argv[])
{
/* code */
vector<int> v;
for(int i = 0; i<10; i++)
{
v.push_back(i);
}
print_vector(v);
return 0;
}
2. c++ auto关键字
2.1 用于两种情况:
(1)声明变量时根据初始化表达式自动推断该变量的类型
(2)声明函数时函数返回值的占位符
#include <iostream>
#include <typeinfo>
using namespace std;
//返回类型后置,auto只作为占位符
auto sum(int a, int b) -> int
{
return a+b;
}
int main(int argc, char const *argv[])
{
/* code */
auto i = 2;
cout<<typeid(i).name()<<endl; //i
auto str = "hello world";
cout<<typeid(str).name()<<endl; //PKc
cout<<typeid(sum(1,2)).name()<<endl; //i
//auto n = 4.2, y = 1; //报错
auto x = true ? 1 : 2.5;
cout<<typeid(x).name()<<endl; //d
return 0;
}
typeid(i).name()返回的名字是编译器规定的。PKc可以记成pointer(P) const(K) char(c)
返回类型后置
2.2 推导规则:
2.2.1 按值推导:会忽略一些限定符
int main(int argc, char const *argv[])
{
/* code */
const int i = 5;
auto j = i;
//i = 2; //报错
j = 2;
return 0;
}
说明j是一个int类型,而不是const int
2.2.2 按引用推导
引用也会被忽略掉
例子中:p是一个int,而不是int&
/*按引用初始化*/
int m = 5;
int& n = m;
auto p = n;
p = 2;
cout<<m<<endl; //5
cout<<n<<endl; //5
cout<<p<<endl; //2
n = 3;
cout<<m<<endl; //3
cout<<n<<endl; //3
cout<<p<<endl; //2
2.2.3 万能引用
int i = 5;
auto&& j = i;
auto&& m = 2;
j是一个int引流类型
m是一个int类型
2.2.4 auto作为函数返回值
返回值类型必须相同
错误写法:
auto get_num (int a, double b)
{
if()
{
return a;
}
return b;
}
2.2.5 lambda表达式的形参中使用auto
auto l = [](auto a1, auto a2){return a1+a2};
auto res = l(4,5.5);
注意,我们可以不用先考虑返回值的类型
3. 其他类型的vector中不能用resize()
#include <iostream>
#include <vector>
using namespace std;
template<typename T1, typename T2>
class Person
{
public:
Person(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
void show_info()
{
cout<<"name is: "<<this->name<<" age is: "<<this->age<<endl;
}
T1 name;
T2 age;
};
template<typename T>
void print_vector(vector<T> vec)
{
for(auto i = vec.begin(); i!= vec.end(); i++)
{
i->show_info();
}
}
int main(int argc, char const *argv[])
{
/* code */
vector<Person<string, int>> v1;
Person<string,int> p1("henry",24);
Person<string,int> p2("lili",22);
Person<string,int> p3("Bill",25);
Person<string,int> p4("Jack",23);
v1.push_back(p1);
v1.push_back(p2);
v1.push_back(p3);
v1.push_back(p4);
print_vector(v1);
cout<<v1.capacity()<<endl; //4
cout<<v1.size()<<endl; //4
/*报错*/
// v1.resize(3);
// print_vector(v1);
// cout<<v1.capacity()<<endl;
// cout<<v1.size()<<endl;
return 0;
}