如何在 C++ STL 中找到 std::forward_list 的大小
C++标准模板库中的前向列表。它位于 #include
Unlike other STL libraries, std::forward_list does not have any size() method. Hence, in this article, we will show you how to get the size of a std::forward_list in C++ STL.
检索前向列表的大小存在问题,因为 std::forward_list 没有任何 std::size()成员函数。要获得前向列表的大小,可以使用 std::distance()函数。
方法:
由于 std::distance()函数采用两个迭代器作为参数并返回一个整数,因此可以传递 std::begin() 和 std::end()函数,它们指向第一项的地址和刚刚的地址在最后一项之后。
句法:
size = distance(forward_list.begin(), forward_list.end());
下面是实现上述方法的 C++ 代码:
C++14
// 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() will throw an error, since
// there is no size() method for
// forward_list. So, to calculate the
// size, we will use std::distance(iterator1,
// iterator2), where iterator1 will be
// l.begin() and iterator2 will be l.end()
int size = distance(l1.begin(),
l1.end());
cout << "Size of l1 is : " << size << endl;
l1.remove(6);
// It will erase all instaces of 6
// from the list
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);
// It will assign l2 to l at the
// provided iterator, making l1
// as empty.
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
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。