初始化具有动态长度的向量
你能告诉我如何将 buf 向量的大小更改为动态长度吗?
long five = 555;
char buf[256];
snprintf(buf, sizeof(buf), "%d", five);
谢谢!
如何使用 std::vector
更改我的代码以便正常工作?
我有错误:
向量不是 std 的成员;
buf 未在此范围内声明,并且错误:预期的主表达式位于“>”之前令牌
Can you please tell me how to change the size of the buf vector into a dynamic length?
long five = 555;
char buf[256];
snprintf(buf, sizeof(buf), "%d", five);
THX!
How to change my code with std::vector<std::string>buf;
in order to work correctly?
I have error:
vector is not a member of std;
buf was not declared in this scope and error: expected primary-expression before ">" token
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++ 中,你不能。您必须以某种方式动态分配它,或者最好仍然使用动态数据结构,例如 std::vector。
In C++, you can't. You will have to allocate it dynamically somehow, or better still use a dynamic data structure like a std::vector.
尝试:
虽然我不使用 snprintf(),但会查找如何使用 stringstream。
Try:
Though rather than using snprintf() I would look up how to use stringstream.
如果你真的反对使用向量类,你可以自己实现动态内存。创建一个函数,用于在没有足够的内存来存储新值时添加到数组中。它将分配新内存,复制内容,附加新值,删除旧内存,然后返回指向新数组的指针。您将使用的新内存量取决于您的应用程序。(即,只需足够的内存来存储新值以节省内存,或者比旧大小多得多(例如两倍),这样您就不必调用此函数一如既往。
if you're really opposed to using the vector class, you could implement the dynamic memory yourself. 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.