c++ - How can I fill a vector with iterators of a different type? -
i have many examples of following code:
struct foo1 { foo1(int ii = 0, int jj = 0) { this->ii = ii; this->jj = jj; } int ii; int jj; }; struct foo2 { foo2() { } foo2(const foo1& f) { this->f = f; } foo1 f; }; typedef std::vector< foo2 > foo_v; typedef std::set< int > bar_s; bar_s barset; barset.insert(1); barset.insert(2); barset.insert(3); barset.insert(4); barset.insert(5); barset.insert(6); ... foo_v foovec; (bar_s::iterator b = barset.begin(); b != barset.end(); ++b) foovec.push_back(foo2(*b));
how can improve code it's filling new vector of foo2?
i thinking along lines of:
std::remove_copy_if(barset.begin(), barset.end(), std::back_inserter(foovec), ...)
but i'm struggling find way bind int
type new instances of foo2
struct.
note:
std::copy(barset.begin(), barset.end(), std::back_inserter(foovec));
gives me following error:
error 1 error c2679: binary '=' : no operator found takes right-hand operand of type 'int' (or there no acceptable conversion)
std::copy(barset.begin(), barset.end(), std::back_inserter(foovec));
int convertable `foo' (the constructor can called 1 int argument , not explicit).
error 1 error c2679: binary '=' : no operator found takes right-hand operand of type 'int' (or there no acceptable conversion)
this because foo2 can not contstructed int, foo1 , 1 step of implicit conversion allowed. can std::transform:
std::transform(barset.begin(), barset.end(), std::back_inserter(foovec), boost::lambda::constructor<foo2>());
the boost::lambda::constructor() can replaced std::fun_ptr(makefoo2):
foo2 makefoo2(const foo& f) { return f; }
Comments
Post a Comment