C++ 中的向量是动态数组,可以包含任何类型的数据,可以是用户定义的或原始的。动态是指向量的大小可以根据操作增加或减少。向量支持各种函数,数据操作非常容易。另一方面,列表是与向量相同的容器,但与向量的数组实现相比,列表实现是基于双向链表的。列表在其中的任何位置都提供相同的恒定时间操作,这是使用列表的主要功能。我们来看看将向量转换为列表的主要方法。
使用范围构造函数
要使用范围构造函数,在创建列表时必须将向量的起始指针和结束指针作为参数传递给构造函数。
语法
vector ip;list op( ip.begin(), ip.end() );
登录后复制
算法
将输入存储在向量中。将向量的起始指针和结束指针传递给列表的范围构造函数。显示列表的内容。
示例
#include #include #include using namespace std;list solve( vector ip) { //initialise the list list op( ip.begin(), ip.end() ); return op;}int main() { vector ip( { 15, 20, 65, 30, 24, 33, 12, 29, 36, 58, 96, 88, 30, 71 } ); list op = solve( ip ); //display the input cout输出
The input vector is: 15 20 65 30 24 33 12 29 36 58 96 88 30 71 The output list is: 15 20 65 30 24 33 12 29 36 58 96 88 30 71登录后复制
使用std::list的assign函数
std::list的用法与范围构造函数的用法类似。我们以与范围构造函数相同的方式传递向量的起始和结束指针。
语法
vector ip;list op();op.assign(ip.begin(), ip.end());登录后复制
算法
将输入存储在向量中。定义一个新的列表。将向量的起始指针和结束指针传递给列表的assign函数显示列表的内容。
示例
#include #include #include using namespace std;list solve( vector ip) { //initialise the list list op; op.assign( ip.begin(), ip.end() ); return op;}int main() { vector ip( { 40, 77, 8, 65, 92 ,13, 72, 30, 67, 12, 88, 37, 18, 23, 41} ); list op = solve( ip ); //display the input cout输出
The input vector is: 40 77 8 65 92 13 72 30 67 12 88 37 18 23 41 The output list is: 40 77 8 65 92 13 72 30 67 12 88 37 18 23 41登录后复制
使用列表插入函数
我们可以使用列表的插入函数将数据从向量插入到列表中。列表需要列表开头的指针以及向量开头和结尾的指针。
立即学习“C++免费学习笔记(深入)”;
语法
vector ip;list op();op.insert(op.begin(), ip.begin(), ip.end());登录后复制
算法
将输入存储在向量中。定义一个新的列表。传递列表的起始指针以及起始和结束指针列表插入函数的向量。显示列表的内容。
示例
#include #include #include using namespace std;list solve( vector ip) { //initialise the list list op; op.insert( op.begin(), ip.begin(), ip.end() ); return op;}int main() { vector ip( { 30, 82, 7, 13, 69, 53, 70, 19, 73, 46, 26, 11, 37, 83} ); list op = solve( ip ); //display the input cout输出
The input vector is: 30 82 7 13 69 53 70 19 73 46 26 11 37 83 The output list is: 30 82 7 13 69 53 70 19 73 46 26 11 37 83登录后复制
结论
在C++中,将向量转换为列表具有在列表的任何位置上统一的操作复杂度的好处。有几种方法可以将向量转换为列表。然而,我们只在这里提到了最简单和最快的方法。
以上就是C++程序将向量转换为列表的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2582587.html