问题描述
我有一个整数向量,我想将其转换为成对向量(成对包含一个 bool 和一个 int).我当前的代码很简单:
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?
推荐答案
1. 你可以创建一个函子和 std::for_each
:
1. You could make a functor and std::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 reusable :).
也许 boost::bind
可以做一些事情.
Maybe there is something that could be done with boost::bind
.
2. 我在想您也许可以使用带有后置插入器和转换的绑定.像这样:
2. 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));
我用 std::bind1st
尝试了这个,我认为它应该可以工作,但我只能用 boost::bind
让它成功.我会继续努力...
I tried this with std::bind1st
, i thought it should have worked, but i could only get it to succeed with boost::bind
. I'll keep trying...
3. 这是一个非提升解决方案:
3. 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));
4. 这是一个 C++11 解决方案(这是我目前最喜欢的):
4. here's a C++11 solution (which is my current favorite):
std::for_each(begin(a), end(a), [&b](int v) {
b.emplace_back(false, v);
});
甚至更简单:
for(int v : a) {
b.emplace_back(false, v);
}
这篇关于使用变换创建新向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!