The C++ standard library
C++'s library is a library for numerical computation; it provides an efficient way to process numeric arrays. In the library, the valarray class template allows programmers to perform element-wise mathematical operations on arrays, including addition, subtraction, multiplication, division, etc. In addition, it supports more advanced math functions such as exponential, logarithm, sine, cosine, etc.
valarray is a class template in the C++ standard library, used to represent and manipulate numeric arrays. It provides a convenient way to perform element-wise array operations.
Syntax
valarray The basic syntax is as follows:
#include
int main() {
std::valarray va(10); // 创建一个包含10个double元素的valarray
va = 1; // 将所有元素初始化为1
// ...
return 0;
}
Example
1. Create and initialize a valarray
Example
#include
#include
int
main
(
)
{
std
::
valarray
<
double
va
(
5
);
// Create a valarray containing 5 double elements
va
=
{
1.0
,
2.0
,
3.0
,
4.0
,
5.0
}
;
// Initialize the valarray
for
(
auto
i
:
va
)
{
std
::
cout
<<
i
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Output result:
1 2 3 4 5
2. Basic operations
Example
#include
#include
int
main
(
)
{
std
::
valarray
<
double
va1
(
5
), va2
(
5
)
;
va1
=
{
1.0
,
2.0
,
3.0
,
4.0
,
5.0
}
;
va2
=
{
2.0
,
3.0
,
4.0
,
5.0
,
6.0
}
;
std
::
valarray
<
double
sum
=
va1
va2;
// Addition
std
::
valarray
<
double
diff
=
va1
va2;
// Subtraction
std
::
valarray
<
double
prod
=
va1
va2;
// Multiplication
std
::
valarray
<
double
quot
=
va1
/
va2;
// Division
std
::
cout
<<
"Sum: "
;
for
(
auto
i
:
sum
)
{
std
::
cout
<<
i
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Difference: "
;
for
(
auto
i
:
diff
)
{
std
::
cout
<<
i
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Product: "
;
for
(
auto
i
:
prod
)
{
std
::
cout
<<
i
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Quotient: "
;
for
(
auto
i
:
quot
)
{
std
::
cout
<<
i
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Output result:
Sum: 3 5 7 9 11
Difference: -1 -1 1 1 -1
Product: 2 6 12 20 30
Quotient: 0.5 0.6666667 0.75 0.8 0.8333334
3. Use valarray for math function operations
Example
#include
#include
#include
int
main
(
)
{
std
::
valarray
<
double
va
(
5
);
va
=
{
1.0
,
2.0
,
3.0
,
4.0
,
5.0
}
;
std
::
valarray
<
double
squares
=
va
va;
// Square
std
::
valarray
<
double
roots
=
std::
sqrt
(
va
)
;
// Square root
std
::
cout
<<
"Squares: "
;
for
(
auto
i
:
squares
)
{
std
::
cout
<<
i
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Square Roots: "
;
for
(
auto
i
:
roots
)
{
std
::
cout
<<
i
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Output result:
Squares: 1 4 9 16 25
Square Roots: 1 1.4142136 1.7320508