如何将提取运算符 (>>) 与向量一起使用<bool>?
How do you use the extraction operator (>>) with vector<bool>?
在vector<int> someVector
和istringstream someStringStream
的示例中,您可以这样做:
for (int i=0; i < someVector.size(); i++) {
someStringStream >> someVector[i];
}
我知道vector<bool>
是一个有效的实现,operator[]
返回一个引用对象。对于这段代码,我应该使用索引而不是迭代器,主要是为了可读性。目前,我使用的是:
for (int i=0; i < someVector.size(); i++) {
bool temp;
someStringStream >> temp;
someVector[i] = temp;
}
有没有更直接的实现方法?
如果您想要使用整个流,可以使用std::copy
或std::vector
范围构造函数:
std::stringstream ss("1 0 1 0");
std::vector<bool> vec;
std::copy(std::istream_iterator<bool>(ss), {}, std::back_inserter(vec));
现场演示
std::stringstream ss("1 0 1 0");
std::vector<bool> vec(std::istream_iterator<bool>(ss), {});
现场演示
现在看看你发布的例子,如果你确定你的std::vector
的大小是合适的,你可以使用std::generate
,就像下面的例子:
std::stringstream ss("1 0 1 0");
std::vector<bool> vec(4);
std::generate(std::begin(vec), std::end(vec), [&ss](){ bool val; ss >> val; return val;});
现场演示
如果您想要的只是bool和其他类型的相同接口,那么包装起来很容易。
template <typename T>
T read(std::istream& stream)
{
T value;
stream >> value; // TODO: guard against failure of extraction, e.g. throw an exception.
return value;
}
但是,直接使用它需要指定一个类型。
for (int i=0; i < someIntVector.size(); i++)
{
someIntVector[i] = read<int>(someStringStream);
}
for (int i=0; i < someBoolVector.size(); i++)
{
someBoolVector[i] = read<bool>(someStringStream);
}
如果你在几个不同的向量上重复使用它,只需重新换行:
template <typename T, typename A>
void fillVectorFromStream(std::istream& stream, std::vector<T, A>& vector)
{
for ( int i = 0; i < vector.size(); ++i )
{
vector[i] = read<T>(stream);
}
}
因此,用法就变成
fillVectorFromStream(streamOfBool, vectorOfBooleanValues);
fillVectorFromStream(streamOfIntegers, vectorOfIntegers);
相关文章:
- 如何将enable-if与模板参数和参数包一起使用
- 如何将PERF_AMPLE_READ与mmap一起使用
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将C++中的库和头与MinGW一起使用
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 为什么我不能将 rand() 与数组的大小一起使用?
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 将fold表达式与std::一起用于两个元组
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- EASTL矢量<向量<int>>连续的
- 将 std::allocate_shared 与多态资源分配器一起使用
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 将 exprtk 与自定义类的对象一起使用
- 将 std::set 与基于键的比较器一起使用
- 将 C++ 类与 Rcpp 一起使用,从 C 或 R 修改它
- 如何将 Eigen::Ref 与 pybind11 一起使用?
- 如何将AERT_Allocate与 std:vector 一起使用
- 如何使我的 sizeof sum 结构与空参数包一起工作