2012-09-02 53 views
0

在我的Python代碼,我開始之前,我翻譯到C++,我需要澄清一個問題:如何讓正確的字典/我可以使用的,「如果VAR在_」在等效名單用於詞典/列表的C++等價的Python代碼?

隨心所欲。例如,需要翻譯:

CONFIRMATION = ('yes', 'yeah', 'yep', 'yesh', 'sure', 'yeppers', 'yup') 
DECLINATION = ('no', 'nope', 'too bad', 'nothing') 

varResponse = str(input('yes or no question')) 
if varResponse in CONFIRMATION: 
    doSomething() 
elif varResponse in DECLINATION: 
    doSomethingElse() 
else: 
    doAnotherThing() 

這是相當容易使用類似的任務陣列,像這樣做:

if (userDogName == name[0]) 
    execute something; 

,但我需要的是這樣的:

if (userDogName is one of a population of dog names in a dictionary) 
    execute something; 
+0

如果列表不是太大,可以對數組進行線性搜索。 – irrelephant

+0

我有一些相當大的名單,但我會考慮爲小的。我應該怎麼做大的? – Stumbleine75

+0

元素的順序是否重要,可以重複嗎? – juanchopanza

回答

2

您可以使用STL容器類set。它採用平衡二叉樹:

#include <iostream> 
#include <set> 
#include <string> 

int main(int argc, char* argv[]) 
{ 
    std::set<std::string> set; 
    std::set<std::string>::const_iterator iter; 

    set.insert("yes"); 
    set.insert("yeah"); 

    iter = set.find("yess"); 

    if (iter != set.end()) 
    { 
    std::cout << "Found:" << *iter; 
    } 
    else 
    { 
    std::cout << "Not found!"; 
    } 

    return 0; 
} 
+0

我喜歡這種方法,但有問題;如果我說25條款,我會怎麼做?當然,我不會做set.insert(「期限」)25次? – Stumbleine75

+0

在C++ 11中,您可以使用初始化程序列表。只要搜索'std :: initializer_list'來理解這個概念。在你的程序中,你只需寫下:'set as = {「a」,「A」...'。 – Tilo

+0

在較舊的版本中,您將使用'set'的構造函數來獲取兩個指針,並假定它們指向數組的開始和結尾,然後用於初始化您的集合。 – Tilo

0

這可以在任何標準模板庫容器使用std::find來解決。

std::vector<std::string> answers; 
std::string input; 
... 
if(std::find(answers.begin(), answers.end(), input) != answers.end()) { 
    /* input was found in answers */ 
} else { 
    /* input was not found in answers */ 
} 

對於較大的列表,它可能是更好您的名單存放在std::set對象,而不是作爲的Tilo建議。 std::find將工作相同。

1

C++ 11允許一個解決方案,這是非常類似的Python代碼:

#include <iostream> 
#include <set> 
#include <string> 

using namespace std; 

set<string> CONFIRMATION = {"yes", "yeah", "yep", "yesh", "sure", "yeppers", "yup"}; 
set<string> DECLINATION = {"no", "nope", "too bad", "nothing"}; 

int main() { 
    cout << "yes or no question"; 
    string varResponse; 
    getline(cin, varResponse); 
    if (CONFIRMATION.find(varResponse) != CONFIRMATION.end()) { 
    doSomething(); 
    } else if (DECLINATION.find(varResponse) != DECLINATION.end()) { 
    doSomethingElse(); 
    } else { 
    doAnotherThing(); 
    } 
} 
+0

您是否試圖用visual C++編譯該文件? –

+0

@ Cheersandhth.-Alf:不,我只能訪問Clang。 –

1

好吧,C++是不適合於小脫開方案,因爲它不提供更多的基礎設施結構體。您打算在標準庫的頂部創建您自己的基礎結構(例如,甚至是簡單的集合!)。或者使用一些3 rd-方庫,即您的選擇。因此,儘管Python自帶電池,但使用C++沒有強大的壓力來接受所提供的特定電池(因爲沒有),但您至少必須選擇電池組。

對於剛剛基本碼,Python的代碼段

CONFIRMATIONS = ("yes", "yeah", "yep", "yesh", "sure", "yeppers", "yup") 
DECLINATIONS = ("no", "nope", "too bad", "nothing") 

response = raw_input("yes or no? ") 
if response in CONFIRMATIONS: 
    pass # doSomething() 
elif response in DECLINATIONS: 
    pass # doSomethingElse() 
else: 
    pass #doAnotherThing() 

可以像這樣在C++:

typedef Set<wstring> Strings; 

Strings const confirmations = temp(Strings()) 
    << L"yes" << L"yeah" << L"yep" << L"yesh" << L"sure" << L"yeppers" << L"yup"; 
Strings const declinations = temp(Strings()) 
    << L"no" << L"nope" << L"too bad" << L"nothing"; 

wstring const response = lineFromUser(L"yes or no? "); 
if(isIn(confirmations, response)) 
{ 
    // doSomething() 
} 
else if(isIn(declinations, response)) 
{ 
    // doSomethingElse() 
} 
else 
{ 
    // doAnotherThing() 
} 

但隨後,它依賴於某些基礎結構已經被定義,如Set類:

template< class TpElem > 
class Set 
{ 
public: 
    typedef TpElem  Elem; 

private: 
    set<Elem> elems_; 

public: 
    Set& add(Elem const& e) 
    { 
     elems_.insert(e); 
     return *this; 
    } 

    friend Set& operator<<(Set& s, Elem const& e) 
    { 
     return s.add(e); 
    } 

    bool contains(Elem const& e) const 
    { 
     return (elems_.find(e) != elems_.end()); 
    } 
}; 

template< class Elem > 
bool isIn(Set<Elem> const& s, Elem const& e) 
{ 
    return s.contains(e); 
} 

我用了一個operator<<因爲仍2012年的Visual C++不支持C++ 11花括號列表初始化。

這裏setstd::set從標準庫。

而且,HM的temp啄:

template< class T > 
T& temp(T&& o) { return o; } 

而且,更多的基礎結構,該lineFromUser功能:

wstring lineFromUser(wstring const& prompt) 
{ 
    wcout << prompt; 

    wstring result; 
    getline(wcin, result) 
     || throwX("lineFromUser: std::getline failed"); 
    return result; 
} 

其中,依靠throwX功能:

bool throwX(string const& s) { throw runtime_error(s); } 

但這是關於所有,除了你必須把C++代碼我發現,先放入一些功能,比如說,稱之爲cppMain,並調用從您的main功能(甚至更多基礎結構來定義!):

int main() 
{ 
    try 
    { 
     cppMain(); 
     return EXIT_SUCCESS; 
    } 
    catch(exception const& x) 
    { 
     wcerr << "!" << x.what() << endl; 
    } 
    return EXIT_FAILURE; 
} 

所以,做事甚至半在C++中正確的方式,有一些陡峭的開銷。

C++主要針對較大的程序和Python(我經常使用它)的小程序。

是的,我知道有些學生可能會或者會對這個聲明做出反應,要麼他們覺得這對C++來說是誹謗,說它對小程序沒有好處(嘿,我一直在做這些! /或者對Python來說,這對大型系統來說並不合適(嘿,你沒有聽說過YouTube,你是一個愚蠢的無能的人嗎?),但是,事情就是這樣。有時使用一個固定螺絲的錘子會更方便,所以有時候我會用C++來完成一些小任務。但一般來說,這是因爲在手邊的機器上安裝Python會比較麻煩,並且一般來說,要執行任務X,最好使用專爲X-like工作而設計的工具。