我正在使用一个名为 Buffer 的类,它具有以下运算符:
unsigned char &operator[](size_t index)
我正在尝试像这样从中复制:
std::copy(buf[96], buf[96 + 32], my_uint32_t);
我觉得不行
/usr/include/c++/7/bits/stl_algobase.h: In instantiation of '_OI std::__copy_move_a(_II, _II, _OI) [with bool _IsMove = false; _II = unsigned char; _OI = unsigned int]':
/usr/include/c++/7/bits/stl_algobase.h:422:45: required from '_OI std::__copy_move_a2(_II, _II, _OI) [with bool _IsMove = false; _II = unsigned char; _OI = unsigned int]'
/usr/include/c++/7/bits/stl_algobase.h:455:8: required from '_OI std::copy(_II, _II, _OI) [with _II = unsigned char; _OI = unsigned int]'
/home/project/SimplePacketCrafter.h:36:95: required from here
/usr/include/c++/7/bits/stl_algobase.h:377:57: error: no type named 'value_type' in 'struct std::iterator_traits<unsigned char>'
typedef typename iterator_traits<_II>::value_type _ValueTypeI;
^~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:378:57: error: no type named 'value_type' in 'struct std::iterator_traits<unsigned int>'
typedef typename iterator_traits<_OI>::value_type _ValueTypeO;
^~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:379:64: error: no type named 'iterator_category' in 'struct std::iterator_traits<unsigned char>'
typedef typename iterator_traits<_II>::iterator_category _Category;
^~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:383:9: error: no type named 'value_type' in 'struct std::iterator_traits<unsigned char>'
const bool __simple = (__is_trivial(_ValueTypeI)
~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __is_pointer<_II>::__value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __is_pointer<_OI>::__value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __are_same<_ValueTypeI, _ValueTypeO>::__value);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:386:44: error: no type named 'iterator_category' in 'struct std::iterator_traits<unsigned char>'
return std::__copy_move<_IsMove, __simple,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
_Category>::__copy_m(__first, __last, __result);
因为我认为我应该在前两个中传递一个地址。还有
unsigned char *index(size_t index)
但是还是不行
方法可以看here
最佳答案
std:copy()
采用迭代器,而不是引用。这就是您收到错误的原因。
原始指针可以用作迭代器,前提是指向的元素按顺序存储在内存中。因此,假设缓冲区的 operator[]
返回对单个内存缓冲区中元素的引用,您可以使用 &
地址运算符来获取 的内存地址char
被 operator[]
引用,然后 std::copy()
可以在这两个地址之间迭代:
std::copy(&buf[96], &buf[96 + 32], my_uint32_t);
或者,缓冲区的 index()
和 c_index()
方法返回等效指针:
std::copy(buf.index(96), buf.index(96 + 32), my_uint32_t);
std::copy(buf.c_index(96), buf.c_index(96 + 32), my_uint32_t);
关于c++ - 如何在类具有 `unsigned char &operator[]` 时使用 std::copy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59383681/