C++第10课 STL容器 (二)

1.vector

void testCreateVector()
{
    vector<int> vi;
    //构造时没有标长度不能直接用下表法访问
    //vi[0]=1;
    vi = { 1,2,3,4 };
    vector<string> vs = { "Hello","Hi","loveyou" };

    vector<int> arrData(3);    //代表长度是3

    for (int i = 0; i < 3; i++) {
        arrData[i] = i;
    }

    for (string s : vs) {
        cout << s << "\t";
    }
    cout << endl;

    //arrData[3]=23;    溢出访问
    //自动扩增只能通过成员函数来做
}
void testInsertAndPrint()
{
    vector<string> vs;
    vs.push_back("Hi");
    vs.push_back("Hello");
    for (string s : vs) {
        cout << s << "\t";
    }
    cout << endl;
    for (int i = 0; i < vs.size(); i++) {
        cout << vs[i] << endl;
    }
    vector<string>::iterator iter;
    for (iter = vs.begin(); iter != vs.end(); iter++)
    {
        cout << *iter << endl;
    }
    //用一段内存初始化另一段内存
    int arr[3] = { 1,2,3 };
    vector<int> vi;
    vi.assign(arr,arr+3);
}
void testFun()
{
    vector<string> vs(3);
    vs[0] = "ILoveYou";
    vs[1] = "IMissYou";
    vs[2] = "Nothing";

    cout << vs.at(0) << endl;
    cout << vs.size() << endl;
    cout << boolalpha << vs.empty() << endl;
    cout << vs.front() << endl;
    cout << vs.back() << endl;
    //注意:当创建时带长度,push_back是在长度之后插入,前面没数据的话会空着
    vs.push_back("Honey");
    for (auto v : vs)
    {
        cout << v << "\t";
    }
    cout << endl;
}
class MM {
    friend ostream& operator<<(ostream& out, const MM& obj);
public:
    MM(string name, int age) :name(name), age(age) {}
protected:
    string name;
    int age;
};
ostream& operator<<(ostream& out, const MM& obj)
{
    out << obj.name << "\t" << obj.age << endl;
    return out;
}

void testUserVector()
{
    vector<MM> vm;
    vm.push_back(MM("Hello", 19));
    for (auto v : vm)
    {
        cout << v << endl;
    }

}

 

C++第10课 STL容器 (二)

上一篇:事务-redis事务介绍和基本操作


下一篇:进阶级快捷键 p10