本文介绍了在C ++中迭代结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

typedef struct A
{
    int a;
    int b;
    char * c;
}aA;

我想遍历结构的每个成员并打印它的值。类似:

I want to iterate over each an every member of the structure and print its value. Something like:

void print_struct_value(struct *A)
{
    for each member of struct A
    cout << "struct name . member name" << "value";
}

如何在C ++中完成

推荐答案

也许你可以使用Boost Fusion / Phoenix将一些字符串连接起来:

Perhaps you can string something together using Boost Fusion/Phoenix:

strong> !

See it live on Coliru!

#include <boost/fusion/adapted/struct.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/phoenix/phoenix.hpp>
using boost::phoenix::arg_names::arg1;

#include <string>
#include <iostream>

struct A
{
    int a;
    int b;
    std::string c;
};

BOOST_FUSION_ADAPT_STRUCT(A, (int,a)(int,b)(std::string,c));

int main()
{
    const A obj = { 1, 42, "The Answer To LtUaE" };

    boost::fusion::for_each(obj, std::cout << arg1 << "\n");
}

输出:

1
42
The Answer To LtUaE

这篇关于在C ++中迭代结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:39