使用分配构造字符串时是否可以使用 cin?
Is it possible to use cin when using allocate to construct a string?
我正在阅读使用分配器的内容,其中一个练习要求使用分配器从 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));
这是一个工作演示。
相关文章:
- 是否可以使C++类成为Objc类的委托
- 是否可以使一个类成为两个不同层次结构的子类?
- 是否可以使整数仅收到一个单个数字而不是两个接收输入
- 是否可以使 std 容器使用默认运算符为新?
- 是否可以使头文件使文本居中?- 在控制台中
- 如果必须在同一向量上写入线程,是否可以使用线程
- 对于具有两个模板化变量的模板化类,是否可以使一个 var 引用另一个 var
- 语法错误,也想知道我是否可以使这段代码更有效率
- 是否可以使结构直接返回值
- 是否可以使函数模板从函数引用中获取“decltype”
- 是否可以使您的Qt应用程序在运行时不锁定文件
- 是否可以使函数模板对不适当的类型而不是错误执行默认操作
- 是否可以使程序的执行跳过 fprintf-语句/如何创建我自己的 fprintf 函数
- 传递给std::basic_string的分配器是否可以使其方法为虚拟的
- 是否可以使类路径成为JNI库中的@rpath
- 是否可以使指向派生类对象的基类指针访问在派生类中声明的新成员
- 是否可以使函数接受给定参数的多种数据类型
- 是否可以使作用域枚举("enum class")在上下文中可转换为布尔值?
- 是否可以使std::string始终包含一个小写字符串
- 是否可以使函数对于常量参数或变量参数的行为不同