vector的构造函数

vector的构造函数

vector():创建一个空vector
vector(int nSize):创建一个vector,元素个数为nSize
vector(int nSize,const t& t):创建一个vector,元素个数为nSize,且值均为t
vector(const vector&):复制构造函数
vector(begin,end):复制[begin,end)区间内另一个数组的元素到vector中,注意最后面的end其实并不包括,此函数也可以认为是vector(begin, begin + lenth)

vector判空

void IsEmpty(const vector<int>& ve)
{
    if (ve.begin() == ve.end()) {
        cout << "size of ve: " << ve.size() << " begin == end" << endl;
    }
}

void func()
{
    vector<int> vec;
    IsEmpty(vec);
    vec.push_back(1);
    vec.pop_back();
    IsEmpty(vec);
}

结果输出为

size of ve: 0 begin == end
size of ve: 0 begin == end

当vector容量为空时,迭代器begin == end

使用构造函数

#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <class T>
void printVector(const vector<T>& ve)
{
    for (auto e : ve) {
        cout << e << " ";
    }
    cout << endl;
}

void f()
{
    int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    vector<int> ve1(nums, nums + 7);
    cout << "ve1: " << endl;
    printVector(ve1);
    
    const char *p = "hello world";
    vector<char> ve2(p, p + 12);
    cout << "ve2: " << endl;
    printVector(ve2);
    
    vector<string> ve3(7, "ha");
    cout << "ve3: " << endl;
    printVector(ve3);
    
    vector<int> ve4(30);
    cout << "ve4: " << endl;
    printVector(ve4);
}

int main()
{
    f();
    
	return 0;
}

输出

ve1: 
1 2 3 4 5 6 7 
ve2: 
h e l l o   w o r l d  
ve3: 
ha ha ha ha ha ha ha 
ve4: 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

使用vector(int nSize)得到的vector内会初始化为0?
通过验证得到,vector, map<type, int>的初始化时,都会把数据初始化为0。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值