将 std::vector<int> 设置为一个范围
Set std::vector<int> to a range
将std::vector<int>
设置为范围的最佳方法是什么,例如 3 到 16 之间的所有数字?
如果您有 C++11 支持或正在使用 STL,则可以使用 std::iota
:
std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);
如果没有,则实现您自己的。
如果你可以使用boost
,那么一个不错的选择是boost::irange
:
std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
参见 例如这个问题
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template<class OutputIterator, class Size, class Assignable>
void iota_n(OutputIterator first, Size n, Assignable value)
{
std::generate_n(first, n, [&value]() {
return value++;
});
}
int main()
{
std::vector<int> v; // no default init
v.reserve(14); // allocate 14 ints
iota_n(std::back_inserter(v), 14, 3); // fill them with 3...16
std::for_each(v.begin(), v.end(), [](int const& elem) {
std::cout << elem << "n";
});
return 0;
}
在 Ideone 上的输出
std::iota - 很有用,但它需要迭代器,在创建向量之前,....所以我采取自己的解决方案。
#include <iostream>
#include <vector>
template<int ... > struct seq{ typedef seq type;};
template< typename I, typename J> struct add;
template< int...I, int ...J>
struct add< seq<I...>, seq<J...> > : seq<I..., (J+sizeof...(I)) ... >{};
template< int N>
struct make_seq : add< typename make_seq<N/2>::type,
typename make_seq<N-N/2>::type > {};
template<> struct make_seq<0>{ typedef seq<> type; };
template<> struct make_seq<1>{ typedef seq<0> type; };
template<int start, int step , int ... I>
std::initializer_list<int> range_impl(seq<I... > )
{
return { (start + I*step) ...};
}
template<int start, int finish, int step = 1>
std::initializer_list<int> range()
{
return range_impl<start, step>(typename make_seq< 1+ (finish - start )/step >::type {} );
}
int main()
{
std::vector<int> vrange { range<3, 16>( )} ;
for(auto x : vrange)std::cout << x << ' ';
}
Output:
3 4 5 6 7 8 9 10 11 12 13 14 15 16
尝试使用 std::generate
.它可以基于公式为容器生成值
std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何设置一个范围来提取我想要获得的信息
- 不计算一个范围内的完美数
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 在 C++20 中将多个范围适配器连接到一个范围中
- 转到基于范围的 for 循环中的下一个迭代器
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 有没有办法在另一个函数中加入线程?(即超出其自身范围)
- 如何将一个范围替换为矢量中的另一个范围?
- 包含来自另一个文件的函数会导致范围错误(openFoam)
- 定义一个 void f(void) 函数,但使用来自同一范围的变量?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- 将整数范围映射到另一个范围
- 是否存在一个范围::视图::group_by对应项,它将所有元素都考虑在内,而不是只考虑连续的元素
- 检查IP是否在其他IP网络范围内,并查找下一个可用IP
- 为什么基于范围的 for 循环中的结构化绑定只是一个副本而不是引用?
- 基于范围的 for 循环将对象移动到另一个容器中?