C/C++教程

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

本文主要是介绍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容器 (二)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!