动态数组 » 更多示例
既然我们已经了解了如何创建和使用动态数组,那么让我们看一些更多的示例。
循环
要充分利用数组的功能,你需要学习循环。我们将在学习完数组后立即学习它们。在此之前,在下面的示例中,我们将只使用我们已经向你展示过的最基本的 for
循环。
示例 1:
操作学生成绩列表
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> student_names(3);
std::vector<int> student_grades(3);
// Ask user to enter student names and grades
std::cout << "Enter the first student's name: ";
std::cin >> student_names[0];
std::cout << "Enter the first student's grade: ";
std::cin >> student_grades[0];
std::cout << "Enter the second student's name: ";
std::cin >> student_names[1];
std::cout << "Enter the second student's grade: ";
std::cin >> student_grades[1];
std::cout << "Enter the third student's name: ";
std::cin >> student_names[2];
std::cout << "Enter the third student's grade: ";
std::cin >> student_grades[2];
// Print out the list of students and their grades
std::cout << "Student list:" << std::endl;
}