C++程序:将向量转换为列表
C++中的向量是动态数组,可以包含任何类型的数据,包括用户定义的类型和基本类型。所谓动态是指向量的尺寸可以根据操作进行增加或减少。向量支持各种函数,使得数据操作非常容易。另一方面,列表与向量一样是容器,但列表的实现基于双向链表,而向量基于数组。列表的特点是可以在任何位置进行常数时间操作,这是使用列表的主要优势。我们将探讨将向量转换为列表的主要方法。
使用范围构造函数
要使用范围构造函数,必须将向量的起始和结束指针作为参数传递给列表的构造函数。
语法
vector <int> ip; list <int> op( ip.begin(), ip.end() );
算法
- 将输入存储到向量中。
- 将向量的起始和结束指针传递给列表的范围构造函数。
- 显示列表的内容。
示例
#include <iostream> #include <vector> #include <list> using namespace std; list <int> solve( vector <int> ip) { //initialise the list list <int> op( ip.begin(), ip.end() ); return op; } int main() { vector <int> ip( { 15, 20, 65, 30, 24, 33, 12, 29, 36, 58, 96, 88, 30, 71 } ); list <int> op = solve( ip ); //display the input cout<< "The input vector is: "; for( int i : ip ) { cout<< i << " "; } //display the output cout << "\nThe output list is: "; for( int j : op ) { cout << j << " "; } return 0; }
输出
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 <int> ip; list <int> op(); op.assign(ip.begin(), ip.end());
算法
- 将输入存储到向量中。
- 定义一个新的列表。
- 将向量的起始和结束指针传递给列表的assign函数。
- 显示列表的内容。
示例
#include <iostream> #include <vector> #include <list> using namespace std; list <int> solve( vector <int> ip) { //initialise the list list <int> op; op.assign( ip.begin(), ip.end() ); return op; } int main() { vector <int> ip( { 40, 77, 8, 65, 92 ,13, 72, 30, 67, 12, 88, 37, 18, 23, 41} ); list <int> op = solve( ip ); //display the input cout<< "The input vector is: "; for( int i : ip ) { cout<< i << " "; } //display the output cout << "\nThe output list is: "; for( int j : op ) { cout << j << " "; } return 0; }
输出
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
使用list的insert函数
我们可以使用列表的insert函数将数据从向量插入到列表中。列表接收列表的起始指针以及向量的起始和结束指针。
语法
vector <int> ip; list <int> op(); op.insert(op.begin(), ip.begin(), ip.end());
算法
- 将输入存储到向量中。
- 定义一个新的列表。
- 将列表的起始指针以及向量的起始和结束指针传递给列表的insert函数。
- 显示列表的内容。
示例
#include <iostream> #include <vector> #include <list> using namespace std; list <int> solve( vector <int> ip) { //initialise the list list <int> op; op.insert( op.begin(), ip.begin(), ip.end() ); return op; } int main() { vector <int> ip( { 30, 82, 7, 13, 69, 53, 70, 19, 73, 46, 26, 11, 37, 83} ); list <int> op = solve( ip ); //display the input cout<< "The input vector is: "; for( int i : ip ) { cout<< i << " "; } //display the output cout << "\nThe output list is: "; for( int j : op ) { cout << j << " "; } return 0; }
输出
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++中具有在列表的任何位置都具有统一操作复杂度的优点。还有其他几种方法可以将向量转换为列表。但是,我们在这里只提到了最简单和最快的方法。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP