在 C++11 中,infinity()
is constexpr
,所以理论上你可以这样直接使用它:
char Buffer_format_text[std::numeric_limits<const int>::infinity()];
但是,这里的问题是int
不能表示无穷大。如果你试过这个:
std::cout << std::numeric_limits<const int>::has_infinity;
您会看到0
( false
) 被打印到标准输出(现场示例)。where is的infinity()
特化函数将返回 0 - 事实上,该函数在这些情况下毫无意义 - 并且您不能创建大小为 0 的数组。std::numeric_limits
has_infinity
false
此外,您不能期望分配一个无限大小的数组 - 它如何适合内存?如果您事先不知道向量的大小,正确的方法是使用std::vector
或类似的容器,它会根据请求分配内存。
更新:
看来您实际上需要一个无限数组是为了能够构建一个事先不知道大小的字符串。要封装这样一个动态增长的字符串,您可以使用std::string
.
为了执行类型安全的输出到 anstd::string
和 replacesprintf()
中,您可以使用std::ostringstream
. 这将允许您将内容插入字符串,就像将其打印到标准输出一样。
然后,一旦你完成了对 的处理std::ostringstream
,你可以std::string
通过调用str()
成员函数从中获取一个对象。
这是您可以在一个简单示例中使用它的方式:
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
int main()
{
std::ostringstream oss;
oss << "The answer is: ";
oss << 42;
oss << ", and this is a double: ";
oss << 3.14;
oss << ". " << std::endl;
oss << "Oh, btw, you can also output booleans: ";
oss << std::boolalpha << true;
oss << ". See? It's easy!" << std::endl;
std::cout << oss.str();
}
现场演示。