首页 > 解决方案 > 字符串数组是否需要 C++ 中的最大维度?

问题描述

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

标签: c++arraysstring

解决方案


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

#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

推荐阅读