gpt4 book ai didi

c++ - 使用 Boost.Bind 打印 Vector 元素

转载 作者:行者123 更新时间:2023-11-30 02:39:22 26 4
gpt4 key购买 nike

我需要使用 Boost.Bind 打印插入到 vector 中的值。请在下面找到代码片段:

请让我知道我在这里缺少什么?

   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?

}

最佳答案

像这样不用boost也可以做到

#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;
}

关于c++ - 使用 Boost.Bind 打印 Vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876430/

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