gpt4 book ai didi

arrays - std::array 与 std::vector 的细微差别

转载 作者:行者123 更新时间:2023-12-03 13:56:56 25 4
gpt4 key购买 nike

我想乱搞 std::array看看它与std::vector有何不同.到目前为止,我只发现了一个主要区别。

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可以不同也可以相同。这甚至从这句话中得到证实:

size and max_size of an array object always match.



那么为什么 std::array有多余的尺寸功能吗?更重要的是,你会认为这是 std::array的陷阱吗?的大小不一定与 std::vector 相同的大小,因为向量有容量?另外,这是否意味着 std::array s 是安全的(即,它们是否具有像向量一样的智能指针管理?)

最佳答案

使其与其他容器兼容。

通过这种方式,您可以拥有一个模板函数,它接受任何集合,并确保无论它是 std::vector 它都能正常工作。或 std::array .

关于arrays - std::array 与 std::vector 的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16380740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com