何时使用矢量以及何时使用数组在C ++? [英] When to use vectors and when to use arrays in C++?

查看:93
本文介绍了何时使用矢量以及何时使用数组在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的时候,最好是使用一个与其他通常不能确定。他们似乎都做同样的东西一般,但向量更加灵活在它能做什么条件?如果是数组更合适?

I am usually unsure when it is better to use one versus the other. They both seem to do the same things in general but is vector more flexible in terms of what it can do? When are arrays more appropriate?

推荐答案

一般总是使用的std ::矢量&lt preFER; T> ,因为破坏会自动一旦载体超出范围和分配的内存将整齐地堆放置,所有的记忆会为你处理。 的std ::矢量< T> 为您提供了在一个阵列得到的一切,甚至保证该元素将被连续存储在内存中(除的std ::矢量<布尔方式>

Generally always prefer using std::vector<T> since the destruction will be automatic once the vector goes out scope and the allocated memory will be placed neatly on the heap and all the memory will be handled for you. std::vector<T> gives you everything you get in an array and even a guarantee that the elements will be contiguously stored in memory (except for std::vector<bool>).

在的情况下,的std ::矢量&lt;&布尔GT; 你必须要,因为code小心这样会打破:

In the case of std::vector<bool> you have to be careful since code like this will break:

 std::vector<bool> vb;
 vb.push_back(true);
 vb.push_back(false);
 vb.push_back(true);
 bool *pB = &vb[0];
 if( *(pB+1) )
 {
     // do something
 }

事实是,的std ::矢量&lt;&布尔GT; 不存储连续布尔秒。这是在标准的异常被固定在C ++ 11

Fact is, std::vector<bool> doesn't store contiguous bools. This is an exception in the standard that is fixed in C++11.

这篇关于何时使用矢量以及何时使用数组在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆