Reputation: 41
I'm reading up on using allocators and one of the exercises asks to use an allocator to read user input from cin. Right now I create the string using a default constructor then read into the string, but I want to know if its possible to directly create the string with the input from cin?
Current Code:
int n = 1;
std::allocator<std::string> alloc;
auto p = alloc.allocate(n);
auto q = p;
alloc.construct(q);
std::cin >> *q;
Ideally:
alloc.construct(q, input from cin);
Upvotes: 2
Views: 77
Reputation: 206567
Use of
std::cin >> *q;
does not look like a burden to me. I am not sure what's the motivation for wanting to use:
alloc.construct(q, input from cin);
Having said that, you can define a helper function.
template <typename T> T read(std::istream& in)
{
T t;
in >> t;
return t;
}
Use it as:
int n = 1;
std::allocator<std::string> alloc;
auto p = alloc.allocate(n);
auto q = p;
alloc.construct(q, read<std::string>(std::cin));
Here's a working demo.
Upvotes: 3