[英]Print Vector elements using Boost.Bind
I need to print the values inserted in the vector using Boost.Bind. 我需要使用Boost.Bind打印插入到向量中的值。 Please find the code snippet below:
请在下面找到以下代码段:
Please let me know what I am missing here? 请让我知道我在这里缺少什么?
class Test
{
int i;
public:
Test() {}
Test(int _i)
{
i = _i;
}
void print()
{
cout << i << ",";
}
};
int main()
{
std::vector<Test> vTest;
Test w1(5);
Test w2(6);
Test w3(7);
vTest.push_back(w1);
vTest.push_back(w2);
vTest.push_back(w3);
std::for_each(vTest.begin(), vTest.end(),boost::bind(boost::mem_fn(&Test::print), _1, ?)); // How do I print Vector elements here?
}
Maybe you do not want to have the parameter i
for your function print()
? 也许你不想让函数
print()
的参数i
? If so, you should simply do like this: 如果是这样,你应该这样做:
std::for_each(vTest.begin(), vTest.end(),boost::bind(&Test::print, _1));
This will output something like this: 5,6,7,
. 这将输出如下内容:
5,6,7,
. See live . 看到现场 。
If you still want to have some argument passed into your function, then you should pass it to bind()
: 如果你仍然希望将一些参数传递给你的函数,那么你应该将它传递给
bind()
:
std::for_each(vTest.begin(), vTest.end(),boost::bind(&Test::print, _1, 0));
0
will be your argument for Test::print()
. 0
将是Test::print()
。 And, in case of your code, you will have next output: 0,0,0,
. 而且,如果您的代码,您将有下一个输出:
0,0,0,
. See live . 看到现场 。
If you fix function to next one: 如果你将功能修复到下一个:
void print(int i)
{
cout << this->i << " " << i << ",";
}
output will be next: 5 0,6 0,7 0,
. 输出将是下一个:
5 0,6 0,7 0,
. See live 看到现场
You can do it without boost like this 你可以这样做而不需要提升
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
class Test {
int i;
public:
Test() {
}
Test(int _i) {
i = _i;
}
void print() const {
std::cout << i << std::endl;
}
};
int main() {
std::vector<Test> vTest;
Test w1(5);
Test w2(6);
Test w3(7);
vTest.push_back(w1);
vTest.push_back(w2);
vTest.push_back(w3);
// use lambda
std::for_each(vTest.begin(), vTest.end(), [&](const Test& t){ t.print(); });
// use std::bind
std::for_each(vTest.begin(), vTest.end(), std::bind(&Test::print, std::placeholders::_1));
return 0;
}
You don't need bind there. 你不需要在那里绑定。 Just replace the for_each from your code with the below statement.
只需使用以下语句替换代码中的for_each即可。
std::for_each(vTest.begin(), vTest.end(), std::mem_fn(&Test::print)) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.