如何在C++ STL中查找std :: forward_list的大小

如何在C++ STL中查找std :: forward_list的大小

C++标准模板库中的前向列表,在#include 头文件中。它是作为单向链表实现的。它在C++ 11中首次引入。前向列表是允许在序列中任何位置进行恒定时间插入和删除操作的序列容器。在前向列表的情况下,不支持快速的随机访问。

与其他STL库不同,std :: forward_list没有任何size()方法。因此,在本文中,我们将向您展示如何在C++ STL中获取std :: forward_list的大小。

由于std :: distance()函数需要两个迭代器作为参数并返回一个整数,因此可以传递std :: begin()和std :: end()函数,这些函数指向第一个项的地址和最后一项的地址之后。

语法:

size = distance(forward_list.begin(), forward_list.end());

下面是实现上述方法的C++代码:

// C++ program to implement
// the above approach
 
#include 
#include 
using namespace std;
 
// Driver code
int main()
{
 
    forward_list l1 = { 3, 5, 6, 9, 6 };
 
    // l.size()将抛出错误,因为
    //对于forward_list没有size()方法。因此,要计算
    //大小,我们将使用std :: distance(iterator1,
    // iterator2),其中iterat​​or1将是
    // l.begin(),iterator2将是l.end()
    int size = distance(l1.begin(),
                        l1.end());
 
    cout << "Size of l1 is : " << size << endl;
 
    l1.remove(6);
 
    //它将从列表中删除所有6的实例
    size = distance(l1.begin(), l1.end());
 
    cout << "Size of l1, after removing all"
         << " instances of 6 is : " << size << endl;
 
    forward_list l2 = { 6, 11, 0 };
 
    int size2 = distance(l2.begin(),
                          l2.end());
 
    cout << "Size of l2, before assigning"
         << " it to l1 : " << size2
         << endl;
 
    l1.splice_after(l1.begin(), l2);
 
    //它会将l2分配给所提供的迭代器,使l1为空。
    size = distance(l1.begin(),
                    l1.end());
    size2 = distance(l2.begin(),
                     l2.end());
 
    cout << "Size of l1, after assigning"
         << " l2 to it : " << size << endl;
 
    cout << "Size of l2, after assigning"
         << " it to l1 : " << size2 << endl;
}  

输出:

Size of l1 is : 5
Size of l1, after removing all instances of 6 is : 3
Size of l2, before assigning it to l1 : 3
Size of l1, after assigning l2 to it : 6
Size of l2, after assigning it to l1 : 0

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程