c++ - 如何将 STL vector 中的一系列元素设置为特定值?

标签 c++ stl vector variable-assignment

我有一个 bool vector 。我需要将其元素从第 n 次到第 m 次设置为 true .有没有不使用循环的优雅方法?

编辑:感谢所有指出使用 vector<bool> 问题的人.不过,我一直在寻找更通用的解决方案,比如 jalf 给出的解决方案。

最佳答案

algorithm header 中的

std::fillstd::fill_n 应该可以解决问题。

 // set m elements, starting from myvec.begin() + n to true
std::fill_n(myvec.begin() + n, m, true);

// set all elements between myvec.begin() + n and myvec.begin() + n + m to true
std::fill(myvec.begin() + n, myvec.begin() + n + m, true); 

关于c++ - 如何将 STL vector 中的一系列元素设置为特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1138724/

相关文章:

c++ - 在 netbeans 中将 C++ 代码输出为汇编语言

c++ - 使用 C 字符串时出错

c++ - 我应该更喜欢迭代器而不是 const_iterators 吗?

c++ - 错误 : non-aggregate type 'vector<string>' cannot be initialized with an initializer list

r 中具有多个条件的数据重估

c++ - 指向结构体指针数组的指针

c++ - C++中的动态二维数组,需要在每一行和整个数组中乘以偶数

c++ - STL拷贝效率

c++ - 如何将元素从 C++11 容器移动到容器的背面?

c++ - 删除 vector 中指针的适当方法