C++使用STL列表,如何将现有列表复制到新列表中
现在我正在使用一个复制构造函数来获取一个名为 char 类型的 val 的列表,并且我需要获取传递到复制构造函数中的字符串 v 的所有元素并将它们放入 val 列表中。
Public:
LongInt(const string v);
Private:
list<char> val;
因此,在 LongInt 类的公共部分中,我有一个复制构造函数,它接受 val 列表并将 v 字符串复制到其中。谁能帮我弄清楚如何做到这一点?提前致谢!
Right now I'm working with a copy constructor for taking a list called val of type char, and I need to take all the elements of a string v that is passed into the copy constructor and put them into the val list.
Public:
LongInt(const string v);
Private:
list<char> val;
So here in the public section of the LongInt class I have a copy constructor which takes the val list and copies the v string into it. Can anyone help me figure out how to do this? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须迭代字符串并逐字符提取数据。使用
std::copy
算法应该可以工作:You'll have to iterate over the string and extract the data character by character. Using the
std::copy
algorithm should work:在
LongInt
构造函数中,只需使用iterator, iterator
list
构造函数:LongInt(const string v) : val(v.begin( ), v.end()) { }
也就是说,您是否考虑过实际使用
string
或可能的deque
来操作您的序列而不是列表
?根据您的需求,这些替代方案可能会更好。In your
LongInt
constructor just use theiterator, iterator
list
constructor:LongInt(const string v) : val(v.begin(), v.end()) { }
That being said, have you considered actually using
string
or possiblydeque<char>
to manipulate your sequence rather thanlist
? Depending on your needs, those alternatives might be better.首先,如果您要存储的是字符串,请使用
std::string
。它是一个像其他容器一样的容器。如果您不能或不想存储字符串,请使用std::vector
。但无论如何,这都会归结为功能较少的std::string
,所以只需使用std::string
即可。对于复制:
但如果它是您存储的
char
列表,则只需使用std::string
即可。First, use
std::string
if it's a string you're storing. It's a container like any other. If you can't or don't want to store a string, usestd::vector
. But that would boil down to a less-functionalstd::string
anyway, so just usestd::string
.For the copying:
But just use a
std::string
if it's a list ofchar
s you're storing.