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

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

问题描述

我通常不确定何时使用一种比另一种更好.一般来说,它们似乎都在做同样的事情,但是 vector 在它可以做什么方面更灵活?什么时候用数组更合适?

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::vector 因为一旦 vector 超出范围并且分配了内存会整齐地放在堆上,所有的内存都会为你处理.std::vector 为您提供数组中的所有内容,甚至保证元素将连续存储在内存中(除了 std::vector代码>).

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::vector 的情况下,你必须小心,因为这样的代码会破坏:

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::vector 不存储连续的 bools.这是 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天全站免登陆