An iterator is passed to the function and the number of bytes that must be copied to the dynamic array, which is accessible via unique_ptr. How do I properly call std :: copy and std :: memcpy in this case?

void Foo(std::iterator<std::input_iterator_tag, uint8_t> iter, int32_t length) { unique_ptr<char[]> container = make_unique<char[]>(100); std::copy (iter, iter + length, container); // Как ΡΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ содСрТимоС iter Π² container std::memcpy (container, iter , length); // Как ΡΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ содСрТимоС iter Π² container for (int i = 0; i < length; i++) cout << container[i]; }; 
  • 2
    The std::iterator template has nothing to do with how you try to use it in this code. - AnT

1 answer 1

The answer for this code is nothing.

The fact is that std::iterator simply provides aliases iterator_category , value_type , difference_type , pointer , reference , and you must pass only the first two parameters to determine iterator_category and value_type , the other aliases for types will be made based on them, of course, if you they will fit. std::iterator does not provide any functionality, i.e. neither operator* , nor operator++ , etc. It does not have it, therefore it is not possible to use it as you wish.

It can be used, for example, to implement your iterator:

 class MyIterator: public std::iterator<std::input_iterator_tag, MyType> //НаслСдуСмся ΠΎΡ‚ std::iterator с Π½ΡƒΠΆΠ½Ρ‹ΠΌΠΈ Π°Ρ€Π³ΡƒΠΌΠ΅Π½Ρ‚Π°ΠΌΠΈ, //Ρ‡Ρ‚ΠΎΠ±Ρ‹ псСвдонимы сами ΡΠ³Π΅Π½Π΅Ρ€ΠΈΡ€ΠΎΠ²Π°Π»ΠΈΡΡŒ. 

It is worth noting that std::iterator since C++17 is obsolete.

  • Thanks for the answer. Can I somehow pass an arbitrary iterator to a function and use it there? Arbitrary in the sense of no matter what it will be for an iterator, an array or for example a vector. - mrFieldy
  • @mrFieldy Usually this is template<typename Itr> void foo(Itr begin, Itr end); . - bipll