English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ List resize()函数更改列表容器的大小。
如果n小于当前容器的大小,则列表容器将减少为n个元素,并删除所有扩展n空间的元素。
如果n大于当前容器的大小,则容器的大小会增加,并且可以在扩展的空间中插入更多元素。
void resize(size_type n, value_type val)
n:这是新的容器大小。
val:它是要插入到新构建的列表中的值。
它不返回任何值。
让我们看一个简单的示例,其中n小于当前容器的大小。
#include<iostream> #include<list> using namespace std; int main() { list<int> li={1,2,3,4,5}; list<int>::iterator itr; std::cout << "列表li内容是:" << std::endl; for(itr=li.begin();itr!=li.end();++itr) cout<<*itr<<","; li.resize(3); cout<<'\n'; std::cout << "After resizing, the content of the list li is: " << std::endl; for(itr=li.begin();itr!=li.end();++itr) cout<<*itr<<","; return 0; }
Output:
The content of the list li is: 1,2,3,4,5 After resizing, the content of the list li is: 1,2,3
在此示例中,resize()函数将列表容器的大小减小2因此,列表的最后两个元素已被删除,输出变为1,2,3。
让我们看一个简单的示例,其中n大于当前容器的大小。
#include<iostream> #include<list> using namespace std; int main() { list<int> li={10,20,30,40}; list<int>::iterator itr; std::cout << "列表li内容是:" << std::endl; for(itr=li.begin();itr!=li.end();++itr) cout<<*itr<<","; li.resize(7,50); cout<<'\n'; std::cout << "After resizing, the content of the list li is: " << std::endl; for(itr=li.begin();itr!=li.end();++itr) cout<<*itr<<","; return 0; }
Output:
The content of the list li is: 10,20,30,40 After resizing, the content of the list li is: 10,20,30,40,50,50,50
In this example, the resize() function increases the size of the list3, and the new element (i.e.,50) Inserted into the newly constructed list.