2011-11-11 19 views
0

以下java方法將hashtable的鍵作爲枚舉返回。enum作爲C++函數的返回類型

Hashtable<String, Object> props = new Hastable<String, Object>(); 

// some code here 

public final Enumeration getPropertyURIs() { 
    return props.keys(); 
} 

我想將這段代碼翻譯成C++。

更具體地說,我該如何在C++中實現相同的函數,該函數返回std :: map的鍵枚舉?

+3

我不知道Java,但我懷疑C++中的枚舉與Java中的枚舉關係甚微。 C++中的'enum'只是列出一些常量的簡便方法,給每個常量賦予一個唯一值。 –

+0

「鍵的枚舉」是什麼意思?在C++中,地圖的關鍵字具有固定類型,您只能說出該類型。 (關鍵類型*當然可以是枚舉。) –

+2

可能是[this]的重複(http://stackoverflow.com/questions/110157/how-to-retrieve-all-keys-or-values-from -a-stdmap) – moooeeeep

回答

0

C++中的enum只是一組常量。

你的意思是這樣嗎?

typedef std::unordered_map<std::string, boost::any> props_t; 
props_t props; 

std::vector<std::string> getPropertyURIs() 
{ 
    std::vector<std::string> keys; 
    for (props_t::const_iterator i = props.begin(); i != props.end(); ++i) 
    { 
     keys.push_back(i->first); 
    } 
    return keys; 
} 
+2

我更喜歡它,如果'getPropertyURIs'會採用一個輸出迭代器(其類型是一個模板參數'作爲輸入,並在那裏寫密鑰,而不是返回一個' vector'。 –

+1

這可能是OP認爲他需要的東西,但這種東西在C++中可能只是不必要的。如果你需要這些鍵,直接迭代地圖... –

+0

或者調用'for_each()'與['select1st <>'](http://www.sgi.com/tech/stl/select1st.html)的變體。 –

2

你可以得到的最接近的東西就是返回一個迭代器。問題是你實際上需要兩個迭代器來指定一個範圍。要解決這個問題的方法之一是使用輸出迭代器:

template<class output_iterator_type> 
void getPropertyURIs(output_iterator_type out) { 
    // loop copied from @dalle 
    for (props_t::const_iterator i = keys.begin(); i != keys.end(); ++i) 
    { 
     *out = i->first; 
     ++out; 
    } 
} 

如果你現在想所有的鑰匙存放在vector,你可以做這樣的:

std::vector<std::string> keys; 
getPropertyURIs(std::back_inserter(keys)); 
+0

@dalle:感謝您修復我的代碼:) –

+0

+1:比我的回答更好,更合適。 – dalle

+0

感謝您的回答 –