[英]no type named ‘value_type’ in ‘struct std::iterator_traits
I'm trying to implement a simple ostream_itreator, which streams every N-th element, but i get a type error我正在尝试实现一个简单的 ostream_itreator,它流式传输每个第 N 个元素,但我收到一个类型错误
error: no type named ‘value_type’ in ‘struct std::iterator_traits<outIterator<int> >’
typedef typename iterator_traits<_OI>::value_type _ValueTypeO;
Code:代码:
#include <iostream>
#include <vector>
#include <iterator>
template<class T>
class outIterator {
std::ostream *stream;
size_t N;
const char* delim;
size_t counter = 0;
public:
// initialization
outIterator(std::ostream& out)
: stream(&out)
, N(1)
, delim(" ")
{}
outIterator(std::ostream& out, size_t N, const char* delimiter)
: stream(&out)
, N(N)
, delim(delimiter)
{}
// =
outIterator<T>& operator= (const T& value) {
if (counter % N == 0){
*stream << value << delim;
}
return *this;
}
};
int main() {
outIterator<int> out(std::cout, 2, " ");
std::vector<int> vec {0, 1, 2, 3, 4, 5};
std::copy(vec.begin(), vec.end(), out);
return 0;
}
Also i didn't include overloadings ++ and ++(int).另外我没有包括重载++和++(int)。 They increment counter and return *this.
他们增加计数器并返回 *this。 And * overloading that returns *this
和 * 重载返回 *this
Error description:错误描述:
/usr/include/c++/7/bits/stl_algobase.h:378:57: error: no type named ‘value_type’ in ‘struct std::iterator_traits<outIterator<int> >’
typedef typename iterator_traits<_OI>::value_type _ValueTypeO;
^~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:383:9: error: no type named ‘value_type’ in ‘struct std::iterator_traits<outIterator<int> >’
const bool __simple = (__is_trivial(_ValueTypeI)
~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __is_pointer<_II>::__value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __is_pointer<_OI>::__value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __are_same<_ValueTypeI, _ValueTypeO>::__value);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Custom iterator types must either contain member typedefs for difference_type
, value_type
, pointer
, reference
, and iterator_category
or specialize std::iterator_traits
to provide the same.自定义迭代器类型必须包含用于
difference_type
、 value_type
、 pointer
、 reference
和iterator_category
成员类型定义,或者专门化std::iterator_traits
以提供相同的类型。
In your specific case, you should modify your outIterator
template like this:在您的特定情况下,您应该像这样修改
outIterator
模板:
template <typename T>
class outIterator {
//...
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::output_iterator_tag;
//...
};
When you write your iterator, you have to include some variable.当您编写迭代器时,您必须包含一些变量。 You only need to include these:
你只需要包括这些:
template <class T>
class iterator {
public:
// code ...
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = value_type*;
using reference = value_type&;
// code ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.