开发者

for_each bind vector of vector resize

This is my first question. I gave up and will use a hand rolled functor for this, but I am curious as to how it is supposed to be done. The contrived example below is intended to resize all of the vectors in a vector to be of size 9, by filling them with nulls. The indicated line causes MinGW GCC 4.5.0 to spew a lot of template errors. I've tried several different permutations, but only posted the code that I consider to be "closest to correct" below. How should it be written? Note, I want to retain the two-argument version of resize.

#include <vector>
using std::vector;
#include <algorithm>
using std::for_each;
#include <tr1/functional>
using std::tr1::bind;
using std::tr1::placeholders::_1;

int main() {
 vector<vector<void *> > stacked_vector(20);
 for_each(stacked_vector.begin(),stac开发者_StackOverflow社区ked_vector.end(),
  bind(&std::vector<void *>::resize,_1,9,0/*NULL*/));  // voluminous error output
 return 0;
}

Thank you very much for your input.


It's hard to say without seeing the error output (and frankly, even with it). However, try passing the NULL as a void* type: static_cast<void*>(0). Otherwise the object returned by bind tries to give an int value as the second parameter to resize.


Try this.

#include <functional> 
#include <algorithm> 
#include <iostream> 
#include <vector>


int main() 
{ 
    typedef std::vector<int> vec_int;
    typedef std::vector<vec_int> vec_vec_int;

    // Do this to make the   _1    work
    using namespace std::placeholders; 

    static const int FIRST_DIM = 5;
    static const int SECOND_DIM = 10;
    static const int DEFAULT_VALUE = 66;

    vec_vec_int v(FIRST_DIM);

    std::for_each(v.begin(), v.end(), 
        std::bind(&vec_int::resize, _1, SECOND_DIM, DEFAULT_VALUE));

    std::cout << v[4][9];

    return (0); 
} 

If you do not want to specify the default value, you do not need to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜