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


C++ valarray swap()用法及代碼示例


swap()函數在valarray頭文件中定義。此函數用於將一個valarray的內容與另一個valarray交換。

用法:

void swap( valarray& valarray2 );

參數:此方法接受一個參數valarray2,該參數表示另一個valarray,我們必須使用該valarray交換舊的valarray。


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

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

示例1:

// C++ program to demonstrate 
// example of swap() function. 
  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initializing 1st valarray 
    valarray<int> varr1 = { 12, 24, 36, 48 }; 
  
    // Initializing 2nd valarray 
    valarray<int> varr2 = { 20, 40, 60, 80 }; 
  
    varr1.swap(varr2); 
  
    // Displaying valarrays after swapping 
    cout << "The contents of 1st valarray "
            "after swapping are : "; 
  
    for (int& x : varr1) 
        cout << x << " "; 
  
    cout << endl; 
  
    cout << "The contents of 2nd valarray "
            "after swapping are : "; 
  
    for (int& x : varr2) 
        cout << x << " "; 
  
    cout << endl; 
  
    return 0; 
}
輸出:
The contents of 1st valarray after swapping are : 20 40 60 80 
The contents of 2nd valarray after swapping are : 12 24 36 48

示例2:

// C++ program to demonstrate 
// example of swap() function. 
  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Initializing 1st valarray 
    valarray<int> varr1 = { -12, -24, -36, -48 }; 
  
    // Initializing 2nd valarray 
    valarray<int> varr2 = { 20, 40, 60, 80 }; 
  
    varr1.swap(varr2); 
  
    // Displaying valarrays after swapping 
    cout << "The contents of 1st valarray "
            "after swapping are : "; 
  
    for (int& x : varr1) 
        cout << x << " "; 
  
    cout << endl; 
  
    cout << "The contents of 2nd valarray "
            "after swapping are : "; 
  
    for (int& x : varr2) 
        cout << x << " "; 
  
    cout << endl; 
  
    return 0; 
}
輸出:
The contents of 1st valarray after swapping are : 20 40 60 80 
The contents of 2nd valarray after swapping are : -12 -24 -36 -48


相關用法


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