如何在C++ STL中使用构造函数创建列表
列表是允许非连续内存分配的序列容器。与向量相比,列表的遍历速度较慢,但一旦找到位置,插入和删除就很快。通常,当我们说列表时,我们指的是双向链表。要实现一个单向链表,我们使用forward list。
可以使用C++中的构造函数创建列表。它的语法是:
语法:
list<type>list_name(size_of_list, value_to_be_inserted);
以下程序展示了如何在C++中使用构造函数创建列表。
程序1:
#include <iostream>
#include <list>
using namespace std;
// Function to print the list
void printList(list<int>mylist)
{
// Get the iterator
list<int>::iterator it;
// 如果使用auto,则代码如下:auto it = mylist.begin(); 遍历循环中不需要指定数据类型
// printing all the elements of the list
for (it = mylist.begin(); it != mylist.end(); ++it)
cout<< ' ' << *it;
cout<<'\n';
}
int main()
{
// Create a list with the help of constructor
// This will insert 100 10 times in the list
list<int>myList(10,100);
printList(myList);
return 0;
}
100 100 100 100 100 100 100 100 100 100
程序2:
#include <bits/stdc++.h>
using namespace std;
// Function to print the list
void printList(list<string>mylist)
{
// Get the iterator
list<string>::iterator it;
// printing all the elements of the list
for (it = mylist.begin(); it != mylist.end(); ++it)
cout<< ' ' << *it;
cout<<'\n';
}
int main()
{
// Create a list with the help of constructor
// This will insert Geeks 5 times in the list
list<string>myList(5, "Geeks");
printList(myList);
return 0;
}
Geeks Geeks Geeks Geeks Geeks