C++练习(持续更新)
教材:c++语言程序设计第四版
[教材习题4_13:定义Circle类并计算面积]
【问题描述】
定义一个Circle类,有数据成员radius(半径),成员函数getArea()计算圆的面积。构造一个Circle的对象进行测试(注:圆周率取值3.14)。
#include<iostream>
using namespace std;
const float PI = 3.14;
class Circle{
public:
Circle(float r);
void area();
private:
float radius;
};
Circle::Circle(float r) {
radius = r;
}
void Circle::area() {
cout <<"Area:"<< PI * radius * radius << endl;
}
int main() {
float radius;
cout << "Input Radius:";
cin >> radius;
Circle a(radius);
a.area();
}
[教材习题4_8:定义Dog类,包含age和weight信息]
【问题描述】
定义一个Dog类,包含age,weight等属性,以及对这些属性操作的方法。实现并测试这个类。
【输入形式】
程序参考的输入(提示“Input Age and Weight:”):
Input Age and Weight:3 20
#include<iostream>
using namespace std;
class Dog {
public:
Dog(int nage, int nweight);
void print();
private:
int age, weight;
};
Dog::Dog(int nage, int nweight) {
age = nage;
weight = nweight;
}
void Dog::print() {
cout << "Dog Age:" << age <<" "<<"years" << endl;
cout << "Dog Weight:" << weight << "kg" << endl;
}
int main() {
int age, weight;
cout << "Input Age and Weight:";
cin >> age >> weight;
Dog a(age, weight);
a.print();
return 0;
}
[教材习题4_9:通过屏幕两点确定矩形类Rectangle]
【问题描述】设计并测试一个名为Rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,根据坐标能计算矩形的面积。
【输入形式】程序参考的输入(提示“Input Point A:”输入左下角的坐标;提示“Input Point B:”输入左下角的坐标):
Input Point A:0 0
Input Point B:8.2 4.5
#include <iostream>
using namespace std;
class Rectangle {
public:
void getPoint();
float getArea();
private:
double x1;
double x2;
double y1;
double y2;
double Area;
};
void Rectangle::getPoint() {
cout << "Input Point A:";
cin >> x1 >> y1;
cout << "Input Point B:";
cin >> x2 >> y2;
}
float Rectangle::getArea() {
Area = (x1 - x2) * (y1 - y2);
if (Area < 0) {
Area = -Area;
}
return Area;
}
int main()
{
Rectangle a;
a.getPoint();
float area = a.getArea();
cout << "Rectangle Area:" << area << endl;
return 0;
}
[ 教材习题4_20:定义满足要求的复数类Complex类]]
[教材习题4_20:定义满足要求的复数类Complex类]
【问题描述】
定义一个复数类Complex,使得下面的代码能够工作。(注:下列代码需放在主函数中。)
Complex c1(3,5); //用复数3+5i初始化c1
Complex c2=4.5; //用实数4.5初始化c2
c1.add(c2); //将c1与c2相加,结果保存在c1中
c1.show(); //将c1输出(这时的结果应该是7.5+5i)
#include<iostream>
using namespace std;
class Complex {
public:
Complex(float nsshu = 0, float nxshu = 0) {
sshu = nsshu;
xshu = nxshu;
}
void add(Complex c1) { sshu += c1.sshu; xshu += c1.xshu; };
void show();
private:
float sshu, xshu;
};
void Complex::show() {
cout << sshu << "+" << xshu << "i" << endl;
}
int main() {
Complex c1(3, 5); //用复数3+5i初始化c1
Complex c2 = 4.5; //用实数4.5初始化c2
c1.add(c2); //将c1与c2相加,结果保存在c1中
c1.show(); //将c1输出(这时的结果应该是7.5+5i)
return 0;
}
[实验题2.2定义Employee类,输出编号和姓名]
【问题描述】
定义一个Employee类,在Employee类中增加一个数据(静态数据成员)来设置本公司员工编号基数,新增加的员工编号将在创建对象的同时自动在基数上增加(程序输入2个人员)。
【输入形式】
参考的输入如下(提示“Input name:”):
Input name:zhangsan
Input name:lisi
#include <iostream>
#include <string>
using namespace std;
class Employee
{
public:
Employee();
void display();
private:
static int base_id;
int id;
string name;
};
int Employee::base_id = 1000;
Employee::Employee() {
cout << "Input name:";
cin >> name;
id = ++base_id;
}
void Employee::display() {
cout << "ID:" << id << " " << "Name:" << name << endl;
}
int main()
{
Employee e1;
Employee e2;
e1.display();
e2.display();
return 0;
}
[实验题2.1利用对象数组,计算10个顶点组成折线的长度]
【问题描述】
假设有一个点类point,具有两个实数坐标。希望主程序使用这个类完成下述功能:
(l)主程序为类point定义10个点的对象数组(也可以动态申请空间)。
(2)要求调用一个函数Set()从键盘输入10个对象的属性。
(3)要求调用一个函数Display()显示10个对象的值。
(4)要求调用一个函数Lenth(),计算将这些点连成一条折线时,这条折线的长度。
#include<iostream>
#include <stdlib.h>
#include"math.h"
using namespace std;
class Point {
public:
void Set();
void Display();
void Length(Point a[]);
private:
int x, y;
};
void Point::Set() {
cout << "Input x,y:";
cin >> x >> y;
}
void Point::Display() {
cout << "(" << x << "," << y << ")" << endl;;
}
void Point::Length(Point a[]) {
double length = 0;
for (int i = 0; i < 9; i++) {
length += sqrt(abs(a[i + 1].x - a[i].x) * abs(a[i + 1].x - a[i].x) + abs(a[i + 1].y - a[i].y) * abs(a[i + 1].y - a[i].y));
}
cout<<"Length:" << length;
}
int main() {
Point a[10];
for (int i = 0; i < 10; i++) {
a[i].Set();
}
for (int i = 0; i < 10; i++) {
a[i].Display();
}
a->Length(a); //a[10].Length(a);
[教材习题5_7:利用静态变量统计小猫Cat的数量]
定义一个Cat类,拥有静态数据成员numOfCats,记录Cat的个体数目;静态成员函数getNumOfCats(),读取numOfCats。设计程序测试这个类,体会静态数据成员和静态成员函数的用法。
主函数如下:
int main()
{
Cat c;
cout<<“Num:”<<Cat::getNumOfCats()<<endl;
Cat carr[4];
cout<<“Num:”<<Cat::getNumOfCats()<<endl;
return 0;
}
#include <iostream>
using namespace std;
class Cat {
public:
Cat() {
numOfCats++;
}
~Cat() { numOfCats--; }
static int getNumOfCats() {
return numOfCats;
}
private:
static int numOfCats;
};
int Cat::numOfCats = 0;
int main()
{
Cat c;
cout << "Num:" << Cat::getNumOfCats() << endl;
Cat carr[4];
cout << "Num:" << Cat::getNumOfCats() << endl;
return 0;
}
[教材习题5_13:定义类X,Y,Z,按要求实现友元]
【问题描述】
定义类X,Y,Z,函数h(X*),满足:类X有私有成员i,Y的成员函数g(X*)是X的友元函数,实现对X的成员i加1;类Z是类X的友元类,其成员函数f(X*)实现对X的成员i加5;函数h(X*)是X的友元函数,实现对X的成员i加10。主函数实现测试。主函数需要定义如下:
int main()
{
int a;
cin>>a;
X x(a);
Y y;
Z z;
y.g(x);
z.f(x);
h(x);
x.print();
}
#include <iostream>
using namespace std;
class X;
class Y
{
public:
void g(X & x);
};
class Z
{
public:
void f(X & x);
};
class X
{
public:
X(int i) :i(i) {}
friend void Y::g(X & x);
friend class Z;
friend void h(X & x);
void print()
{
cout << i;
}
private:
int i;
};
void Y::g(X & x) {
x.i += 1;
}
void Z::f(X& x) {
x.i += 5;
}
void h(X& x) {
x.i += 10;
}
int main()
{
int a;
cin >> a;
X x(a);
Y y;
Z z;
y.g(x);
z.f(x);
h(x);
x.print();
}
[教材习题5_14:定义Boat与Car两个类,友元计算总重量]
【问题描述】
定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight(),计算二者的重量和。
【输入形式】
参考的输入(数字前为提示文字):
Input boat weight:3
Input car weight:5
#include <iostream>
using namespace std;
class Car;
class Boat {
public:
Boat(int weight) {
weightB = weight;
}
friend int getTotalWeight( Car & a,Boat & b);
private:
int weightB;
};
class Car {
public:
Car(int weight) {
weightC = weight;
}
friend int getTotalWeight( Car & a, Boat & b);
private:
int weightC;
};
int getTotalWeight(Car & a,Boat & b) {
return static_cast<int>(a.weightC + b.weightB);
}
int main() {
int a,b;
cout << "Input boat weight:";
cin >> a;
Boat test1(a);
cout << "Input car weight:";
cin >> b;
Car test2(b);
cout<<getTotalWeight(test2, test1)<<endl;
return 0;
}
教材习题6_20:实现一个简单圆类
【问题描述】
实现一个名为SimpleCircle的简单圆类。其数据成员int *itsRadius为一个指向其半径值的指针,存放其半径值。设计对数据成员的各种操作并计算面积,给出这个类的完整实现并测试这个类。
注:简单计算半径为10的圆面积,不需要输入,圆周率取3.14。
参考的输出如下:
Area:314
#include <iostream>
using namespace std;
const float pi = 3.14;
class SimpleCircle
{
public:
SimpleCircle() {
itsRadius=new float();
//也可以这样分配内存:itsRadius=(float*)malloc(sizeof(float));
//但是要加上头文件:include<stdio.h>
}
void setRadius(float r)
{
*itsRadius = r;
}
float getRadius()
{
return *itsRadius;
}
float getArea()
{
return (*itsRadius) * (*itsRadius) * pi;
}
private:
float* itsRadius;
};
int main()
{
SimpleCircle c;
c.setRadius(10);
cout << "Area:" << c.getArea() << endl;
}
教材习题7_5:Shape类派生Rectangle和Circle类
问题描述】
定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象面积。使用Rectangle类创建一个派生类Square。
注:圆周率取3.14
【输入形式】
参考的输入(数字前面的文字为提示):
Input a,b:5 10
Input r:10
【输出形式】
参考的输出:
Rectangle Area:50,Circle Area:314
#include<iostream>
using namespace std;
#define PI 3.14
class Shape {
public:
float getArea() {};
private:
};
class Rectangle:public Shape {
public:
Rectangle(float nwidth, float nlength) {
width = nwidth;
length = nlength;
}
float getArea() {
return width * length;
}
private:
float width, length;
};
class Circle:public Shape {
public:
Circle(float nr) {
r = nr;
}
float getArea() {
return PI * r * r;
}
private:
float r;
};
int main() {
float a, b,r;
cout << "Input a,b:";
cin >> a >> b;
cout << "Input r:";
cin >> r;
Rectangle* p1 = new Rectangle(a, b);
Circle* p2 = new Circle(r);
cout <<"Rectangle Area:" << p1->getArea() << ",Circle Area:" << p2->getArea();
return 0;
}
教材习题7_6:哺乳动物类Mammal派生出狗类Dog
【问题描述】
定义一个哺乳动物类Mammal,再由此派生出狗类Dog,定义一个Dog类的对象,观察基类与派生类的构造函数和析构函数的调用顺序。
【输入形式】
参考的输入为("Input Dog Name:"为提示文字):
Input Dog Name:wangcai
#include <iostream>
#include <string>
using namespace std;
class Mammal
{
public:
Mammal(string name) :name(name)
{
cout << "Con.Mammal" << endl;
}
~Mammal()
{
cout << "Des.Mammal" << endl;
}
protected:
string name;
};
class Dog:public Mammal {
public:
Dog(string name) :Mammal(name) {
cout << "Con.Dog:" << name << endl;
}
~Dog(){
cout << "Des.Dog:" << name<<endl;
}
private:
};
int main()
{
string name;
cout << "Input Dog Name:";
cin >> name;
Dog d(name);
return 0;
}
实验题3.1计算出球、圆柱和圆锥的表面积和体积
【问题描述】
编写一个程序计算出球、圆柱和圆锥的表面积和体积。
要求:
(1)定义一个基类,至少含有一个数据成员半径,并设为保护成员;
(2)定义基类的派生类球、圆柱、圆锥,都含有求表面积和体积的成员函数和输出函数;
(3)编写主函数,求球、圆柱、圆锥的表面积和体积。
注:圆周率取3.14
#include<iostream>
#include<cmath>
using namespace std;
#define PI 3.14
class Base {
public:
float Area(){};
float Volume(){};
protected:
float r;
};
class Sphere:public Base {
public:
Sphere(float radius) {
r = radius;
}
float Area() {
return 4*PI*r*r;
}
float Volume() {
return (4.0/3.0) * PI * r * r * r;
}
protected:
float r;
};
class Cylinder:public Base {
public:
Cylinder(float radius,float height) {
r = radius;
h = height;
}
float Area() {
return (2*PI*r*r)+(2*PI*r*h);
}
float Volume() {
return PI*r*r*h;
}
protected:
float r;
float h;
};
class Cone :public Base {
public:
Cone(float radius,float height) {
r = radius;
h = height;
}
float Area() {
return (PI*r*r)+(sqrt(r*r+h*h)*PI*r);
}
float Volume() {
return (1.0/3.0)*PI*h*r*r;
}
protected:
float r;
float h;
};
int main() {
float radius1;
float radius2, height2;
float radius3, height3;
cout<< "Input the radius of the sphere:";
cin >> radius1;
cout << "Input the radius and height of the cylinder:";
cin >> radius2 >> height2;
cout << "Input the radius and height of the cone:";
cin >> radius3 >> height3;
Sphere* p1 = new Sphere(radius1);
cout << "The area of the sphere:"<<(p1->Area())<<endl;
cout << "The volume of the sphere:" << (p1->Volume()) << endl;
Cylinder* p2 = new Cylinder(radius2, height2);
cout << "The area of the cylinder:" << (p2->Area()) << endl;
cout << "The volume of the cylinder:" << (p2->Volume()) << endl;
Cone* p3 = new Cone(radius3, height3);
cout << "The area of the cone:"<< (p3->Area())<<endl;
cout << "The volume of the cone:" << (p3->Volume());
return 0;
}
实验题3.2编写一个学生和教师类
【问题描述】
编写一个学生和教师数据输入和显示程序。其中,学生数据有编号、姓名、班级和成绩,教师数据有编号、姓名、职称和部门。
要求:
(1)将编号、姓名输入和显示设计成一个类person;
(2)设计类person的派生类:学生类student和教师类teacher;
(3)主函数中分别定义一个学生对象和教师对象进行测试。
#include <iostream>
#include <string>
using namespace std;
class person
{
public:
person()
{
cout << "Input id:";
cin >> id;
cout << "Input name:";
cin >> name;
}
void display()
{
cout << "Id:" << id << endl;
cout << "Name:" << name << endl;
}
private:
string id;
string name;
};
class student :public person {
public:
student() :person() {
cout << "Input class:";
cin >> Class;
cout << "Input score:";
cin >> score;
};
void display()
{
cout << "Student's info:" << endl;
person::display();
cout << "Class:"<<Class<<endl;
cout << "Score:"<<score<<endl;
}
private:
string Class;
string score;
};
class teacher :public person {
public:
teacher() :person() {
cout << "Input title:";
cin >> title;
cout << "Input department:";
cin >> department;
};
void display()
{
cout << "Teacher's info:" << endl;
person::display();
cout << "Title:"<<title<<endl;
cout << "Department:"<<department<<endl;
}
private:
string title;
string department;
};
int main()
{
student stu;
teacher tea;
stu.display();
tea.display();
return 0;
}
教材习题7_8:定义一个Document类和Book类
【问题描述】
定义一个Document类,有数据成员name,从Document派生出Book类,增加数据成员pageCount。
【输入形式】
程序参考的输入(数据前面文字为提示):
Input Name and Page:Math 280
【输出形式】
程序参考的输出:
Name:Math
Page:280
#include<iostream>
#include<string>
using namespace std;
class Document {
public:
Document() {
cout << "Input Name and Page:";
}
void coutname() {
cout << "Name:" << name << endl;
}
protected: //此处用到保护成员为了在派生类中访问基类中的成员数据,不能用public
string name;
};
class Book :public Document {
public:
Book() :Document() {
cin >> name >> pageCout;
}
void coutpage() {
Document::coutname();
cout << "Page:" << pageCout;
}
protected:
int pageCout;
};
int main() {
Book p2;
p2.coutpage();
return 0;
}
教材习题7_10:定义一个Object类和Box类
问题描述】
定义一个Object类,有数据成员weight及相应的操作函数,由此派生出Box类,增加数据成员height和width及相应的操作函数,声明一个Box对象,观察构造函数和析构函数的调用顺序。
【输入输出形式】
参考的输入及输出(其中Input开头的两段文字为输入提示和输入数据,其他均为输出):
Constructing Object!
Constructing Box!
Input weight:50
Input height and width:20 30
Weight:50
Height and width:20,30
Destructing Box!
Destructing Object!
#include <iostream>
#include <string>
using namespace std;
class Object
{
public:
Object()
{
cout << "Constructing Object!" << endl;
}
~Object()
{
cout << "Destructing Object!" << endl;
}
void getInfo()
{
cout << "Input weight:";
cin >> weight;
}
void showInfo()
{
cout << "Weight:" << weight << endl;
}
private:
int weight;
};
class Box:public Object{
public:
Box()
{
cout << "Constructing Box!" << endl;
}
~Box()
{
cout << "Destructing Box!" << endl;
}
void getInfo() {
Object::getInfo();
cout << "Input height and width:";
cin >> height >> width;
}
void showInfo() {
Object::showInfo();
cout << "Height and width:" << height <<","<< width << endl;
}
private:
int height, width;
};
int main()
{
Box box;
box.getInfo();
box.showInfo();
return 0;
}
实验题4.2修改下面的4个类,添加析构函数
问题描述】
修改下面的4个类,添加析构函数,在析构函数中输出各私有数据成员的值。并分析结果。
修改后程序的输出结果为:
Constructing B2.2
Constructing B1.1
Constructing B3.3
Constructing A.4
1
2
4
Destructing A.4
Destructing B3.3
Destructing B1.1
Destructing B2.2
#include <iostream>
using namespace std;
class B1
{
public:
B1(int i)
{
b1 = i;
cout << "Constructing B1." << b1 << endl;
}
void print() { cout << b1 << endl; }
~B1() { cout << "Destructing B1." << b1 << endl; }
private:
int b1;
};
class B2
{
public:
B2(int i)
{
b2 = i;
cout << "Constructing B2." << b2 << endl;
}
void print() { cout << b2 << endl; }
~B2() { cout << "Destructing B2." << b2 << endl; }
private:
int b2;
};
class B3
{
public:
B3(int i)
{
b3 = i;
cout << "Constructing B3." << b3 << endl;
}
~B3() { cout << "Destructing B3." << b3 << endl; }
int getb3() { return b3; }
private:
int b3;
};
class A : public B2, public B1
{
public:
A(int i, int j, int k, int l) :B1(i), B2(j), bb(k)
{
a = l;
cout << "Constructing A." << a << endl;
}
~A() { cout << "Destructing A." << a << endl; }
void print()
{
B1::print();
B2::print();
cout << a << endl;
}
private:
int a;
B3 bb;
};
int main()
{
A aa(1, 2, 3, 4);
aa.print();
return 0;
}
实验题4.1定义一个员工类、经理类、销售员类和销售经理类
【问题描述】
定义一个员工类Employee,有数据成员姓名,编号。定义一个销售员继承自员工类Sales,工资为销售额的提成10%,定义一个经理类Manager,固定工资8000,定义一个销售经理类,继承自销售员类和经理类,工资为固定工资5000加销售额的提成5%。每个类均有display()函数输出信息,编写主函数测试。主函数中定义一个销售经理对象,销售额为100000,输出信息。
【输入形式】
程序参考的输入(第一行为提示文字):
Input id name and sale:
M001 zhangsan 100000
【输出形式】
程序参考的输出结果如下:
ID:M001
Name:zhangsan
Salary:10000
#include <iostream>
using namespace std;
class Employee
{
public:
Employee(string id, string name) :id(id), name(name)
{}
void display()
{
cout << "ID:" << id << endl;
cout << "Name:" << name << endl;
}
protected:
string id, name;
};
class Sales : public Employee {
public:
Sales(string id, string name, float sale) :Employee(id, name), sale(sale) { };
void display() {
float salary = Sales::sale * (1.0 / 10.0);
}
protected:
float sale;
};
class Manager {
public:
float salary = 8000;
void display() {
cout << salary;
}
};
class SalesManager :public Manager, public Sales {
public:
SalesManager(string id, string name, float sale) :Sales(id, name, sale) { };
//程序结果是正确的,但是这有一处警告,说sale未初始化,不明白为什么,后续再看看
float salary = 5000 + Sales::sale * (5.0 / 100.0);
void display() {
Employee::display();
cout << "Salary:" << salary << endl;
}
private:
string id, name;
float sale;
};
int main()
{
string id, name;
float sale;
cout << "Input id name and sale:" << endl;
cin >> id >> name >> sale;
if (sale < 0)
{
cout << "Input Error!" << endl;
return 0;
}
SalesManager sm(id, name, sale);
sm.display();
return 0;
}
运算符重载课堂练习:分钟秒钟的时间相减★★★
【问题描述】
定义一个时间类CTime,分钟和秒钟是其两个私有成员数据。输入一个起始时间和一个结束时间(起始时间早于结束时间),通过运算符重载-(减号),计算这两个时间相隔多少秒钟。说明:这两个时间在同一小时之内,且采用60分钟60秒钟的计时分式,即从00:00-59:59。
【样例输入】
12 11 12 58
00 13 16 00
09 07 23 59
00 00 00 00
【样例输出】
47
947
892
#include <iostream>
using namespace std;
#define N 100
class CTime {
public:
int operator- (const CTime& c2);
void input() ;
int beZero() ;
private:
int m, s;
};
int CTime::operator- (const CTime& c2) {
int a = ((m - c2.m) * 60 + s - c2.s);
return a;
}
void CTime::input() {
cin >> m >> s;
}
int CTime::beZero() {
int flag = 0;
if (m == 0 && s == 0) {
flag = 1;
}
return flag;
}
int main()
{
CTime time[N];
int count = -1;
do
{
count++;
time[2 * count].input();
time[2 * count + 1].input();
} while (!(time[2 * count].beZero() && time[2 * count + 1].beZero()));
for (int i = 0; i < count; i++)
{
cout << (time[2 * i + 1] - time[2 * i]) << endl;
}
return 0;
}
教材习题8_7:对类Point重载自增和自减运算符
【问题描述】
对类Point重载“++”(自增)、“–”(自减)运算符,要求同时重载前缀和后缀。
【输入形式】
无
【输出形式】
参考的输出结果如下(没有输入):
(5,5)
(7,7)
(6,6)
(6,6)
#include <iostream>
using namespace std;
class Point {
public:
Point(int x = 0, int y = 0);
void display();
Point& operator++ ();
Point operator++(int);
Point& operator-- ();
Point operator--(int);
private:
int x, y;
};
Point::Point(int x, int y) {
this->x = x;
this->y = y;
}
void Point::display() {
cout << "(" << x << "," << y << ")" << endl;
}
Point& Point::operator++() {
x++;
y++;
return *this;
}
Point Point::operator++(int) {
Point old = *this;
++(*this);
return old;
}
Point& Point::operator--() {
x--;
y--;
return *this;
}
Point Point::operator--(int) {
Point old = *this;
--(*this);
return old;
}
int main()
{
Point a, b(5, 5);
a = b++;
a.display();
a = ++b;
a.display();
a = --b;
a.display();
a = b--;
a.display();
}
教材习题9_10:利用插入排序函数模板进行排序
【问题描述】
初始化int类型数组data[]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20},应用本章的直接插入排序函数模板进行排序。对此函数模板稍做修改,加入输出语句,在每插入一个待排序元素后显示整个数组,观察排序过程中数据的变化,加深对插入排序算法的理解。
【输入形式】
无
【输出形式】
参考的输出结果(注:只有19行,第1个数不用插入):
1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
…
#include<iostream>
using namespace std;
template<class T>
void insertionSort(T a[], int n) {
int i, j;
T temp;
for (int i = 1; i < n; i++) {
int j = i;
T temp = a[i];
while (j > 0 && temp < a[j - 1]) {
a[j] = a[j - 1];
j--;
}
a[j] = temp;
for (int b = 0; b < n; b++) {
cout << a[b]<<" ";
}
cout << endl;
}
}
int main() {
const int n = 20;
int data[n] = { 1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20 };
insertionSort(data,n);
return 0;
}
教材习题10_8:统计单词曾经出现的次数
问题描述】
编写一个程序,从键盘上输入一个个单词,每接收到一个单词后,输出该单词是否曾经出现过以及出现次数。可以尝试分别用多重集合(multiset)或映射(map)两种途径实现,将二者进行比较。本题答案你可以任意提交一种方法的代码。
注:输入一个单词并回车,立即输出出现的次数(用times:次数)表示。输入#结束。
参考的输入输出如下(下面单数行为输入,双数行为输出):
hello
times:0
world
times:0
hello
times:1
hello
times:2
#
#include <iostream>
#include <string>
using namespace std;
#include <set>
int main()
{
multiset<string> arr;
string s;
cin >> s;
while (s != "#")
{
int times = 0;
times = arr.count(s);
cout << "times:" << times << endl;
arr.insert(s);
cin >> s;
}
}
教材习题10_5:约瑟夫问题
【问题描述】
约瑟夫问题:n个骑士编号1,2,…,n,围坐在圆桌旁。编号为1的骑士从1开始报数,报到m的骑士出列,然后下一个位置再从1开始报数,找出最后留在圆桌旁的骑士编号。
(1)编写一个函数模板。以一种顺序容器的类型作为模板参数,在模板中使用指定类型的顺序容器求解约瑟夫问题。m,n是该函数模板的形参。
(2)分别以vector,deque,list作为类型参数调用该函数模板,调用时将n设为较大的数,将m设为较小的数(例如令n=100000,n=5)。观察3种情况下调用该函数模板所需花费的时间。
注:本题答案的提交只需选择一种顺序容器类型作为模板参数。
【输入形式】
程序参考的输入(数字前为提示文字):
Input n and m:7 3
【输出形式】
程序参考的输出:
Result:4
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> a;
int n, m, x = 0;
cout << "Input n and m:";
cin >> n >> m;
a.resize(n);
for (int i = 0; i < n; i++)
{
a[i] = i + 1;
}
x = -1;
while (a.size() != 1)
{
x = (x + m) % a.size();
a.erase(a.begin() + x);
x = x - 1;
}
cout << "Result:" << a[0] << endl;
return 0;
}