C++提高

389 阅读1分钟

模板

C++ 除了面向对象、还有一个思想就是 泛型编程、主要用到的技术就是模板。

两种模板机制:函数模板、类模板。


void swapInt(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

void swapInt(double &a, double &b) {
    double temp = a;
    a = b;
    b = temp;
}

使用模板

template <class T> // 申明一个模板

// 编译器会自己推到出来数据类型
void mySwap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}

类模板

类模板没有自动类型推导

template <class TypeName, class TypeAge>

class Person {

public:
    TypeName m_name;
    TypeAge m_age;

    Person(TypeName name, TypeAge age) {
        this->m_name = name;
        this->m_age = age;
    }

    void show() {
        cout << this->m_name << this->m_age << endl;
    }
};

int main()
{
    Person<string, int> p1("shuai", 18);
    p1.show();

    system("pause");
    return 0;
}

如果申明和实现在同一个文件中。 这个文件的后缀最好是 .hpp 文件、不强制但是最好用这个

STL

容器 vector string list deque set map

vector

#include<iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void func(int value) {
    cout << value << endl;
}

int main()
{

    vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    v.push_back(40);

    for_each(v.begin(), v.end(), func);

    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << endl;
    }

    system("pause");
    return 0;
}

String 他和char * 的却别。 string 是一个类、里面封装了一个char * 管理这个字符串,他有很多方法。

#include<iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    const char* str = "hellow word";
    string s1(str);
    string s2(s1);

    cout << s1 << endl;
    cout << s2 << endl;

    s2 = "hellow";
    cout << s2 << endl;
    
    string s3;
    s3.assign("wuchaoshuai", 5); // 取前五
    cout << s3 << endl;

    // 拼接
    string pStr;
    pStr += "hellow";
    pStr += 'a';
    pStr.append("love");
    pStr.append(" wochaoshuao", 3); // 拼接前三
    pStr.append(" wochaoshuao", 3, 4); // 拼接第三个开始拼接四个

    cout << pStr << endl;

    system("pause");
    return 0;
}