gpt4 book ai didi

c++ - 字符串数组是否需要 C++ 中的最大维度?

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:16 25 4
gpt4 key购买 nike

我是否需要声明数组的最大维度,或者有没有办法在我添加项目时让数组缩放?

最佳答案

每个数组都有固定大小,这是其类型的一部分,不能更改:

#include <cstddef>

int main()
{
const std::size_t sz = 5;
int iarr[sz];
return 0;
}

这里,数组的大小是 5,这意味着它最多包含 5 个元素。尝试添加更多是未定义的:

iarr[5] = 10; // undefined 

虽然行为未定义,但如果您尝试越界分配,编译器不会阻止您。因此,您需要以一种避免此类情况的方式构建代码:

for (std::size_t i = 0; i != sz; ++i)
{
iarr[i] = 10;
}

这里的代码是完全合法的,很可能是您通常想要的。但如果您使用的是 C++11 或更高版本,则可以使用基于范围的 for 循环并让编译器担心大小:

for (auto &elm : iarr)
{
elm = 10;
}

这个例子做了完全相同的事情。

话虽如此,最好的做法可能是始终使用 std::vector .使用 vector 对象,您不必担心容器的大小,您可以不断添加元素:

#include <vector>

int main()
{
std::vector<int> ivec;

for (std::size_t i = 0; i != 5; ++i) // you may replace 5 any with non-negative integer
{
ivec.push_back(10);
}
return 0;
}

在收集了所有必要的元素后,使用基于范围的 for 循环再次非常容易地遍历 vector 对象以查看其所有元素:

#include <iostream>
#include <vector>
#include <string>
#include <cstddef>

int main()
{
std::vector<std::string> svec;

for (std::size_t i = 0; i != 5; ++i)
{
svec.push_back("hello");
}

for (const auto &elm : svec)
{
std::cout << elm << std::endl;
}

return 0;
}

输出:

hello
hello
hello
hello
hello

关于c++ - 字符串数组是否需要 C++ 中的最大维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53797537/

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