栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++之容器(vector)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++之容器(vector)

代码1:

#include 
#include
using namespace std;


void printVector(vector& v)
{
    for (vector::iterator it = v.begin(); it != v.end(); it++)
    {
        cout<<*it<<" ";
    }
    cout << endl;
}
void test01()
{
    //vector容器构造
    vector v1;//默认构造 无参构造
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    printVector(v1);
    //通过区间方式进行构造
    vectorv2(v1.begin(), v1.end());
    printVector(v2);

    //n个elem方式构造
    vectorv3(10, 100); //10个100
    printVector(v3);

    //拷贝构造
    vectorv4(v3);
    printVector(v4);
}
int main() {
    test01();
    system("pause");
    return 0;
}

结果:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100

代码2:

#include 
#include
using namespace std;


void printVector(vector& v)
{
    for (vector::iterator it = v.begin(); it != v.end(); it++)
    {
        cout<<*it<<" ";
    }
    cout << endl;
}
void test01()
{
    //vector容器赋值
    vector v1;//默认构造 无参构造
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    printVector(v1);
   
    //赋值 operator=
    vector v2;
    v2 = v1;
    printVector(v2);

    //assign
    vector v3;
    v3.assign(v1.begin(), v1.end());
    printVector(v3);

    //n个elem赋值
    vector v4;
    v4.assign(10, 100);
    printVector(v4);
}
int main() {
    test01();
    system("pause");
    return 0;
}

结果:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
100 100 100 100 100 100 100 100 100 100

代码3:

#include 
#include
using namespace std;


void printVector(vector& v)
{
    for (vector::iterator it = v.begin(); it != v.end(); it++)
    {
        cout<<*it<<" ";
    }
    cout << endl;
}
void test01()
{
    //vector容器的容量和大小操作
    vector v1;
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    printVector(v1);
   
    if (v1.empty())  //为真 代表容器为空
    {
        cout << "v1为空" << endl;
   }
    else
    {
        cout << "v1不为空" << endl;
        cout << "v1的容量为:" << v1.capacity() << endl;
        cout << "v1的大小为:" << v1.size() << endl;
    }
    //重新指定大小
    v1.resize(15);
    printVector(v1); //如果重新指定比原来的长了  默认用0填充新的位置
    v1.resize(5);//如果重新指定比原来的短了  超出部分会删除掉
    printVector(v1);
}
int main() {
    test01();
    system("pause");
    return 0;
}

结果:

0 1 2 3 4 5 6 7 8 9
v1不为空
v1的容量为:13
v1的大小为:10
0 1 2 3 4 5 6 7 8 9 0 0 0 0 0
0 1 2 3 4
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430039.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号