# generating sequence of natural numbers

This topic is 3754 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I use the following code to generate the first n natural numbers in a vector:
struct count
{
count(int initial): i(initial) {}
int operator()() { return i++; }
private:
int i;
};

const int n = 5;

int main()
{
std::vector<int> v(n);
std::generate(v.begin(), v.end(), count(1));
// ...
}

Question: does something like count already exist in the standard library? Is there an even better way?

##### Share on other sites
I suppose you could do this:

std::vector<int> v(n, 1);v[0] = initial;std::partial_sum(v.begin(), v.end(), v.begin());
Although it's not very generalised.

There's even:

for (int i = 0; i < n; ++i)    v = initial + i;

AFAICT there's nothing like iota in the standard C++ library.

[Edited by - dmatter on July 12, 2008 8:04:04 PM]

##### Share on other sites
I'm sure if there was an easier way Lippman would've used it in his "Essential C++" book since the majority of the book deals with generating various numerical sequences like fibonacci,lucas,pell,square,triangular,etc...
Never heard of iota that's a new one for me.

##### Share on other sites
With boost your code might be written as

#include <boost/iterator/counting_iterator.hpp>const int n = 5;int main(){    std::vector<int> v(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n + 1));    // ...}

1. 1
Rutin
46
2. 2
3. 3
4. 4
5. 5

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632995
• Total Posts
3009775
• ### Who's Online (See full list)

There are no registered users currently online

×