C++ 向量多个值

c++ vector multiple values

本文关键字:向量 C++      更新时间:2023-10-16

我是c++的新手,但有半年的Java se/ee7工作经验。

我想知道如何将 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. Porchen2. Ford n3. Toyota");
right_answer.push_back("2");
questions.push_back("Who is the manufacturer of Corvette?");
answers.push_back("1. Porchen2. 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]的东西。

你可以有一个struct,并将它的对象存储在vector中:

struct question
{
    std::string title;
    std::string choices;
    std::string answer;
};
// ...
question q = {"This is a question", "Choice anChoice b", "Choice a"};
std::vector<question> questions;
questions.push_back(q);

然后你会使用questions[0].titlequestions[0].answer等。

为什么没有这样的结构:

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) ...
}

你可以在现代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::tie 稍后阅读它。