结构成员名称 - 搜索

时间:2010-10-21 10:00:46

标签: c++ structure

在上一个问题中,我在那里弄得一团糟。所以我想给它一个新的尝试。


struct emp
{
    int salary;
    string empid;
};
struct payroll
{
    int empid;
    int deductions;
};
    emp a1,a2, a3;  

    a1.salary = 9000;
    a1.empid = 1;

    a2.salary = 1000;
    a2.empid = 2;

    a3.salary = 9000;
    a3.empid = 3;

    payroll p1,p1,p3;   

    p1.empid = 1;
    p1.deductions = 10;

    p12.empid = 2;
    p2.deductions = 20;

    p3.empid = 3;
    p3.deductions = 30;

now, from the command prompt i have given like this

empid = 1;

然后我需要答案a1和p1。 在这里,我需要检查结构是否具有成员名称:empid - 如果为true - 然后检查empid = 1。
如何以通用方式执行此操作。我的意思是,如果我有30个像这样的结构怎么办。给我任何想法,如果这是不可能的,那么如何使用任何其他数据结构。

3 个答案:

答案 0 :(得分:2)

没有可移植的方法来动态检查结构的成员变量名称。如果您不想检查成员变量名称,请使用std::vector来存储结构实例。使用std::find_if搜索满足谓词的特定实例。有关find_if的使用示例,请参阅this link。如果您确实想要检查empid中是否存在名为struct的字段,请改用std::map

typedef std::map<std::string, int> emp;
typedef std::map<std::string, int> payroll;
typedef std::vector<emp> emp_list;
typedef std::vector<payroll> payroll_list;

emp_list emps;
emp a1;
a1["empid"] = 1;
a1["salary"] = 9000;
emps.push_back(a1);
// ...

payroll_list pays;
payroll p1;
p1["empid"] = 1;
p1["deductions"] = 10;
pays.push_back(p1);
// ...

// use an iterator over emps and pays to check for specific items
emp_list::const_iterator eit = emps.begin ();
emp_list::const_iterator eend = emps.end ();
while (eit != eend)
  {
    emp e = *eit;
    int eid = e["empid"];
    if (eid == empid)
      {
        std::cout << e["salary"] << '\n';
      }
    eit++;
  }
// ...

答案 1 :(得分:0)

  1. 您应该在所有empid中使用struct的一致数据类型。
  2. 作为@Vijay Mathew suggests,使用vector然后搜索。或者,您可以使用mapempid作为密钥,这样可以为大量条目提供更好的性能。

答案 2 :(得分:0)

如果我理解你的问题,如果你的“数据库”中有30个结构(表),你想找到所有具有“empid”列的结构(即结构成员)?在C ++中,我不知道有一种机制来测试结构是否按名称具有特定成员,至少不是运行时提供的名称。您需要将其存储在某种形式的“元数据”中 - 例如用字符串键映射,例如列出一组结构(或用字符串比较等逻辑编码)......

这是一个粗略的草图......

在行类型(即结构)

上键入“table”类
class table
{
  // some virtual methods common to all classes..
};

template <typename _Row>
class data_table : public table
{
  // methods

  // real data
  std::vector<_Row> data;
};

然后你需要一个数据库类来保存所有表..

class database
{
  // methods
  std::map<int, boost::shared_ptr<table> > tables; // here int is for a unique id for table
};

现在您有一组表,其中每个表都是一组行(结构)。然后,您需要为数据库定义一些元数据,即将列映射到表等。

std::multimap<std::string, boost::shared_ptr<table> > columns;

您必须使用您对结构的了解来填充,例如,此地图可能包含上述代码:

columns["empid"] = id of table<emp>;
columns["empid"] = id of table<payroll>;

现在,您可以将“查询”传递给“数据库”类,在其中您说“empid”= 1,然后在列映射中查找并查找表的所有实例,然后查找每个表您可以使用“empid”查询= 1.关于如何将“empid”映射到结构empid中的真实emp字段,您必须将该逻辑嵌入{{1}中的方法中} emp可以委托给的结构(或者如果你能想到一种存储对成员的引用的聪明方法......)

这只是一个建议......

或者,考虑使用其中一个支持真实查询的数据库,并以独立或嵌入方式运行!

编辑:

table<emp>

所以“元数据”在测试逻辑中编码,你传入一个字符串字段名称,然后根据它是什么,你比较适当的值...这不是很有效,但它的工作原理......