C++-STL(14)-Vector

   1.与list相比就是可以有下标访问。.at(index)[index]访问基本一样,只是.at(index)是有边界检查的。
   2.remove ()并不删除元素,因为容器的size()没有变化
   3.
如果需要高效的存取操作,选择vector,如果有大量的插入删除操作,选择 list。

void vector_test(void)
{
    std::cout << "vector(void)";
    cout<<"******//1.创建与添加  push_back(0-5)******"<<endl;
    vector<int>  vi;    
    for (int i = 0; i < 5; i++)
    {
        vi.push_back(i);
        cout << vi[i] << ",";
    }
    cout << "******//2.插入insert(vi.begin()+vi.size(),6)******" << endl;

    vi.insert(vi.begin()+vi.size(),6);
    cout << endl;
    cout << "******//3.删除  pop_back()******" << endl;
    for (int i = 0; i < vi.size(); i++)
    {
        vi.pop_back();//3.删除
    }
    cout << "******删除 后 ******" << endl;
    vector<int>::iterator it;//声明一个迭代器,来访问vector容器,作用:遍历或者指向vector容器的元素 
    for (it = vi.begin(); it != vi.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
    cout << "******//4 批量添加 string 5个******" << endl;
    vector<string> vstr(5, "ab");// 创建5个string "00"
    vstr.push_back("111");
    vstr.push_back("222");
    for (int i = 0; i < vstr.size(); i++)
    {
        cout << vstr[i] << ",";
    }

//  cout << "******erase(vstr[5]),删'111'  "<<endl;
    vstr.erase(vstr.begin() + 5);
    cout << "******erase(vstr.begin()+5),删一个 " <<"vstr大小="<< vstr.size() <<endl;
    for (int i = 0; i < vstr.size(); i++)
    {
        cout << vstr[i] << ",";
    }   
    remove("222");
    cout << "******remove('222'); " << "vstr大小=" << vstr.size() << endl;
    for (int i = 0; i < vstr.size(); i++)
    {
        cout << vstr[i] << ",";
    }


    cout << "******//5.索引vstr.at(0)=******" << vstr.at(0) << endl;
    cout << "******//索引vstr[0]=******" << vstr[0] << endl;
    vstr.clear();
    cout << "******//6.清空 clear()清空元素,但不回收空间******" <<"vstr.size()=" <<vstr.size()<<endl;
    for (int i = 0; i < vstr.size(); i++)
    {
        cout << vstr[i] << endl;
    }
}

 

原文链接: https://www.cnblogs.com/jasmineTang/p/14369282.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++-STL(14)-Vector

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/328108

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午4:33
下一篇 2023年3月1日 下午4:33

相关推荐