📜  C ++中的valarray shift()

📅  最后修改于: 2021-05-31 21:58:08             🧑  作者: Mango

shift()函数在valarray头文件中定义。此函数返回一个具有相同大小的新valarray,其位置偏移n个元素。如果n为负,则应用右移,如果n为正,则应用左移。

句法:

valarray shift (int n) const;

参数:此方法接受强制性参数n ,该参数表示要移动的元素数。

返回值:该函数在移位元素后返回新的valarray

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

范例1:-

// C++ program to demonstrate
// example of shift() function.
  
#include 
using namespace std;
  
int main()
{
    // Initializing valarray
    valarray varr = { 3, 2, 5, 4, 1 };
  
    // Declaring new valarray
    valarray varr1;
  
    // using shift() to shift elements to left
    // shifts valarray by 3 position
    varr1 = varr.shift(3);
  
    // Displaying elements of valarray after shifting
    cout << "The new valarray after shifting is = ";
  
    for (int& x : varr1)
        cout << x << " ";
  
    cout << endl;
  
    return 0;
}
输出:
The new valarray after shifting is = 4 1 0 0 0

示例2:

// C++ program to demonstrate
// example of shift() function.
  
#include 
using namespace std;
  
int main()
{
    // Initializing valarray
    valarray varr = { 3, 2, 5, 4, 1 };
  
    // Declaring new valarray
    valarray varr1;
  
    // using shift() to shift elements to right
    // shifts valarray by 2 position
    varr1 = varr.shift(-2);
  
    // Displaying elements of valarray after shifting
    cout << "The new valarray after shifting is = ";
  
    for (int& x : varr1)
        cout << x << " ";
  
    cout << endl;
  
    return 0;
}
输出:
The new valarray after shifting is = 0 0 3 2 5
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”