NUMCXX  0.13.20181108
Numerical library for small projects and teaching purposes
05-cxx-style-sharedptr2.cxx
Go to the documentation of this file.
1 #include <cstdio>
9 #include <vector>
10 #include <memory>
11 
12 
16 
17 void initialize(std::vector<double> &x)
18 {
19  const int n=x.size();
20  for (int i=0;i<n;i++) x[i]= 1.0/(double)(1+n-i);
21 }
22 
23 double sum_elements(std::vector<double> & x)
24 {
25  double sum=0;
26  for (int i=0;i<x.size();i++)sum+=x[i];
27  return sum;
28 }
29 
30 int main()
31 {
32  const int n=12345678;
33 
34  // This is a shortcut to the cumbersome statement from
35  // Example 04. We have to write the data type only once,
36  // as a template argument to std::make_shared<>.
37  auto x=std::make_shared<std::vector<double>>(n);
38 
39  // Dereference the smart pointer here in order to
40  // obtain a reference which can be used as an argumet to the functions.
41  initialize(*x);
42  double s=sum_elements(*x);
43  printf("sum=%e\n",s);
44 
45  // The shared pointer is destroyed, reference counter decremented
46  // and, as it becomes 0, the allocated memory is released.
47  return 0;
48 }
49 
void initialize(std::vector< double > &x)
We pass (as in example 03) a reference to the vector to the functions using it.
double sum_elements(std::vector< double > &x)
A::value_type sum(const A &a)
Sum of array or expression.
Definition: util.ixx:81