0

我正在编写一个程序,该程序将从服务器中提取可变数量的数据。我将使用三种不同的结构来保存三组不同的变量(尽管我想知道这是否也可以用一个类来完成)。因为不同的服务器会有不同数量的数据集,所以我希望能够用字符串命名结构或能够做类似的事情。

有什么办法可以解决这个问题,或者有什么好的做法可以做类似的事情吗?提前致谢。

快速示例:

struct foo {
    std::string name;
    std::string ipAddress;
    std::string macAddress;
};

struct bar {
    std::string dhcpServer;
    std::string tftpServer;
};

foo [string_as_name_one];  
bar [string_as_name_two];

我希望任意命名结构。map看起来与我正在寻找的相似,所以我现在正在阅读它。

感谢您的帮助和快速响应,map这正是我想要的。

4

3 回答 3

1

如果你想要一个有名字的结构:

struct Foo {
  std::string name;
  Foo(const std::string& name) : name(name) {}
};

Foo f1("Bob");
Foo f2("Mary");
std::cout << f2.name << "\n";

如果您想要的只是一个可以存储在集合中并根据名称查找的结构,那么您可以使用std::mapor std::unordered_map

struct Bar{};
std::map<std::string, Bar> m;
Bar b1, b2;
m["Bob"] = b1;
m["Mary"] = b2;
于 2012-08-29T06:04:41.913 回答
1

如果你可以用一个结构来做,你可以用一个类来做。我假设“名称结构”是指按键存储它们?map为此,您可以使用 a 。如果你打算用类(我推荐)来做这件事,你可以使用 a并为不同的变量集map<string, BaseDataClass*>派生。BaseDataClass

于 2012-08-29T06:05:28.287 回答
0

因为不同的服务器会有不同数量的数据集,所以我希望能够用字符串命名结构或能够做类似的事情。

您不需要“用字符串命名结构”,只需将检索到的数据放入某种键值存储中。

#include <map>
#include <string>

typedef std::map<std::string, std::string> server_result;
struct server
{
   server(std::string uri): uri(uri) {}
   server_result get(){ server_result result; /* retrieve results, put them in result[name]= value; */ return result; }

   private:
   std::string uri;
};

// or

class server
{
   std::string uri;

   public:
   server(std::string uri): uri(uri) {}
   server_result get(){ server_result result; /* retrieve results, put them in result[key]= value; */ return result; }
};

// use it like

#include <iostream>
#include <ostream>
int main(){ server_result result= server("42.42.42.42").get(); std::cout<< result["omg"]; }
于 2012-08-29T06:13:07.503 回答