问题
I would like to create a row vector in C++ with integer elements from and including 0 to N (an integer variable I assign in my C++ program). I have seen the Armadillo C++ library and tried using its span
function but it does not create a vector (rather creates an object with type arma::span
) so writing:
vec n = span(0,N);
does not create the desired vector. If it helps (like if my explanation of what I want is unclear) I know that in MATLAB this creates the vector I want:
n=0:N;
I do not really care which library (if any) is used, provided the library is available on most major Linux distributions (like my present one, Fedora 25).
回答1:
You could use std::iota
like so.
#include <numeric>
#include <vector>
#include <iostream>
int main()
{
int N = 9;
std::vector<int> n(N + 1);
std::iota(begin(n), end(n), 0);
for(auto i: n)
{
std::cout << i << '\n';
}
}
Theres probably also a cool way to do it at compile time using std::integer_sequence
and some metaprogramming.
回答2:
You can use the function std::iota like this:
std::vector<int> v(n + 1);
std::iota(v.begin(), v.end(), 0);
Or you could wrap that up into a function like this:
inline std::vector<int> zero_to_n_vector(std::size_t n)
{
std::vector<int> v(n + 1);
std::iota(v.begin(), v.end(), 0);
return v;
}
auto v = zero_to_n_vector(20);
来源:https://stackoverflow.com/questions/41030499/how-to-create-a-row-vector-with-elements-from-0-up-to-and-including-n-in-c