当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。