C++程式:將列表轉換為集合
C++中的列表與向量類似,都是容器,但列表的實現基於雙向連結串列,而向量的實現基於陣列。列表的元素通常不儲存在連續的記憶體位置,而是分散在記憶體中。列表在任何位置都能提供相同的常數時間操作,這是使用列表的主要特點。另一方面,集合是包含特定型別唯一值的容器,所有元素都按升序排序。這兩個容器不同,但有多種方法可以將列表轉換為集合。我們將在下面詳細討論該方法。
樸素方法
最簡單也是最樸素的方法是定義兩個不同的容器:一個列表型別,另一個集合型別,並將列表的每個元素複製到集合中。
語法
list<int> myList;
set<int> mySet;
for ( int const &val: myList ) {
mySet.insert(val);
}
演算法
- 將輸入放入列表中。
- 迭代遍歷列表中的每個元素,並將它們插入到集合中。
- 顯示集合的內容。
示例
#include <iostream>
#include <set>
#include <list>
using namespace std;
int main(){
//initializing the list
list<int> myList = { 10, 30, 65, 98, 76, 44, 32, 73, 81, 29 };
set<int> mySet;
cout<< "The list contents are:" << endl;
//displaying the list contents
for ( int const &val: myList ) {
cout << val << ' ';
}
//copying the elements of the list
for ( int const &val: myList ) {
mySet.insert(val);
}
cout << "\nThe set contents are:" << endl;
for ( int const &val: mySet ) {
cout << val << ' ';
}
return 0;
}
輸出
The list contents are: 10 30 65 98 76 44 32 73 81 29 The set contents are: 10 29 30 32 44 65 73 76 81 98
使用範圍建構函式
建立集合時,必須將列表的起始和結束指標作為引數提供給建構函式以使用範圍建構函式。
語法
list<int> myList; set<int> mySet(begin(myList), end(myList));
演算法
將輸入放入列表中。
建立集合時,將列表的起始和結束指標傳遞給集合的範圍建構函式。
顯示集合的內容。
示例
#include <iostream>
#include <set>
#include <list>
using namespace std;
int main(){
//initializing the list
list<int> myList = { 30, 70, 56, 89, 67, 44, 23, 37, 18, 92 };
//using the range constructor
set<int> mySet(begin(myList), end(myList));
cout<< "The list contents are:" << endl;
//displaying the list contents
for ( int const &val: myList ) {
cout << val << ' ';
}
cout << "\nThe set contents are:" << endl;
for ( int const &val: mySet ) {
cout << val << ' ';
}
return 0;
}
輸出
The list contents are: 30 70 56 89 67 44 23 37 18 92 The set contents are: 18 23 30 37 44 56 67 70 89 92
使用copy函式
C++ 中的 copy 函式允許將資料從一個容器複製到另一個容器。要使用 copy 函式,必須將列表的起始和結束指標以及指向集合和集合開頭的指標作為引數傳遞給函式,這些指標在一個插入器函式中。
語法
list<int> myList; set<int> mySet; copy(begin(myList), end(myList), inserter(mySet, begin(mySet)));
演算法
將輸入放入列表中。
定義一個新的集合。
將列表的起始和結束指標以及指向集合和集合開頭的指標(在一個插入器函式中)作為引數傳遞給 copy 函式。
顯示集合的內容。
示例
#include <iostream>
#include <set>
#include <list>
using namespace std;
int main(){
//initializing the list
list<int> myList = { 33, 74, 52, 84, 65, 47, 28, 39, 13, 96 };
set<int> mySet;
//using the copy function
copy(begin(myList), end(myList), inserter(mySet, begin(mySet)));
cout<< "The list contents are:" << endl;
//displaying the list contents
for ( int const &val: myList ) {
cout << val << ' ';
}
cout << "\nThe set contents are:" << endl;
for ( int const &val: mySet ) {
cout << val << ' ';
}
return 0;
}
輸出
The list contents are: 33 74 52 84 65 47 28 39 13 96 The set contents are: 13 28 33 39 47 52 65 74 84 96
結論
當我們使用集合時,不能向集合中新增或儲存重複元素,但列表或類似陣列的資料結構允許儲存重複元素。在某些情況下,最好使用集合而不是列表。我們之前看到的這些轉換技術對此非常有用。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP