无限值和缓冲区

时间:2013-04-20 14:16:35

标签: c++

我有一个记分板,可以随时获取新信息,缓冲区大小为=行数 得分板可以汉德尔,但我试图让它无限无限。

我要做的是将as-sign无穷大值作为这样的缓冲区:

 const int infinity = std::numeric_limits<const int>::infinity(); 

 char Buffer_format_text [infinity]; 

但它不起作用,因为它说:

错误C2057:预期的常量表达式  错误C2466:无法分配常量大小为0的数组

有办法吗?还是骗术? , 请帮我。不要问我为什么要那样做,我问怎么做。

更新

这是我用sprintf做的,你怎么在ostringstream?

char Buff[100]; 
int length  = 0;
int amount_of_space = 8;
length += sprintf(Buff+length,"%-*s %s\n", amount_of_space, "Test", "Hello");

this output: Test     Hello

4 个答案:

答案 0 :(得分:6)

在C ++ 11中,infinity()constexpr,理论上 你可以这样直接使用它:

char Buffer_format_text[std::numeric_limits<const int>::infinity()];

但是,问题在于int 无法表示无穷大。如果你试过这个:

std::cout << std::numeric_limits<const int>::has_infinity;

您会看到0false)打印到标准输出(live example)。其中infinity()std::numeric_limits的{​​{1}}特化的has_infinity函数将返回0 - 实际上,在这些情况下函数没有意义 - 并且您无法创建大小为0的数组

此外,您不能指望分配无限大小的数组 - 它如何适合内存?如果您事先不知道向量的大小,那么正确的方法是使用false或类似的容器,根据请求分配内存。


<强>更新

你真正需要一个无限数组似乎是能够建立一个大小未提前知道的字符串。要封装这种动态增长的字符串,可以使用std::string

为了在std::vector中执行类型安全输出并替换std::string,您可以使用std::ostringstream。这将允许您将内容插入字符串,就像将其打印到标准输出一样。

然后,使用sprintf()后,您可以通过调用std::ostringstream成员函数从中获取std::string个对象。

这是您在一个简单示例中使用它的方法:

str()

Live demo

答案 1 :(得分:2)

您基本上无法在堆栈或堆上分配具有真正无限内存的数组。 您也无法分配大小为0的数组,因为根据标准它是非法的。

您可以尝试使用std :: vector,它会在必要时自行增长。但你仍然无法分配infinite内存,因为你的磁盘空间有限,无论它有多大。

答案 2 :(得分:2)

将缓冲区声明为无穷大是没有意义的,因为整数类型不能(通常)表示无穷大(infinity numeric_limits成员用于FP类型),并且因为没有机器可以创建一个大的缓冲区无限字节。 :)

相反,使用一个容器,它可以自己处理新插入所需的重新分配,仅受可用内存的限制,例如: std::vector(或std::deque或其他人,具体取决于您的插入/删除模式)。


编辑:由于问题似乎是关于创建一个任意长的字符串,“C ++答案”是使用std::ostringstream,它允许您编写任意数量的元素(仅受可用内存的限制) )并为您提供std::string

std::ostringstream os;
for(int i=0; i<1000; i++)
    os<<rand()<<" ";
std::string out=os.str();
// now in out you have a concatenation of 1000 random numbers

编辑/ 2:

  

这是我用sprintf做的,你怎么在ostringstream?

char Buff[100]; 
int length  = 0;
int amount_of_space = 8;
length += sprintf(Buff+length,"%-*s %s\n", amount_of_space, "Test", "Hello");
// needed headers: <sstream> and <iomanip>
std::ostringstream os;
int amount_of_space = 8;
os<<std::left<<std::setw(amount_of_space)<<"Test"<<" "<<"Hello";
std::string out=os.str(); // you can get `length` with `out.size()`.

但是如果你需要做多次插入,只在最后,当你真正需要字符串时调用os.str()。同样,无需跟踪长度,流自动完成。

答案 3 :(得分:0)

您应该使用可以动态增长的容器,例如std::vector(或者,如您的情况似乎是文字,std::string)。

您可以使用std::ostringstream构建std::string,如下所示:

#include <iomanip>
#include <sstream>

std::ostringstream ss;
ss << std::setw(amount_of_space) << std::left << "Test" << ' ' << "Hello" << '\n';
std::string result = ss.str();