首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >std::数组与std::向量细微差异

std::数组与std::向量细微差异
EN

Stack Overflow用户
提问于 2013-05-05 02:12:21
回答 5查看 1.7K关注 0票数 3

我想和std::array混在一起,看看它和std::vector有多大的不同。到目前为止,我只发现了一个主要的区别。

代码语言:javascript
复制
Sentence sentence = { "Hello", "from", "GCC", __VERSION__, "!" };  
std::array<std::string, 10> a;
std::copy(sentence.begin(), sentence.end(), a.begin());

int i = 0;
for (const auto& e : a)
{
    i++;
    std::cout << e << std::endl;
}
std::cout << i << std::endl;

// outputs 10

i = 0;
for (const auto& e : sentence)
{
    i++;
    std::cout << e << std::endl;
}
std::cout << i << std::endl;

// outputs 5

for (int i = 0; i < a.size(); i++)
    std::cout << i << " " << a[i] << std::endl;

// outputs 0 Hello
// ...
//         4 !
//         5-9 is blank

for (int i = 0; i < sentence.size(); i++)
    std::cout << i << " " << sentence[i] << std::endl;

// outputs 0 Hello
// ...
//         4 !
// stops here


// The following outputs the same as above
i = 0;

for (auto it = a.begin(); it != a.end(); it++)
{
    std::cout << i << " " << *it << std::endl;
    i++;
}
std::cout << i << std::endl;
i = 0;
for (auto it = sentence.begin(); it != sentence.end(); it++)
{
    std::cout << i << " " << *it << std::endl;   
    i++;
}
std::cout << i << std::endl;

因此,在我看来,std::arraysizemax_size是多余的,但std::vectorsizecapacity可能是不同的,也可能是相同的。这一点甚至可以从这句话中得到证实:

数组对象的大小和max_size总是匹配的。

那么,为什么std::array有冗余大小函数呢?更重要的是,您是否认为std::array的大小不一定与std::vector的大小相同,因为向量具有容量?这是否意味着std::arrays是安全的(也就是说,它们有像向量一样的智能指针管理?)

EN

Stack Overflow用户

发布于 2013-05-05 02:28:19

稍微扩展一下,关于这个主题,std::array非常接近于数组的实际设计,比如char[],其中数组的最大大小就是数组的大小。这是因为数组可以被认为具有不可变的大小。这是一个大小是不能改变的,除了完全重新分配内存。与std::vector不同,后者可以设置为具有capacity,大小可以从0到该capacity,但是,一旦传递capacity值,每个新元素将导致vector内部的底层数组的完整重新分配。

票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16380740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档