练习:
3.14:编写一段程序,用cin读入一组整数并把它们存入一个vector对象。
【解答】:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vInt; // 元素类型为int的vector对象
int i; // 记录用户的输入值
char cont = 'y'; // 与用户交互,决定是否继续输入
while (cin >> i)
{
vInt.push_back(i); // 向vector对象中添加元素
cout << "您要继续(y or n)? " << endl;
cin >> cont;
if (cont != 'y' && cont != 'Y')
break;
}
for (auto mem : vInt) // 使用范围for循环语句遍历vInt中的每个元素
cout << mem << " ";
cout << endl;
return 0;
}
3.15:改写上题的程序,不过这次读入的是字符串。
【解答】:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> vString; // 元素类型为string的vector对象
string s; // 记录用户的输入值
char cont = 'y'; // 与用户交互,决定是否继续输入
while (cin >> s)
{
vString.push_back(s); // 向vector对象中添加元素
cout << "您要继续吗(y or n)? " << endl;
cin >> cont;
if (cont != 'y' && cont != 'Y')
break;
}
for (auto mem : vString) // 使用范围for循环语句遍历vString中的每个元素
cout << mem << " ";
cout << endl;
return 0;
}