2.2.6. C++標準ライブラリのstd::vectorを使う例

 1// using std::vector
 2
 3// s003: dynamically allocated array held on a struct
 4// along with the data count.
 5//
 6#include <iostream>
 7#include <vector>
 8#include <cassert>
 9
10const int N_SIZE = 10;
11
12
13// function to set dummy data to the array
14void set_dummy_data(double *d, int n)
15{
16    for (int i = 0; i < n; i++) {
17        d[i] = static_cast<double>(i) / static_cast<double>(n);
18    }
19}
20
21void set_dummy_data_vec(std::vector<double> &vec)
22{
23    for (int i = 0; i < vec.size(); i++) {
24        vec[i] = static_cast<double>(i) / static_cast<double>(vec.size());
25    }
26}
27
28void copy_data(double *dest, const double *src, int n)
29{
30    for (int i = 0; i < n; i++) {
31        dest[i] = src[i];
32    }
33}
34
35void copy_data_vec(std::vector<double> &dest, const std::vector<double> &src)
36{
37    assert(dest.size() == src.size());
38    for (int i = 0; i < dest.size(); i++) {
39        dest[i] = src[i];
40    }
41}
42
43void print_data(std::ostream &os, const double *d, int n)
44{
45    os << "[";
46    for (int i = 0; i < n; i++) {
47        os << d[i];
48        if (i < n - 1) {
49            os << ", ";
50        }
51    }
52    os << "]\n";
53}
54
55void print_data_vec(std::ostream &os, const std::vector<double> &vec)
56{
57    os << "[";
58    for (int i = 0; i < vec.size(); i++) {
59        os << vec[i];
60        if (i < vec.size() - 1) {
61            os << ", ";
62        }
63    }
64    os << "]\n";
65}
66
67int main(int argc, const char *argv[])
68{
69    std::cout << "s006\n";
70
71    // allocate array dynamically on the heap area.
72    std::vector<double> vec1(N_SIZE, 0.0); // number of elems, initial value.
73    std::vector<double> vec2(N_SIZE, 0.0);
74
75    std::cout << "Before initialization\n";
76    print_data(std::cout, &vec1[0], N_SIZE);
77    print_data_vec(std::cout, vec1);
78
79    // 配列の名前のデータ型は配列要素のアドレス。
80    // 受ける側のdoubleのポインタに代入できる。
81    set_dummy_data(&vec1[0], N_SIZE);
82    set_dummy_data_vec(vec1);
83
84    std::cout << "After initialization\n";
85    print_data(std::cout, &vec1[0], N_SIZE);
86    print_data_vec(std::cout, vec1);
87
88    copy_data(&vec2[0], &vec1[0], N_SIZE);
89    copy_data_vec(vec2, vec1);
90
91    std::cout << "After array copy\n";
92    print_data(std::cout, &vec2[0], N_SIZE);
93    print_data_vec(std::cout, vec2);
94
95    // vectorが割り当てたメモリはvectorのデストラクタにおいて
96    // 自動的に解放される。
97
98    return EXIT_SUCCESS; // exit status code 0
99}

Download the source code