C++ List::size() 函式



C++ 的std::list::size()函式用於獲取列表中的元素數量。

列表的大小就是當前列表中存在的元素總數。如果列表為空列表,則此函式返回零作為列表大小,但如果列表為空但包含一些空格,則size()函式將所有空格計算為一個(1)並將其返回為當前列表的大小。

語法

以下是 C++ std::list::size() 函式的語法:

int size() const;

引數

  • 它不接受任何引數。

返回值

此函式返回容器中的元素數量。

示例 1

如果列表是非空列表,則此函式返回列表中的元素數量。

在下面的程式中,我們使用 C++ std::list::size() 函式來獲取當前列表 {1, 2, 3, 4, 5} 的大小。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<int> num_list = {1, 2, 3, 4, 5};
   cout<<"The list elements are: "<<endl;
   for(int l : num_list){
      cout<<l<<" ";
   }
   cout<<"\nThe size of list: "<<num_list.size()<<endl;
}

輸出

執行上述程式後,將產生以下輸出:

The list elements are: 
1 2 3 4 5 
The size of list: 5

示例 2

如果列表為空列表,則此函式返回零。

以下是 C++ std::list::size() 函式的另一個示例。在這裡,我們建立一個名為 empt_list 的列表(型別為 char),其值為為空。然後,使用 size() 函式,我們嘗試獲取當前列表的大小。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<char> empt_list = {};
   cout<<"The list elements are: ";
   for(char l : empt_list){
      cout<<l<<" ";
   }
   cout<<"\nThe size of list: "<<empt_list.size()<<endl;
}

輸出

以下是上述程式的輸出:

The list elements are: 
The size of list: 0

示例 3

如果列表(型別為字串)為空但包含空格,則 size() 函式將列表大小返回為 1。

在此示例中,我們建立一個名為 names 的列表(型別為字串),其值為為空 {" "}。使用 size() 函式,我們嘗試獲取此列表的大小。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<string> names = {" "};
   cout<<"The list elements are: ";
   for(string l : names){
      cout<<l<<" ";
   }
   cout<<"\nThe size of list: "<<names.size()<<endl;
}

輸出

上述程式產生以下輸出:

The list elements are:   
The size of list: 1
廣告

© . All rights reserved.