题目要求
1.编写一个交互式程序,它接受用户输入的整数并将其存储到vector中。用户应能够随时使用索引查询vector中存储的值。
2.对练习1中的程序进行扩展,使其能够告诉用户他查询的值是否在vector中。
3.Jack在eBay销售广口瓶。为了帮助他打包和发货,请编写一个程序,让他能够输入每件商品的尺寸,将其存储在vector中再显示到屏幕上。
4.编写一个应用程序,将一个队列初始化为包含以下3个字符串:Hello、Containers are cool!和C++ is evolving!,并使用适用于各种队列的泛型函数来显示这些元素。另外,在这个应用程序中,使用C++11引入的列表初始化和C++14引入的operator “”s。
代码示例
// vector和deque动态数组小练习.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// 题目:
//1.编写一个交互式程序,它接受用户输入的整数并将其存储到vector中。用户应能够随时使用索引查询vector中存储的值。
//2.对练习1中的程序进行扩展,使其能够告诉用户他查询的值是否在vector中。
//3.Jack在eBay销售广口瓶。为了帮助他打包和发货,请编写一个程序,让他能够输入每件商品的尺寸,将其存储在vector中再显示到屏幕上。
//4.编写一个应用程序,将一个队列初始化为包含以下3个字符串:Hello、Containers are cool!和C++ is evolving!,并使用适用于各种队列的泛型函数来显示这些元素。另外,在这个应用程序中,使用C++11引入的列表初始化和C++14引入的operator “”s。
#include <iostream>
#include <string>
#include <vector>
#include <deque>
using namespace std;
void Question1_2()
{
int Index = 0, Mode = 0;
vector<int> SQL;
int InputNumber = 0;
int FindValue = 0;
vector<int>::iterator itor = SQL.begin();
while (true)
{
itor = SQL.begin();
InputNumber = 0;
ReinputMode:cout << "Mode = ";
cin >> Mode;
if (Mode != 0 && Mode != 1 && Mode != 2 && Mode != 3 && Mode != 4)
{
goto ReinputMode;
}
ReinputIndex:cout << "Index = ";
cin >> Index;
if (Index > SQL.size())
{
cout << "您输入的索引值错误,请重试!" << endl;
goto ReinputIndex;
}
if (Mode == 0)
{
cout << "请输入将要录入的数据:";
cin >> InputNumber;
SQL.insert(itor + Index, InputNumber);
cout << "数据录入成功!" << endl;
}
else if (Mode == 1)
{
cout << "开始读出数据!" << endl;
cout << "当前索引数据为" << SQL.at(Index) << endl;
}
else if (Mode == 2)
{
cout << "正在删除当前错误数据" << endl;
SQL.erase(itor + Index);
}
else if (Mode == 3)
{
cout << "数据查询中!请输入您要索引的对象:" << endl;
cin >> FindValue;
itor = find(SQL.begin(), SQL.end(), FindValue);
if (itor == SQL.end())
{
cout << "您要索引的元素无法找到,请重试!" << endl;
}
else
{
cout << "元素在数组中的索引值为" << distance(SQL.begin(), itor) << endl;
}
}
else if (Mode == 4)
{
cout << "数据库操作结束!" << endl;
break;
}
}
}
void Question3()
{
deque<string> CupSize;
string InputSize;
int Mode;
deque<string>::const_iterator citor = CupSize.begin();
while (true)
{
ReInputSize: cout << "Mode = ";
cin >> Mode;
citor = CupSize.begin();
if (Mode == 1)
{
cout << "InputSize = " << endl;
cin >> InputSize;
CupSize.push_back(InputSize);
cout << "录入数据成功!" << endl;
}
else if (Mode == 2)
{
cout << "显示录入所有尺寸:" << endl;
for (; citor != CupSize.end(); citor++)
{
cout << *citor << " ";
}
cout << endl;
}
else if(Mode == 3)
{
cout << "结束录入信息!" << endl;
break;
}
else
{
cout << "输入无效值,请重新输入Mode!" << endl;
goto ReInputSize;
}
}
}
template<typename T>
void Question4(deque<T> var)
{
for (auto itor = var.cbegin(); itor != var.cend(); itor++)
{
cout << *itor << endl;
}
}
int main()
{
cout << "Question1&Question2" << endl;
Question1_2();
cout << "Question3" << endl;
Question3();
cout << "Question4" << endl;
deque<string> var{ "Hello"s,"Containers are cool!"s,"C++ is evolving!"s };
Question4(var);
// ""s时C++11中新加的语法,当字符串中有" "空格时,系统会把他认为'\0',从而截断字符串,如果用这个语法就不会了
}