C++ Standard Library C++ STL Library

C++ <valarray> - cos() Function

The C++ <valarray> cos() function returns a valarray containing cosine value of all the elements of valarray va, in the same order. This function overloads with cmath's cos() function and calls this function once for each element.


template<class T> valarray<T> cos (const valarray<T>& va);


va Specify valarray containing elements of a type for which the function cos() is defined.

Return Value

Returns valarray containing cosine value of all the elements of va.


The example below shows the usage of cos() function.

#include <iostream>
#include <valarray>
using namespace std;
const double pi = acos(-1);

int main (){
  valarray<double> va1 = {0, pi/3, pi/2, pi};
  //va2 will contain cosine value
  //of all elements of va1
  valarray<double> va2 = cos(va1);

  cout<<"va1 contains: ";
  for(int i = 0; i < va1.size(); i++)
    cout<<va1[i]<<" ";

  cout<<"\nva2 contains: ";
  for(int i = 0; i < va2.size(); i++)
    cout<<va2[i]<<" ";   
  return 0;

The output of the above code will be:

va1 contains: 0.000000 1.047198 1.570796 3.141593 
va2 contains: 1.000000 0.500000 0.000000 -1.000000 

❮ C++ <valarray> Library