C++ 数组array与vector的比较

<span style="background-color: rgb(255, 255, 255);"><span style="color:#333333;"></span></span><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(51, 51, 51); font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; font-size: 16px; line-height: 28px; text-align: justify;">vector 是STL中的容器类,包含多种通用算法</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(51, 51, 51); font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; font-size: 16px; line-height: 28px; text-align: justify;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(51, 51, 51); font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; font-size: 16px; line-height: 28px; text-align: justify;">长度可变,使用灵活,但效率稍低</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(51, 51, 51); font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; font-size: 16px; line-height: 28px; text-align: justify;"></p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(51, 51, 51); font-family: 'Microsoft Yahei', 微软雅黑, arial, 宋体, sans-serif; font-size: 16px; line-height: 28px; text-align: justify;">vector是使用 new 和 delete 来管理内存的</p><pre class="reply-text mb10" id="content-260763807" name="code" style="white-space: pre-wrap; word-wrap: break-word; font-size: 14px; line-height: 26px;"><span style="background-color: rgb(255, 255, 255);"><span style="color:#333333;">
</span></span>
1:array 定义的时候必须定义数组的元素个数;而vector 不需要;
 
<span style="background-color: rgb(255, 255, 255);"><span style="color:#333333;">且只能包含整型字面值常量,枚举常量或者用常量表达式初始化的整型const对象,</span><span style="color:#990000;">非const变量以及需要到运行阶段才知道其值的const变量</span><span style="color:#333333;">都不能用来定义数组的维度.

2:array 定义后的空间是固定的了,不能改变;而vector 要灵活得多,可再加或减.

3:vector有一系列的函数操作,非常方便使用.和vector不同,数组不提供 push——back或者其他的操作在数组中添加新元素,数组一经定义就不允许添加新元素;
若需要则要充许分配新的内存空间,再将员数组的元素赋值到新的内存空间。

</span></span>

4.   数组和vector不同,一个数组不能用另一个数组初始化,也不能将一个数组赋值给另一个数组;

5、vector与数组最大的区别就是可以实现动态存储;

vector<string> text;//定义string的容器,这时候该容器是空的.。
//翻译为容器非常形象吧,呵呵!
string word; //定义字符串变量
while(cin>>word)
text.push_back(word)//每输入一串字符,就将他装入我们定义的容器

//为了验证我们的结论,我们看看输出结果,当然vector类型可以像数
//数组一样用下标输出,不过这不是一个好办法
//输出容器中的数据我们一般使用迭代器,代码如下:

for( vector<string>::iterator i=text.begin();    i!=text.end();    i++)
{
    cout<<*i;
}



  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值