Jump to content
  • Advertisement
Sign in to follow this  
DevFred

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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));
// ...
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!