11-14 模板,容器,命令

template<class X>
template<typename X>
声明一个X为抽象类型的类
用的时候是 模板+实参类型=具体函数

#include<iostream>
using namespace std;
template<class X>
X Max(X a,X b)
{
    return(a>b?a:b);
}
int main()
{
    int X1=20;
    int X2=30;   
    cout<< Max<int>(X1,X2)<<endl;  //此处<int>可以带也可以不带,建议加上
    double a=10.56789;
    double b=10.56781;
    cout<< Max<double>(a,b)<<endl;
}
#include<iostream>
using namespace std;
template<class X,class Y>
class Test
{
    X m_t1;
    Y m_t2;
public:
    Test(X t1,Y t2)
    {
        m_t1=t1;
        m_t2=t2;        
    }
    void show()
    {
        cout<<"T1="<<m_t1<<endl<<"T2="<<m_t2<<endl;
    }
    void print();
};
template<class X,class Y>  //必须如此。。。最好用show类型的来定义
void Test<X,Y>::print()
{
    cout<<"T1="<<m_t1<<endl<<"T2="<<m_t2<<endl;
}
int main()
{
    Test<int,char>t(10,'s');
    t.show();
    t.print();
}

cin输入,只有类型不符才会返回0
迭代器和指针const的用法对比

 iterator i1;                                                 int *p1;
 const_iterator i2;                                     const int *p2;
 const iterator i3;                                      int *const p3;
 const const_iterator i4;                          const int* const p4;

容器的建造与一些命令的应用

#include<iostream>
#include<vector>
using namespace std;
void show(vector<int>vi)
{
    vector<int>::iterator it;
    it=vi.begin();
    while(it!=vi.end())
    cout<<*it++<<' ';
    cout<<endl;
}
int main()
{
    vector<int>vi(3,90);
    show(vi);
    int a[5]={3,4,5,6,7};
    vi.insert(vi.begin(),a,a+5);
    show(vi);
    vi.push_back(100);
    show(vi);
    cout<<"size:"<<vi.size()<<endl;
    vi.assign(5,99);                    //清除之前的内容,并赋值给该容器
    show(vi);
    cout<<"size:"<<vi.size()<<endl;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy阅读 9,554评论 1 51
  • C++运算符重载-下篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 1,492评论 0 49
  • 再读高效c++,颇有收获,现将高效c++中的经典分享如下,希望对你有所帮助。 1、尽量以const \enum\i...
    橙小汁阅读 1,264评论 0 1
  • 重新系统学习下C++;但是还是少了好多知识点;socket;unix;stl;boost等; C++ 教程 | 菜...
    kakukeme阅读 20,104评论 0 50
  • 接着上节 condition_varible ,本节主要介绍future的内容,练习代码地址。本文参考http:/...
    jorion阅读 14,896评论 1 5