0

I'm writing a program that will pull a variable amount of data from a server. There are three different structs I will be using to hold three different sets of variables (though I'd like to know if this can be done with a class as well). Because different servers will have varying amounts of sets of data, I'd like to be able to name structs with strings or be able to do something similar.

Is there any way to go about this, or any good practice to do something similar? Thanks in advance.

Quick example:

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];

I'm hoping to name structs arbitrarily. map looks similar to what I'm looking for, so I'm reading into that a bit right now.

Thanks for the help and quick response, map was exactly what I was looking for.

3 Answers3

1

If you want a struct with a name:

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

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

If all you want is a struct that can be stored in a collection and looked up according to a name, then you can use std::map or std::unordered_map:

struct Bar{};
std::map<std::string, Bar> m;
Bar b1, b2;
m["Bob"] = b1;
m["Mary"] = b2;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

If you can do it with a struct, you can do it with a class. I assume 'name structs' refers to storing them by key? You can use a map for this purpose. If you're going to do it with classes (which I recommend) you'd could use a map<string, BaseDataClass*> and derive BaseDataClass for the different sets of variables.

pauluss86
  • 454
  • 6
  • 9
0

Because different servers will have varying amounts of sets of data, I'd like to be able to name structs with strings or be able to do something similar.

You don't need to "name structs with strings", you just need to place the retrieved data into a key-value store of some kind.

#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"]; }
nurettin
  • 11,090
  • 5
  • 65
  • 85