C ++如何在std :: vector中插入一个连续的区间范围? [英] C++ How to insert a consecutive inter range into std::vector?
本文介绍了C ++如何在std :: vector中插入一个连续的区间范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我希望从23到57的所有数字都在向量
中。我可以这样做:
Say I want all numbers from 23 to 57 be in a vector
. I can do this:
vector<int> result;
for (int i = 23; i <= 57; ++i)
{
result.push_back(i);
}
但这是简单工作的5行解决方案。我不能更优雅地做到这一点吗?最好的语法是 vector< int> result {23 .. 57};
例如这样的琐碎的单行代码。 C ++ 17有什么选择吗?
But this is a 5 line solution for a simple job. Can't I do that more elegantly? The best syntax would be vector<int> result{23 .. 57};
for example or such a trivial one line code. Any options with C++17?
推荐答案
您可以使用 std :: iota
(自C ++ 11起)。
You can use std::iota
(since C++11).
使用从
值
开始并重复评估++值$ c $的值依次增加的值填充[first,last)范围c>。
该函数以编程语言APL中的整数函数named命名。
The function is named after the integer function ⍳ from the programming language APL.
eg
std::vector<int> result(57 - 23 + 1);
std::iota(result.begin(), result.end(), 23);
这篇关于C ++如何在std :: vector中插入一个连续的区间范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文