2013-10-03 72 views
-2

我是新來的C++,但有半年的Java se/ee7工作經驗。C++矢量多值

我想知道如何把3個值到vector<string> 例如:vector<string, string, string>或只是vector<string, string> 避免3個載體的使用。

vector<string> questions; 
vector<string> answers; 
vector<string> right_answer; 

questions.push_back("Who is the manufacturer of Mustang?"); 
answers.push_back("1. Porche\n2. Ford \n3. Toyota"); 
right_answer.push_back("2"); 

questions.push_back("Who is the manufacturer of Corvette?"); 
answers.push_back("1. Porche\n2. Ford \n3. Toyota \n4. Chevrolette"); 
right_answer.push_back("4"); 


for (int i = 0; i < questions.size(); i++) { 
    println(questions[i]); 
    println(answers[i]); 

    if (readInput() == right_answer[i]) { 
     println("Good Answer."); 
    } else { 
     println("You lost. Do you want to retry? y/n"); 
     if(readInput() == "n"){ 
      break; 
     }else{ 
      i--; 
     } 
    } 
} 

如果可能,我想使用類似questions[i][0] questions[i][1] questions[i][3]的東西。

+4

C++與Java非常不一樣。不要陷入思考的陷阱中,事情是相似的。 –

回答

4

爲什麼沒有像結構:

struct question_data { 
    std::string question; 
    std::string answers; // this should probably be a vector<string> 
    std::string correct_answer; 
}; 

然後:

std::vector<question_data> questions; 
... 
for (int i = 0; i < questions.size(); i++) { // I would personally use iterator 
    println(questions[i].question); 
    println(questions[i].answers); 

    if (readInput() == questions[i].correct_answer) ... 
} 
+0

Thankyou,我今天開始用C++,我從來沒有聽說過struct,所以我會用這個 –

+0

好運與你的C++努力。它很複雜,但奇怪的是獎勵:)'struct'就像'class',不同之處在於默認情況下成員是'public',所以在這個例子中少寫一行:)。隨意使用類,而不是結構 –

+0

你明白我的權利,它完美的作品。再次感謝你。 –

8

你可以擁有它的struct和存儲對象在vector

struct question 
{ 
    std::string title; 
    std::string choices; 
    std::string answer; 
}; 

// ... 

question q = {"This is a question", "Choice a\nChoice b", "Choice a"}; 
std::vector<question> questions; 
questions.push_back(q); 

然後你可以使用questions[0].titlequestions[0].answer

+0

+1有更好的命名,那麼我的例子:) –

+0

謝謝你,似乎作爲第二個答案,效果很好。謝謝 –

0

你可以做你想在現代C++中做的事情。

您可以使用像一個元組:

std::vector<std::tuple<std::string, std::string>> vec; 
std::tuple<std::string, std::string> some_tuple; 
some_tuple = std::make_tuple("some", "strings"); 
vec.push_back(some_tuple); 

您可以使用std ::領帶日後讀取。