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

标签 c++ boost

我需要使用 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/

相关文章:

c++ - 为什么是 std::bitset::reference::operator~?

c++ - 改进这个 std::index_sequence 惯用法代码

c++ - 获取非侵入式 boost 序列化 C++ 的私有(private)数据成员

c++ - 用于组合类的 Boost Karma 生成器

c++ - Boost Spirit Karma - 具有约束和传播失败的字符串输出 vector ?

c++ - "mangle"(代表)内存的最佳方式

c++ - 如何在 qt 标签中显示 em dash 字符?

c++ - 将父对象静态转换为子 C++

c++ - 使用反向迭代器 boost ptree 失败

C++ boost : initializing endpoint after contructor