📜  C++中的valarray swap()函数

📅  最后修改于: 2021-05-30 03:16:57             🧑  作者: Mango

swap()函数在valarray头文件中定义。此函数用于将一个valarray的内容与另一个valarray交换。

句法:

void swap( valarray& valarray2 );

参数:此方法接受参数valarray2 ,该参数表示我们必须交换旧参数的另一个valarray。

返回值:该函数不返回任何内容。

下面的程序说明了上述函数:

范例1:-

// C++ program to demonstrate
// example of swap() function.
  
#include 
using namespace std;
  
int main()
{
    // Initializing 1st valarray
    valarray varr1 = { 12, 24, 36, 48 };
  
    // Initializing 2nd valarray
    valarray 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 
using namespace std;
  
int main()
{
    // Initializing 1st valarray
    valarray varr1 = { -12, -24, -36, -48 };
  
    // Initializing 2nd valarray
    valarray 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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”