C++ 向量多个值
c++ vector multiple values
我是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].title
或questions[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 稍后阅读它。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么