Marson Mao
Marson Mao

Reputation: 3035

How to use std algorithm to replace this for loop?

I have:

struct A
{
    int index;

    A(): index(0) {}
}
std::vector<A> ManyAs(10, A());

And wants to do:

for (int i = 0, size = ManyAs.size(); i < size; ++i)
{
    ManyAs[i].index = i;
}

I want to do this with std algotrithm, maybe std::for_each?

How to do it, thanks!

Upvotes: 1

Views: 975

Answers (4)

Marson Mao
Marson Mao

Reputation: 3035

Somehow I found my ideal answer:

std::for_each(ManyAs.begin(), ManyAs.end(),
    [&](A& a)
    {
        int offset=(&a) - (&ManyAs.front());
        a.index = offset;
    });

Actually it's quite similar to Raxvan's answer, but everything is local, which is better imo.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

I would do the following way

struct A
{
    int index;

    A(): index(0) {}
    A & operator =( int i )
    {
        index = i;
        return ( *this );
    }
};

std::iota( ManyAs.begin(), ManyAs.end(), 0 );

Upvotes: 3

In this particular case, I'd leave the code as it is. Standard library algorithms are best used when you want to apply the same operation to all elements of the range. But here, you don't actually apply the same operation, as you assign a different number to each element's index. So a counter-based for loop seems to be the most natural solution here.

However, if you really want to use a standard algorithm, you can use a stateful functor:

struct Functor
{
  size_t index;
  Functor() : index(0) {}
  void operator() (A &a) { a.index = index++; }
};

std::for_each(ManyAs.begin(), ManyAs.end(), Functor());

Upvotes: 2

Raxvan
Raxvan

Reputation: 6505

Here are two approaces:

struct my_functor
{
    my_functor()
        : i(0)
    {
    }
    void operator () (A & a)
    {
        a.index = i++;
    }
    int i;
};
void foo();
{
    //old c++ style
    std::for_each(ManyAs.begin(), ManyAs.end(), my_functor());
}

second:

//c++11
int i = 0;
std::for_each(ManyAs.begin(), ManyAs.end(), [&](A & a){ a.index = i++; });

Upvotes: 1

Related Questions