當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ forward_list resize()用法及代碼示例


forward_list::resize()是C++ STL中的內置函數,可更改forward_list的大小。如果給定的大小大於當前大小,則在forward_list的末尾插入新元素。如果給定的大小小於當前大小,則多餘的元素將被銷毀。

用法:

forwardlist_name.resize(n)

參數:該函數僅接受一個強製性參數n,該參數指定了轉發列表的新大小。


返回值:該函數不返回任何內容。

以下示例程序旨在說明上述函數:

示例1:

// C++ program to illustrate the 
// forward_list::resize() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    forward_list<int> fl = { 10, 20, 30, 40, 50 }; 
  
    // Prints the forward list elements 
    cout << "The contents of forward list :"; 
    for (auto it = fl.begin(); it != fl.end(); ++it) 
        cout << *it << " "; 
  
    cout << endl; 
  
    // resize to 7 
    fl.resize(7); 
  
    // // Prints the forward list elements after resize() 
    cout << "The contents of forward list :"; 
    for (auto it = fl.begin(); it != fl.end(); ++it) 
        cout << *it << " "; 
  
    return 0; 
}
輸出:
The contents of forward list :10 20 30 40 50 
The contents of forward list :10 20 30 40 50 0 0

示例2:

// C++ program to illustrate the 
// forward_list::resize() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    forward_list<int> fl = { 10, 20, 30, 40, 50 }; 
  
    // Prints the forward list elements 
    cout << "The contents of forward list :"; 
    for (auto it = fl.begin(); it != fl.end(); ++it) 
        cout << *it << " "; 
  
    cout << endl; 
  
    // resize to 3 
    fl.resize(3); 
  
    // Prints the forward list elements after resize() 
    cout << "The contents of forward list :"; 
    for (auto it = fl.begin(); it != fl.end(); ++it) 
        cout << *it << " "; 
  
    return 0; 
}
輸出:
The contents of forward list :10 20 30 40 50 
The contents of forward list :10 20 30


相關用法


注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 forward_list resize() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。