c++ - 字符串数组是否需要 C++ 中的最大维度?
问题描述
我是否需要声明数组的最大维度,或者有没有办法在我添加项目时让数组缩放?
解决方案
每个数组都有一个固定的大小,这是其类型的一部分并且不能更改:
#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。使用矢量对象,您不必担心容器的大小,您可以继续添加元素:
#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 循环再次很容易地遍历向量对象以查看其所有元素:
#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
推荐阅读
- sql - Oracle SQL:在没有子查询连接的情况下从另一个表中排除 ID
- javascript - Preloader - 从子页面返回主页面时如何关闭它?
- symfony - Symfony 中返回了意外的集合
- r - R 数据表中的交互式突出显示
- java - 如何解析包含我用作分隔符的相同符号的字符串?
- react-native - Native Base 和 TabNavigator 在 tabBarComponent 中获得活动状态
- c# - 如何在 Unity 中更改音频剪辑
- pandas - Pandas 合并数据框时的“多索引”问题
- powershell - PowerShell WMI/WQL 从 SCCM 获取信息 - 优化
- vue.js - 如何从组件中获取变量值并将其分配给 vuejs 中另一个组件中的变量