如何在 std::vector 中存储固定长度的字符串
我想模仿一个结构:
char [][40] = { "Stack", "Overflow", "Exchange", "Network" };
使用 std::vector
,这样我就可以在运行时填充它并动态更改 vector
的大小,但保持成员元素的位置在固定大小的块内。
静态初始化不是我的问题 - 我可以使用 boost::assign 或其他技巧来做到这一点。
I want to mimic a structure:
char [][40] = { "Stack", "Overflow", "Exchange", "Network" };
using a std::vector
, so I can populate it at runtime and dynamically change the size of the vector
, but keeping the member elements located inside fixed size blocks.
Static initialization is not my question - I can do that using boost::assign
or other tricks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用类似 Boost.Array 的东西:
如果你使用的是合理的最近的编译器,您可以使用
std::array<>
(C++11;#include
) 来代替 Booststd::tr1::array<>
(带有 TR1 的 C++03;#include
或#include
,取决于平台)。I'd use something like Boost.Array:
If you're using a reasonably recent compiler, instead of Boost you can probably use
std::array<>
(C++11;#include <array>
) orstd::tr1::array<>
(C++03 with TR1;#include <array>
or#include <tr1/array>
, depending on platform).如果您使用 C++11(或至少 TR1),您可能需要使用
std::array
而不是fixed_string
。我认为 Boost 也有类似的东西。如果有人想知道为什么我将它放在
struct
中,而不是直接创建数组向量:因为vector
中的项目需要可复制和可分配,并且是裸露的数组都不是。If you have C++11 (or at least TR1), you probably want to use
std::array
instead offixed_string
. I think Boost has an equivalent as well.In case anybody's wondering why I put it in a
struct
, instead of creating a vector of array directly: because items in avector
need to be copyable and assignable, and a bare array is neither.可能是
vector
中的vector
有帮助。这里大小是固定的,字符串可以在纯C中使用。May be
vector
invector
helps. Here size is fixed, strings could be used in pure C.Parapura 的答案是正确的,但您将存储指向字符串的指针。如果原始字符数组超出范围,您将丢失发布的信息。如果这个向量在其他地方使用,它应该分配(和释放!)它自己的内存。这可以在获取输入时完成。
这是一个执行此操作的示例程序。
Parapura's answer is correct, but you will be storing the pointers to the strings. If the original character array falls out of scope you will lose the information posted. If this vector is used elsewhere, it should allocate (and deallocate!) it's own memory. This can be done when the input is taken.
Here's a sample program that does that.