2012-08-29 51 views
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正是我所期待的。

+2

你能提供一些關於如何使用這個名字的僞代碼嗎?作爲對象ID,或作爲調試手段,或... – xtofl

+0

['std :: map'](http://en.cppreference.com/w/cpp/container/map)? –

+0

你的意思是你想要命名這些結構的實例(對象)嗎? –

回答

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::mapstd::unordered_map

struct Bar{}; 
std::map<std::string, Bar> m; 
Bar b1, b2; 
m["Bob"] = b1; 
m["Mary"] = b2; 
+0

std :: cout << f2.name()... - 爲什麼括號? – neagoegab

+0

@neagoegab錯字,現在修復,謝謝。 – juanchopanza

1

如果你可以用一個結構來完成它,你可以用一個類來完成。我假設'名字結構'是指通過鍵存儲他們?您可以使用map來達到此目的。如果你打算使用類(我建議)來做,你可以使用map<string, BaseDataClass*>,併爲不同的變量組派生BaseDataClass

+1

這會導致切片,你需要一個指向基類的指針或智能指針的映射。 – juanchopanza

+0

@juanchopanza謝謝你指出,你是絕對正確的。編輯帖子反映了這一點。 – pauluss86

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"]; } 
相關問題