gpt4 book ai didi

c++ - 如何用不同类型的迭代器填充 vector ?

转载 作者:行者123 更新时间:2023-11-30 03:09:10 26 4
gpt4 key购买 nike

我有很多下面代码的例子:

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;
for (bar_s::iterator b = barSet.begin(); b != barSet.end(); ++b)
fooVec.push_back(foo2(*b));

如何改进填充 foo2 新 vector 的代码?

我在想一些事情:

std::remove_copy_if(barSet.begin(), barSet.end(), 
std::back_inserter(fooVec), ...)

但我正在努力寻找一种方法将 int 类型绑定(bind)到 foo2 结构的新实例。


注意:

std::copy(barSet.begin(), barSet.end(), std::back_inserter(fooVec));

给我以下错误:

错误 1 ​​error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there are no acceptable conversion)

最佳答案

std::copy(barSet.begin(), barSet.end(), std::back_inserter(fooVec));

int 可以转换为 `foo'(唯一的构造函数可以用一个 int 参数调用,它不是显式的)。

Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)

这是因为 foo2 不能从 int 构造,只能从 foo1 构造,并且只允许一步隐式转换。你可以 std::transform:

std::transform(barSet.begin(), barSet.end(), 
std::back_inserter(fooVec),
boost::lambda::constructor<foo2>());

boost::lambda::constructor() 可以用 std::fun_ptr(makeFoo2) 代替:

foo2 makeFoo2(const foo& f) { return f; }

关于c++ - 如何用不同类型的迭代器填充 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4334121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com