回答編集履歴
3
修正
test
CHANGED
@@ -21,7 +21,7 @@
|
|
21
21
|
質問のコードは本当に教材のコードそのままなんでしょうか?
|
22
22
|
back_inserter はクラステンプレートなのに、<> を付けない
|
23
23
|
`auto out = back_inserter(temp) ;` はエラーになりませんか?
|
24
|
-
copy の第
|
24
|
+
copy の第3引数は output_iterator の要件を満たしていなければいけないのに
|
25
25
|
back_inserterクラスには *演算子も、++演算子も定義されていません。
|
26
26
|
標準ライブラリの back_inserter はクラスではなく関数テンプレートであり、
|
27
27
|
その関数は back_inserter_iteratorクラスのオブジェクトを返します。
|
2
追記
test
CHANGED
@@ -16,3 +16,61 @@
|
|
16
16
|
それがメンバ関数なのかメンバ変数なのかメンバ型なのか分かりません。
|
17
17
|
そこで typename Container::value_type と書くのです。
|
18
18
|
|
19
|
+
|
20
|
+
**追記**
|
21
|
+
質問のコードは本当に教材のコードそのままなんでしょうか?
|
22
|
+
back_inserter はクラステンプレートなのに、<> を付けない
|
23
|
+
`auto out = back_inserter(temp) ;` はエラーになりませんか?
|
24
|
+
copy の第2引数は output_iterator の要件を満たしていなければいけないのに
|
25
|
+
back_inserterクラスには *演算子も、++演算子も定義されていません。
|
26
|
+
標準ライブラリの back_inserter はクラスではなく関数テンプレートであり、
|
27
|
+
その関数は back_inserter_iteratorクラスのオブジェクトを返します。
|
28
|
+
|
29
|
+
次のように書かないと正しく動かないのではありませんか?
|
30
|
+
```C++
|
31
|
+
#include <iostream>
|
32
|
+
#include <vector>
|
33
|
+
|
34
|
+
template <typename Container>
|
35
|
+
struct back_inserter_iterator {
|
36
|
+
using container_type = Container;
|
37
|
+
using value_type = void;
|
38
|
+
using pointer = void;
|
39
|
+
using reference = void;
|
40
|
+
using difference_type = void;
|
41
|
+
using iterator_category = std::output_iterator_tag;
|
42
|
+
|
43
|
+
back_inserter_iterator(Container& c) : c(c) { }
|
44
|
+
|
45
|
+
back_inserter_iterator& operator=(const typename Container::value_type & value) {
|
46
|
+
c.push_back(value);
|
47
|
+
return *this;
|
48
|
+
}
|
49
|
+
back_inserter_iterator& operator*() { return *this; }
|
50
|
+
back_inserter_iterator& operator++() { return *this; }
|
51
|
+
back_inserter_iterator& operator++(int) { return *this; }
|
52
|
+
|
53
|
+
Container& c;
|
54
|
+
};
|
55
|
+
|
56
|
+
template <typename Container>
|
57
|
+
back_inserter_iterator<Container> back_inserter(const Container& c) {
|
58
|
+
return back_inserter_iterator<Container>(c); // クラステンプレートには <> が必要。
|
59
|
+
}
|
60
|
+
|
61
|
+
template <typename Container>
|
62
|
+
void f(const Container& c) {
|
63
|
+
std::vector<typename Container::value_type> temp;
|
64
|
+
auto out = back_inserter(temp); // 関数テンプレートの呼び出しは <> がなくてもよい
|
65
|
+
std::copy(std::begin(c), std::end(c), out);
|
66
|
+
|
67
|
+
for (auto e : temp) std::cout << e << std::endl;
|
68
|
+
}
|
69
|
+
|
70
|
+
int main() {
|
71
|
+
std::vector<int> a = { 3, 1, 4, 2 };
|
72
|
+
f(a);
|
73
|
+
}
|
74
|
+
```
|
75
|
+
|
76
|
+
|
1
語句修正
test
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
Container はテンプレート引数であり、型名です。
|
2
2
|
型といっても、ここでは int や double のような型ではなく、
|
3
3
|
vector<int> や list<double> のようなクラス型であることを仮定しています。
|
4
|
-
クラスの
|
4
|
+
クラスの内部には、メンバ関数やメンバ変数以外にメンバ型があります。
|
5
5
|
|
6
6
|
vectorクラスは、`template<typename T> class vector { ... };` と定義されて
|
7
7
|
いるテンプレートクラスで、size や begin といったメンバ関数を持っています。
|