回答編集履歴

4

yumetodoさんからご指摘を受けて

2018/01/24 05:42

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -51,6 +51,34 @@
51
51
  }
52
52
 
53
53
  ```
54
+
55
+
56
+
57
+ 修正:yumetodoさんからご指摘を受けて
58
+
59
+ ---
60
+
61
+ 今回の場合、[std::next](https://cpprefjp.github.io/reference/iterator/next.html)の方が簡潔に処理を記述できるようです。
62
+
63
+
64
+
65
+ yumetodoさんが書かれたslice_sum関数はこちら。
66
+
67
+ > ```C++
68
+
69
+ template<typename T>
70
+
71
+ int slice_sum(const std::vector<T>& v, size_t from, size_t to) {
72
+
73
+ assert(to <= v.size());
74
+
75
+ return std::accumulate(std::next(v.cbegin(), from), std::next(v.cbegin(), to), T{});
76
+
77
+ }
78
+
79
+ > ```
80
+
81
+
54
82
 
55
83
 
56
84
 

3

追記

2018/01/24 05:42

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -51,3 +51,79 @@
51
51
  }
52
52
 
53
53
  ```
54
+
55
+
56
+
57
+ コメントを受けて
58
+
59
+ ---
60
+
61
+ 構造体を利用する例。
62
+
63
+ ```C++
64
+
65
+ #include <iostream>
66
+
67
+ #include <numeric>
68
+
69
+ #include <vector>
70
+
71
+
72
+
73
+ struct Person {
74
+
75
+ Person(const std::string& name, const std::vector<int>& scores)
76
+
77
+ : name_(name), scores_(scores) { }
78
+
79
+
80
+
81
+ auto& get_name(void) const noexcept {
82
+
83
+ return this->name_;
84
+
85
+ }
86
+
87
+ auto& get_scores(void) const noexcept {
88
+
89
+ return this->scores_;
90
+
91
+ }
92
+
93
+
94
+
95
+ private:
96
+
97
+ const std::string& name_;
98
+
99
+ const std::vector<int> scores_;
100
+
101
+ };
102
+
103
+
104
+
105
+ int main(void) {
106
+
107
+ Person p("青木", {2, 3, 4, 5});
108
+
109
+
110
+
111
+ int sum = std::accumulate(
112
+
113
+ p.get_scores().cbegin(),
114
+
115
+ p.get_scores().cend(),
116
+
117
+ 0
118
+
119
+ );
120
+
121
+ std::cout << p.get_name() << " sum : " << sum << std::endl;
122
+
123
+
124
+
125
+ return 0;
126
+
127
+ }
128
+
129
+ ```

2

assert追加

2018/01/23 16:20

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -1,6 +1,8 @@
1
1
  [std::advance](https://cpprefjp.github.io/reference/iterator/advance.html)を使うと良いかと思います。
2
2
 
3
3
  ```C++
4
+
5
+ #include <cassert>
4
6
 
5
7
  #include <iterator>
6
8
 
@@ -13,6 +15,10 @@
13
15
 
14
16
 
15
17
  int slice_sum(const std::vector<int>& v, size_t from, size_t to) {
18
+
19
+ assert(to <= v.size());
20
+
21
+
16
22
 
17
23
  auto it_begin = v.cbegin(), it_end = v.cend();
18
24
 

1

成形

2018/01/23 15:54

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -40,7 +40,7 @@
40
40
 
41
41
 
42
42
 
43
- return 0;
43
+ return 0;
44
44
 
45
45
  }
46
46