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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:24:06  来源:igfitidea点击:

C++ using STL List, how to copy an existing list into a new list

c++liststllinked-listlong-integer

提问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 LongIntconstructor just use the iterator, iteratorlistconstructor:

在您的LongInt构造函数中,只需使用iterator, iteratorlist构造函数:

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 stringor 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::copyalgorithm 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::stringif 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::stringanyway, 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::stringif it's a list of chars you're storing.

但是,std::string如果它char是您要存储的s列表,请使用 a 。