數組與C-style數組相比,這些類通常更高效,輕巧且可靠。 C++ 11中數組類的引入為C-style數組提供了更好的替代方法。
array::fill()
此函數用於為數組容器的所有元素設置一個公共值。
用法:
arrayname.fill(value) 參數: 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 <array> 
#include <iostream> 
using namespace std; 
  
int main() 
{ 
        // array container declaration 
    array<int, 4> myarray{ 1, 2, 3, 4 }; 
  
        // Using fill() function to  
    myarray.fill(5); 
  
        // printing the array 
    for(auto it=myarray.begin(); it<myarray.end(); ++it) 
        cout<<*it<<" "; 
    return 0; 
}輸出:
5 5 5 5
array::swap()
此函數用於將一個數組的內容與相同類型和大小的另一個數組交換。
用法:
arrayname1.swap(arrayname2) 參數: 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 <array> 
#include <iostream> 
using namespace std; 
  
int main() 
{ 
        // array container declaration 
    array<int, 4> myarray1{ 1, 2, 3, 4 }; 
    array<int, 4> 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.end(); ++it) 
        cout<<*it<<" "; 
  
        // printing the second array 
    cout<<endl<<"myarray2 = "; 
    for(auto it=myarray2.begin(); it<myarray2.end(); ++it) 
        cout<<*it<<" "; 
    return 0; 
}輸出:
myarray1 = 3 5 7 9 myarray2 = 1 2 3 4
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 array::fill() and array::swap() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
