使用分配构造字符串时是否可以使用 cin?

Is it possible to use cin when using allocate to construct a string?

本文关键字:是否 可以使 cin 字符串 分配      更新时间:2023-10-16

我正在阅读使用分配器的内容,其中一个练习要求使用分配器从 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);

使用

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));

这是一个工作演示。