首页 > 编程语言 > 详细

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

时间:2021-09-08 19:36:18      阅读:14      评论:0      收藏:0      [点我收藏+]

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容器 (二)

原文:https://www.cnblogs.com/creature-lurk/p/15239637.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!