std::vector<int>
3 から 16 までのすべての数値など、範囲を設定する最良の方法は何ですか?
48474 次
5 に答える
66
std::iota
C++11 をサポートしている場合、またはSTLを使用している場合に使用できます。
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));
于 2012-08-15T07:51:22.757 に答える
24
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
于 2012-08-15T07:51:18.823 に答える
8
たとえば、この質問を参照してください
#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での出力
于 2012-08-15T07:55:29.063 に答える
1
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
于 2013-10-31T10:45:55.783 に答える
1
使ってみてくださいstd::generate
。式に基づいてコンテナの値を生成できます
std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});
于 2020-01-31T22:28:35.323 に答える