简体   繁体   English

初始化具有动态长度的向量

[英]Initialize a vector with a dynamic length

Can you please tell me how to change the size of the buf vector into a dynamic length? 您能告诉我如何将buf向量的大小更改为动态长度吗?

long five = 555;
char buf[256];
snprintf(buf, sizeof(buf), "%d", five); 

THX! 谢谢!

How to change my code with std::vector<std::string>buf; 如何使用std::vector<std::string>buf;更改我的代码std::vector<std::string>buf; in order to work correctly? 为了正常工作?
I have error: 我有错误:

vector is not a member of std; vector不是std的成员;
buf was not declared in this scope and error: expected primary-expression before ">" token 没有在此范围内声明buf并发生错误:“>”标记之前的预期主表达式

In C++, you can't. 在C ++中,您不能这样做。 You will have to allocate it dynamically somehow, or better still use a dynamic data structure like a std::vector. 您将必须以某种方式动态分配它,或者最好还是使用动态数据结构,例如std :: vector。

Try: 尝试:

#include <vector>
#include <string>

long five = 555;

// using vector
std::vector<char> buf1(256);
snprintf(&buf1[0], buf1.size(), "%d", five);

// Or using string 
std::string       buf2(256);
snprintf(&buf2[0], buf2.size(), "%d", five);

Though rather than using snprintf() I would look up how to use stringstream. 虽然不使用snprintf(),但我将查找如何使用stringstream。

if you're really opposed to using the vector class, you could implement the dynamic memory yourself. 如果您真的反对使用vector类,则可以自己实现动态内存。 Create a function for adding to the array when theres not enough memory to store the new values. 创建一个函数,当没有足够的内存来存储新值时添加到数组。 It would malloc new memory, copy the contents over, append new values, delete the old memory, then return a pointer to the new array. 它将分配新内存,复制内容,追加新值,删除旧内存,然后返回指向新数组的指针。 They amount new memory that you would use would depend on your application.(ie. just enough memory to store new values to conserve memory, or a lot more(eg double) than the old size so you wouldn't have to call this function as often. 它们使用的新内存量取决于您的应用程序。(即,足够的内存来存储新值以节省内存,或者比旧大小多很多(例如,双倍),因此您不必调用此函数经常。

You probably want to make a vector of characters, not a vector of strings. 您可能希望创建一个字符向量,而不是字符串向量。

The second error I suspect is a missing space character before the variable name. 我怀疑的第二个错误是变量名称前缺少空格字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM