您好,欢迎访问一九零五行业门户网

C++程序将列表转换为集合

c++中的列表与向量一样是容器,但列表的实现是基于双重的链表与向量的数组实现相比。列表一般不包含列表中的元素分布在连续的位置记忆。列表在其中的任何地方都提供相同的恒定时间操作,这是主要的使用列表的特点。另一方面,集合是包含唯一值的容器某种类型并且所有元素都按升序排序。这两个容器是不同,但是有多种方法可以将列表转换为集合。我们讨论该方法详情如下。
朴素方法最简单、最幼稚的方法是定义两个不同的容器;列表类型之一另一个是set类型,将列表的每个元素复制到集合中。
语法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
使用复制功能c++ 中的复制函数允许将数据从一个容器复制到另一个容器。要使用复制函数,列表的开始和结束指针必须作为参数传递到函数以及指向集合的指针和集合内的集合的开头插入器功能。
语法list<int> mylist;set<int> myset;copy(begin(mylist), end(mylist), inserter(myset, begin(myset)));
算法在列表中获取输入。
定义一个新集合。
将列表的开始和结束指针以及插入器函数中的集合和集合开头的指针作为参数传递给复制函数。
显示集合的内容。
示例#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
结论当我们使用集合时,我们不能向集合中添加或存储重复的元素,但是允许重复的元素存储在列表或类似数组的数据结构中。有在某些情况下,首选使用集合而不是列表。这些转换我们之前见过的技术对此确实很有帮助。
以上就是c++程序将列表转换为集合的详细内容。
其它类似信息

推荐信息