tags:

views:

199

answers:

1

I have a vector of integers and I want to convert it to a vector of pairs (pair consists of a bool and a int). My current code is simple like this:

    std::vector<int> a;
    std::vector<std::pair<bool,int> > b;

    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    for(int i = 0; i < a.size(); ++i)
    {
     b.push_back(std::make_pair(false, a[i]));
    }

Is there any way to do this without writing the loop myself? Probably using some algorithms?

+6  A: 

1. You could make a functor and and for_each:

struct F {
    F(std::vector<std::pair<bool,int> > &b) : m_b(b){
    }

    void operator()(int x) {
        m_b.push_back(std::make_pair(false, x));
    }

    std::vector<std::pair<bool,int> > &m_b;
};

std::for_each(a.begin(), a.end(), F(b));

Though this may prove to be more trouble than it's worth. But at least it would be reuseable :).

Maybe there is something that could be done with boost bind.

2. EDIT: I was thinking you might be able to use bind with a back inserter and transform. something like this:

std::transform(a.begin(), a.end(), std::back_inserter(b), boost::bind(std::make_pair<bool, int>, false, _1));

I tried this with bind1st, i thought it should have worked, but i could only get it to succeed with boost::bind. I'll keep trying...

3. EDIT: here's a non-boost solution:

std::transform(a.begin(), a.end(), std::back_inserter(b), std::bind1st(std::ptr_fun(std::make_pair<bool, int>), false));
Evan Teran
Thanks..I was hoping there would be simpler way than doing this.. Also can you edit the answer so that the parameter passed to the constructor is not a const reference. I am not using boost so I have live with the standard STL algorithms.
Naveen
good call on the const, force of habit to default to const :)
Evan Teran