📜  C++ STL中的array :: fill()和array :: swap()

📅  最后修改于: 2021-05-30 13:53:00             🧑  作者: Mango

数组类通常比C型数组更有效,更轻量且更可靠。 C++ 11中数组类的引入为C样式数组提供了更好的替代方法。

array :: fill()

此函数用于为数组容器的所有元素设置一个公共值。

句法 :

arrayname.fill(value)
Parameters :
The value to be set for all the elements of
the container is passed as parameter.
Result :
All the elements of the container are
set to be equal to the parameter passed.

例子:

Input  : myarray = {1, 2, 3, 4}
         myarray.fill(5);
Output : myarray = {5, 5, 5, 5}

Input  : myarray = {1, 2, 3, 4, 5, 6, 7}
         myarray.fill(2);
Output : myarray = {2, 2, 2, 2, 2, 2, 2}

错误和异常

1.如果赋值操作抛出一些错误,它将引发一个错误。
2.否则,它有一个基本的无异常抛出保证。

// CPP program to illustrate
// Implementation of fill() function
#include 
#include 
using namespace std;
  
int main()
{
        // array container declaration
    array myarray{ 1, 2, 3, 4 };
  
        // Using fill() function to 
    myarray.fill(5);
  
        // printing the array
    for(auto it=myarray.begin(); it

输出:

5 5 5 5
array :: swap()

此函数用于将一个数组的内容与相同类型和大小的另一个数组交换。

句法 :

arrayname1.swap(arrayname2)
Parameters :
The name of the array with which
the contents have to be swapped.
Result :
All the elements of the 2 array are swapped.

例子:

Input  : myarray1 = {1, 2, 3, 4}
         myarray2 = {3, 5, 7, 9}
         myarray1.swap(myarray2);
Output : myarray1 = {3, 5, 7, 9}
         myarray2 = {1, 2, 3, 4}

Input  : myarray1 = {1, 3, 5, 7}
         myarray2 = {2, 4, 6, 8}
         myarray1.swap(myarray2);
Output : myarray1 = {2, 4, 6, 8}
         myarray2 = {1, 3, 5, 7}

错误和异常

1.如果数组不是同一类型,则会引发错误。
2.如果数组的大小不同,则会引发错误。
2.否则,它有一个基本的无异常抛出保证。

// CPP program to illustrate
// Implementation of swap() function
#include 
#include 
using namespace std;
  
int main()
{
        // array container declaration
    array myarray1{ 1, 2, 3, 4 };
    array myarray2{ 3, 5, 7, 9 };
  
        // using swap() function to swap elements of arrays
    myarray1.swap(myarray2);
  
        // printing the first array
    cout<<"myarray1 = ";
    for(auto it=myarray1.begin(); it

输出:

myarray1 = 3 5 7 9 
myarray2 = 1 2 3 4 
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”