📜  C++ STL中的数组算法(all_of,any_of,none_of,copy_n和iota)

📅  最后修改于: 2021-05-25 19:14:16             🧑  作者: Mango

从C++ 11开始,在C++的STL中添加了一些有趣的新算法。这些算法在数组上运行,可用于节省编码时间,因此也可用于竞争性编程。

所有的()

此函数可在整个数组元素范围内运行,并可节省运行循环以逐个检查每个元素的时间。它检查每个元素上的给定属性,并在范围内的每个元素满足指定属性时返回true,否则返回false。

// C++ code to demonstrate working of all_of()
#include
#include // for all_of()
using namespace std;
int main()
{
    // Initializing array
    int ar[6] =  {1, 2, 3, 4, 5, -6};
  
    // Checking if all elements are positive
    all_of(ar, ar+6, [](int x) { return x>0; })?
          cout << "All are positive elements" :
          cout << "All are not positive elements";
  
    return 0;
  
}

输出:

All are not positive elements

在上面的代码中,-6为负元素会否定条件并返回false。

任何()

如果甚至没有一个元素满足函数提到的给定属性,则此函数检查给定范围。如果至少一个元素满足该属性,则返回true,否则返回false。

// C++ code to demonstrate working of any_of()
#include
#include // for any_of()
using namespace std;
int main()
{
    // Initializing array
    int ar[6] =  {1, 2, 3, 4, 5, -6};
  
    // Checking if any element is negative
    any_of(ar, ar+6, [](int x){ return x<0; })?
          cout << "There exists a negative element" :
          cout << "All are positive elements";
  
    return 0;
  
}

输出:

There exists a negative element

在上面的代码中,-6使条件为正。

没有()

如果没有元素满足给定条件,则此函数返回true,否则返回false。

// C++ code to demonstrate working of none_of()
#include
#include // for none_of()
using namespace std;
int main()
{
    // Initializing array
    int ar[6] =  {1, 2, 3, 4, 5, 6};
  
    // Checking if no element is negative
    none_of(ar, ar+6, [](int x){ return x<0; })?
          cout << "No negative elements" :
          cout << "There are negative elements";
  
    return 0;
}

输出:

No negative elements

由于所有元素都是正数,因此该函数返回true。

copy_n()

copy_n()将一个数组元素复制到新数组。这种类型的副本会创建数组的深层副本。此函数接受3个参数,即源数组名称,数组大小和目标数组名称。

// C++ code to demonstrate working of copy_n()
#include
#include // for copy_n()
using namespace std;
int main()
{
    // Initializing array
    int ar[6] =  {1, 2, 3, 4, 5, 6};
  
    // Declaring second array
    int ar1[6];
  
    // Using copy_n() to copy contents
    copy_n(ar, 6, ar1);
  
    // Displaying the copied array
    cout << "The new array after copying is : ";
    for (int i=0; i<6 ; i++)
       cout << ar1[i] << " ";
  
    return 0;
  
}

输出:

The new array after copying is : 1 2 3 4 5 6

在上面的代码中,使用copy_n()将ar的元素复制到ar1中

iota()

此函数用于为数组分配连续值。此函数接受3个参数,即数组名称,大小和起始编号。

// C++ code to demonstrate working of iota()
#include
#include // for iota()
using namespace std;
int main()
{
    // Initializing array with 0 values
    int ar[6] =  {0};
  
    // Using iota() to assign values
    iota(ar, ar+6, 20);
  
    // Displaying the new array
    cout << "The new array after assigning values is : ";
    for (int i=0; i<6 ; i++)
       cout << ar[i] << " ";
  
    return 0;
  
}

输出:

The new array after assigning values is : 20 21 22 23 24 25

在上面的代码中,使用iota()将连续值分配给数组。

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。