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++中具有在列表的任何位置都具有統一操作複雜度的優點。還有其他幾種方法可以將向量轉換為列表。但是,我們在這裡只提到了最簡單和最快的方法。

更新於:2022年10月19日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告