C++ 使用 STL 列表,如何将现有列表复制到新列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5543049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ using STL List, how to copy an existing list into a new list
提问by Ctak
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.
现在我正在使用一个复制构造函数来获取一个名为 val 的 char 类型的列表,我需要获取传递给复制构造函数的字符串 v 的所有元素并将它们放入 val 列表中。
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!
所以在 LongInt 类的公共部分,我有一个复制构造函数,它接受 val 列表并将 v 字符串复制到其中。谁能帮我弄清楚如何做到这一点?提前致谢!
采纳答案by Mark B
In your LongInt
constructor just use the iterator, iterator
list
constructor:
在您的LongInt
构造函数中,只需使用iterator, iterator
list
构造函数:
LongInt(const string v) : val(v.begin(), v.end()) { }
LongInt(const string v) : val(v.begin(), v.end()) { }
That being said, have you considered actually using string
or possibly deque<char>
to manipulate your sequence rather than list
? Depending on your needs, those alternatives might be better.
话虽如此,您是否考虑过实际使用string
或可能deque<char>
操纵您的序列而不是list
?根据您的需要,这些替代方案可能更好。
回答by Timo Geusch
You'll have to iterate over the string and extract the data character by character. Using the std::copy
algorithm should work:
您必须遍历字符串并逐个字符地提取数据。使用该std::copy
算法应该有效:
std::copy(v.begin(), v.end(), std::back_inserter(val));
回答by f4.
LongInt::LongInt( const string v ) : val(v.begin(), v.end())
{
}
回答by rubenvb
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, use std::vector
. But that would boil down to a less-functional std::string
anyway, so just use std::string
.
首先,std::string
如果它是您要存储的字符串,请使用。这是一个和其他容器一样的容器。如果您不能或不想存储字符串,请使用std::vector
. 但这std::string
无论如何都会归结为功能较少,所以只需使用std::string
.
For the copying:
对于复制:
std::copy( v.begin(), v.end(), std::back_inserter(val) );
But just use a std::string
if it's a list of char
s you're storing.
但是,std::string
如果它char
是您要存储的s列表,请使用 a 。