如何为向量的前 n 个元素赋值?C++ [英] How to assign a value to the first n elements of a vector? c++

查看:34
本文介绍了如何为向量的前 n 个元素赋值?C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为向量的前 n 个元素赋值?比如说,我想将 1 分配给从索引 0 到索引 4 的向量.

How to assign a value to the first n elements of a vector? Say, I want to assign 1 to a vector from index 0 to index 4.

我已经有一个大小为 11 的向量.现在我想将 1 放在前 5 个元素中.

I already have a vector with size 11. Now I want to put 1 to the first 5 elements.

推荐答案

您可以使用 <代码>std::fillstd::fill_n:

You can use std::fill or std::fill_n:

std::fill(v.begin(), std::next(v.begin(), 5), 1);
std::fill_n(v.begin(), 5, 1);

注意:std::next 是 C++11.在这种情况下,它可以替换为 v.begin() + 5.

Note: std::next is C++11. In this case it can be replaced by v.begin() + 5.

这篇关于如何为向量的前 n 个元素赋值?C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆