std :: vector元素是否保证是连续的? [英] Are std::vector elements guaranteed to be contiguous?

查看:557
本文介绍了std :: vector元素是否保证是连续的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单:std :: vector元素保证是连续的?按顺序,我可以使用std :: vector的第一个元素的指针作为C数组?

My question is simple: are std::vector elements guaranteed to be contiguous? In order word, can I use the pointer to the first element of a std::vector as a C-array?

如果我的内存很好,C ++标准没有作出这样的保证。然而,std :: vector的要求是,如果元素不是连续的,它几乎是不可能满足的。

If my memory serves me well, the C++ standard did not make such guarantee. However, the std::vector requirements were such that it was virtually impossible to meet them if the elements were not contiguous.

有人可以澄清这一点吗?

Can somebody clarify this?

示例:

std::vector<int> values;
// ... fill up values

if( !values.empty() )
{
    int *array = &values[0];
    for( int i = 0; i < values.size(); ++i )
    {
        int v = array[i];
        // do something with 'v'
    }
}


推荐答案

这是从C ++ 98标准错过了,但后来作为TR的一部分添加。

This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement.

从n2798(C ++ 0x草稿):

From n2798 (draft of C++0x):


23.2.6类模板向量[vector]

1向量是支持随机存取迭代器的序列容器。此外,它支持(摊销)
常量时间插入和擦除操作结束;在中间插入和擦除取线性时间。存储
管理是自动处理的,虽然可以提供提示以提高效率。
向量的元素是连续存储的,意味着如果v是一个向量,其中T是某种类型的其他
而不是bool,则它遵守身份& v [n] ==& v [ 0] + n,对于所有0 <= n < v.size()。

1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

这篇关于std :: vector元素是否保证是连续的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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