我正在阅读使用分配器,其中一个练习要求使用分配器从cin读取用户输入。现在我使用默认构造函数创建字符串然后读入字符串,但我想知道是否可以使用cin的输入直接创建字符串?
当前代码:
int n = 1;
std::allocator<std::string> alloc;
auto p = alloc.allocate(n);
auto q = p;
alloc.construct(q);
std::cin >> *q;
理想情况下:
alloc.construct(q, input from cin);
答案 0 :(得分:3)
使用
std::cin >> *q;
对我来说不是一种负担。我不确定想要使用的动机是什么:
alloc.construct(q, input from cin);
话虽如此,您可以定义辅助函数。
template <typename T> T read(std::istream& in)
{
T t;
in >> t;
return t;
}
将其用作:
int n = 1;
std::allocator<std::string> alloc;
auto p = alloc.allocate(n);
auto q = p;
alloc.construct(q, read<std::string>(std::cin));
这是working demo。