2

Given a data structure which has a user defined constructor taking a parameter, something like this:

struct Foo {
    Foo() = default;
    Foo(const int) {}
};

And given 2 vectors of the same size: vector<int> input and vector<Foo> output. I'd like to be able to do this:

copy(cbegin(input), cend(input), begin(output))

Is there a way I can tell copy or some other standard algorithm to construct a Foo from the int that is being iterated over?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 3
    `std::transform` is your friend. – Max Langhof Jul 16 '19 at 13:02
  • 2
    Maybe something like https://stackoverflow.com/questions/18724999/why-no-emplacement-iterators-in-c11-or-c14/18726119 – Vittorio Romeo Jul 16 '19 at 13:03
  • @MaxLanghof Yeah that's what I was doing now. It's just annoying to have to write a lambda when the constructor is right there. – Jonathan Mee Jul 16 '19 at 13:06
  • @VittorioRomeo That is pretty much what I want. I take it from the presence of that question that it isn't possible to do this with the tools already available to us in the standard? – Jonathan Mee Jul 16 '19 at 13:07
  • 3
    You need a `back_inserter` if you want to use copy to create the objects. – NathanOliver Jul 16 '19 at 13:07
  • @NathanOliver Clever, so I can't do this with the `vector`s already being the same size, but I can construct when using `back_inserter`. That's not a perfect answer, but I can do a reserve before, so I think it works well enough. I'd accept if you wrote up an answer. – Jonathan Mee Jul 16 '19 at 13:13
  • It's already closed to a Q that shows it so no need. You can't use a pre-sized vector but you can use one that has been `reserved` so you don't have unnecessary allocations but this should have better performance because constructing a bunch of default object to just reassign them is wasteful. – NathanOliver Jul 16 '19 at 13:15
  • It seems to me like [`std::copy`](http://www.cplusplus.com/reference/algorithm/copy/) already calls `Foo::Foo(const int)`, as there are no other conversion mechanisms available. Maybe you can share the complete code to reproduce the issue? – Tiberiu Maran Jul 16 '19 at 13:20

0 Answers0