Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

一週間で身につくC++言語の基本[練習問題]

Last updated at Posted at 2023-02-15

※注意

本記事は、筆者が考えた解答であり、実際の解答とは異なる場合があります。

基本編

名前空間とストリーム(1日目)

prob1-1.

#include <iostream>

using namespace std;

int main(void)
{
	cout << "C++" << endl;
	return (0);
}

prob1-2.

#include <iostream>

// using namespace std;

int main(void)
{
	std::cout << "prigramming in C++ Language" << std::endl;
	return (0);
}

prob1-3.

#include <iostream>

using namespace std;

int main(void)
{
	cout << "ONE TWO THREE" << endl << "FOUR FIVE SIX" << endl;
	return (0);
}

prob1-4.

#include <iostream>

using namespace std;

int main(void)
{
	int value;

	cout << "Please enter a numerical value:";
	cin >> value;
	cout << "Number of " << value << " multiplied by 2 is " << value * 2 << "." << endl;
	return (0);
}

prob1-5.

#include <iostream>

using namespace std;

int main(void)
{
	int first, second;

	cout << "first number:";
	cin >> first;
	cout << "second number:";
	cin >> second;
	cout << first << " + " << second << " = " << first + second << endl;
		cout << first << " - " << second << " = " << first - second << endl;
	return (0);
}

prob1-6.

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string first, last;

	cout << "first name:";
	cin >> first;
	cout << "last name:";
	cin >> last;
	cout << "My name is " << first << " " << last << "." << endl;
	return (0);
}

prob1-7.

#include <iostream>

using namespace std;

int main(){
	cout << "HelloWorld." << endl;
}

クラス(2日目)

prob2-1.

keisan.h
#ifndef _KEISAN_H_
#define _KEISAN_H_

class Keisan
{
public:
	int a;
	int b;
	int add();
	int sub();
};

#endif
keisan.cpp
#include "keisan.h"

int Keisan::add()
{
	return a + b;
}

int Keisan::sub()
{
	return a - b;
}
main.cpp
#include <iostream>
#include "keisan.h"

using namespace std;

int main()
{
	Keisan k;
	k.a = 4;
	k.b = 3;
	cout << k.a << " + " << k.b << " = " << k.add() << endl;
	cout << k.a << " - " << k.b << " = " << k.sub() << endl;
	return 0;
}

prob2-2.

minmax.h
#ifndef _MINMAX_H_
#define _MINMAX_H_

class MinMax
{
public:
	int max(int n1, int n2, int n3);
	int min(int n1, int n2, int n3);
};

#endif
minmax.cpp
#include "minmax.h"

int MinMax::max(int n1, int n2, int n3)
{
	if (n1 > n2)
	{
		if (n1 > n3)
			return n1;
		else
			return n3;
	}
	else
	{
		if (n2 > n3)
			return n2;
		else
			return n3;
	}
}

int MinMax::min(int n1, int n2, int n3)
{
	return -max(-n1, -n2, -n3);
}
main.cpp
#include <iostream>
#include "minmax.h"

using namespace std;

int main(void)
{
	MinMax m;
	int a = 4;
	int b = 2;
	int c = 7;
	cout << "Of " << a << ", " << b << " and " << c << ", " << "the largest is " << m.max(a, b, c) << "." << endl;
	cout << "Of " << a << ", " << b << " and " << c << ", " << "the smallest is " << m.min(a, b, c) << "." << endl;
	return (0);
}

アクセス指定子(3日目)

prob3-1.

data.h
#ifndef _CDATA_H_
#define _CDATA_H_

#include <iostream>
#include <string>

using namespace std;

class CDATA
{
private:
	// member variable
	int number;
	// member variable
	string comment;
public:
	// initialization
	void init();
	// setter
	void setNumber(int n);
	void setComment(string s);
	// getter
	int getNumber();
	string getComment();
};

#endif
data.cpp
#include "data.h"

void CDATA::init()
{
	number = 0;
	comment = "";
}

void CDATA::setNumber(int n)
{
	number = n;
}

int CDATA::getNumber()
{
	return (number);
}

void CDATA::setComment(string s)
{
	comment = s;
}

string CDATA::getComment()
{
	return (comment);
}
main.cpp
#include <iostream>
#include "data.h"

using namespace std;

int main(void)
{
	CDATA d;
	d.init();
	d.setNumber(100);
	d.setComment("Programming C++");
	cout << "number = " << d.getNumber() << " comment = " << d.getComment() << endl;
	return (0);
}

prob3-2.

twostrings.h
#ifndef _TWOSTRINGS_H_
#define _TWOSTRINGS_H_

#include <iostream>
#include <string>

using namespace std;

class TwoStrings
{
private:
	// First string
	string m_string1;
	// Second string
	string m_string2;
public:
	// set first string
	void setString1(string s);
	// set second string
	void setString2(string s);
	// get first string
	string getString1();
	// get second string
	string getString2();
	// get connected two string
	string getConnectedString();
	// get length that is getted by getConnectedString()
	int getConnectedLength();
};

#endif
twostrings.cpp
#include "twostrings.h"

void TwoStrings::setString1(string s)
{
	m_string1 = s;
}

string TwoStrings::getString1()
{
	return (m_string1);
}

void TwoStrings::setString2(string s)
{
	m_string2 = s;
}

string TwoStrings::getString2()
{
	return (m_string2);
}

string TwoStrings::getConnectedString()
{
	return (m_string1 + m_string2);
}

int TwoStrings::getConnectedLength()
{
	return (getConnectedString().length());
}
main.cpp
#include <iostream>
#include "twostrings.h"

using namespace std;

int main(void)
{
	TwoStrings s;
    s.setString1("Hello");
    s.setString2("World");
    cout << "First string is " << s.getString1() << "." << endl;
    cout << "Second string is " << s.getString2() << "." << endl;
    cout << "Connected string is " << s.getConnectedString() << "." << endl;
    cout << "Lengths of Connected string is " << s.getConnectedLength() << "." << endl;
	return (0);
}

prob3-3.

caculation.h
#ifndef _CALCULATION_H_
#define _CALCULATION_H_

#include <iostream>

using namespace std;

class Calculation
{
private:
	// First number
	int m_number1;
	// Second number
	int m_number2;
public:
	// set first number
	void setNumber1(int n);
	// set second number
	void setNumber2(int n);
	// get first number
	int getNumber1();
	// get second number
	int getNumber2();
	// add first number and second number
	int add();
	// substract first number and second number
	int sub();
};

#endif
calculation.cpp
#include "calculation.h"

void Calculation::setNumber1(int n)
{
	m_number1 = n;
}

int Calculation::getNumber1()
{
	return (m_number1);
}

void Calculation::setNumber2(int n)
{
	m_number2 = n;
}

int Calculation::getNumber2()
{
	return (m_number2);
}

int Calculation::add()
{
	return (getNumber1() + getNumber2());
}

int Calculation::sub()
{
	return (getNumber1() - getNumber2());
}
main.cpp
#include "calculation.h"

int main(void)
{
	Calculation c;
	c.setNumber1(8);
	c.setNumber2(9);
	// display result of addition
	cout << c.getNumber1() << " + " << c.getNumber2() << " = " << c.add() << endl;
    // display result of substraction
    cout << c.getNumber1() << " - " << c.getNumber2() << " = " << c.sub() << endl;
	return (0);
}

生成と消去(4日目)

prob4-1.

number.h
#ifndef _NUMBER_H_
#define _NUMBER_H_

class Number
{
private:
	// member variable
	int a;
	int b;
public:
	// set two figure
	void setNumbers(int n1, int n2);
	// get result to addition
	int getAdd();
	// constructor
	Number();
	// destructor
	~Number();
};

#endif
number.cpp
#include "number.h"

Number::Number() : a(0), b(0)
{
	// Nothing to do
}

Number::~Number()
{
	// Nothing to do
}

// set two figure
void Number::setNumbers(int n1, int n2)
{
	a = n1;
	b = n2;
}

int Number::getAdd()
{
	return (a + b);
}
main.cpp
#include <iostream>
#include "number.h"

using namespace std;

int main(void)
{
	Number* pN;
	pN = new Number();
	// cout << pN->getAdd() << endl;
	pN->setNumbers(1, 2);
	cout << pN->getAdd() << endl;
	delete pN;
	return (0);
}

prob4-2.

hoge.h
#ifndef _HOGE_H_
#define _HOGE_H_

class Hoge
{
public:
	// constructor
	Hoge();
	// destructor
	~Hoge();
	void foo();
};

#endif
hoge.cpp
#include "hoge.h"
#include <iostream>

using namespace std;

Hoge::Hoge()
{
	cout << "constrctor" << endl;
}

Hoge::~Hoge()
{
	cout << "destructor" << endl;
}

void Hoge::foo()
{
	cout << "foo method" << endl;
}
main.cpp
#include <iostream>
#include "hoge.h"

using namespace std;

int main(void)
{
	Hoge* pH;
	pH = new Hoge();
	pH->foo();
	delete pH;
	return (0);
}

prob4-3.

main.cpp
#include <iostream>

using namespace std;

int main(void)
{
	// Generate array
	int* num = new int[4];
	int i;
	// Assign values to the array
	for (i = 0; i < 4; i++)
	{
		num[i] = i;
	}
	// Display array contents
	for (i = 0; i < 4; i++)
	{
		cout << "num[" << i << "]=" << num[i] << " ";
	}
	cout << endl;
	delete [] num;
	return (0);
}

静的メンバ(5日目)

prob5-1.

function.h
#ifndef _FUNCTION_H_
#define _FUNCTION_H_

class Function
{
public:
	// Function to return the maximum value
	static int max(int n1, int n2);
	// Function to return the minimum value
	static int min(int n1, int n2);
};

#endif
function.cpp
#include "function.h"

int Function::max(int n1, int n2)
{
	return ((n1 > n2)? n1 : n2);
}

int Function::min(int n1, int n2)
{
	return (-max(-n1, -n2));
}
main.cpp
#include <iostream>
#include "function.h"

using namespace std;

int main(void)
{
	int m = 3, n = 1;
	cout << "Of " << m << " and " << n << ", " << Function::max(m, n) << " is the largest." << endl;
	cout << "Of " << m << " and " << n << ", " << Function::min(m, n) << " is the smallest." << endl;
	return (0);
}

prob5-2.

object.h
#ifndef _OBJECT_H_
#define _OBJECT_H_

class Object
{
private:
	static int m_objectNum;
public:
	// constructor
	Object();
	// destructor
	~Object();
	// additional function
	static int getObjectNum();
};

#endif
object.cpp
#include "object.h"

// Set initial values for static member variables
int Object::m_objectNum = 0;

// constructor
Object::Object()
{
	// Count the number of objects
	m_objectNum++;
}

// destructor
Object::~Object()
{
	// Count the number of objects
	m_objectNum--;
}

// Get the value of m_objectNum
int Object::getObjectNum()
{
	return (m_objectNum);
}
main.cpp
#include <iostream>
#include "object.h"

using namespace std;

int main(void)
{
	Object *o1, *o2, *o3;
    o1 = new Object();
    o2 = new Object();
    o3 = new Object();
    cout << "Num of object:" << Object::getObjectNum() << endl;
    delete o3;
    cout << "Num of object:" << Object::getObjectNum() << endl;
    delete o2;
    delete o1;
	return (0);
}

prob5-3.

counter.h
#ifndef _COUNTER_H_
#define _COUNTER_H_

class Counter
{
private:
	// frequency
	int m_count;
	// Static member variable that records the total number of counts
	static int m_totalCount;
public:
	// constructor
	Counter();
	// reset
	void reset();
	// count
	void count();
	// num of count
	int getCount();
	// addtional function
	static int getTotalCount();
};

#endif
counter.cpp
#include "counter.h"

int Counter::m_totalCount = 0;

// Constructor (initialize counts with 0)
Counter::Counter() : m_count(0)
{
}

void Counter::reset()
{
	m_totalCount -= m_count;
	m_count = 0;
}

void Counter::count()
{
	m_count++;
	m_totalCount++;
}

int Counter::getCount()
{
	return (m_count);
}

int Counter::getTotalCount()
{
	return (m_totalCount);
}
main.cpp
#include <iostream>
#include "counter.h"

using namespace std;

int main(void)
{
	Counter c1, c2;
	c1.count();
	c2.count();
	c2.count();
	c2.reset();
	c1.count();
	c1.count();
	c2.count();
	cout << "Num of c1's count : " << c1.getCount() << endl;
	cout << "Num of c2's count : " << c2.getCount() << endl;
	cout << "Num of total count : " << Counter::getTotalCount() << endl;
	return (0);
}

継承(6日目)

prob6-1.

airplane.h
#ifndef _AIRPLANE_H_
#define _AIRPLANE_H_

class Airplane
{
public:
	void fly();
};

#endif
airplane.cpp
#include "airplane.h"
#include <iostream>

using namespace std;

void Airplane::fly()
{
	cout << "Flight." << endl;
}
fighter.h
#ifndef _FIGHTER_H_
#define _FIGHTER_H_

#include "airplane.h"

class Fighter : public Airplane
{
public:
	void fight();
};

#endif
fighter.cpp
#include "fighter.h"
#include <iostream>

using namespace std;

void Fighter::fight(void)
{
	cout << "Combat." << endl;
}
main.cpp
#include <iostream>
#include "airplane.h"
#include "fighter.h"

using namespace std;

int main(void)
{
	Fighter f;
	Airplane a;

	a.fly();
	f.fly();
	f.fight();
	return (0);
}

prob6-2.

fundcalc.h
#ifndef _FUNDCALC_H_
#define _FUNDCALC_H_

class FundCalc
{
protected:
	double m_number1;	// first number
	double m_number2;	// second number
public:
	// constructor
	FundCalc();
	// set the first number
	void setNumber1(double number);
	// set the second number
	void setNumber2(double number);
	// get the first number
	double getNumber1();
	// get the second number
	double getNumber2();
	// outputs the sum of two numbers
	double add();
	// outputs the difference of two numbers
	double sub();
};

#endif
fundcalc.cpp
#include "fundcalc.h"

FundCalc::FundCalc() : m_number1(0), m_number2(0)
{
}

// Set the first number
void FundCalc::setNumber1(double number)
{
	m_number1 = number;
}

// Set the second number
void FundCalc::setNumber2(double number)
{
	m_number2 = number;
}

// Get the fist number
double FundCalc::getNumber1()
{
	return m_number1;
}

// Get the second number
double FundCalc::getNumber2()
{
	return m_number2;
}

// Outputs the sum of two numbers
double FundCalc::add()
{
	return m_number1 + m_number2;
}

// Outputs the difference of two numbers
double FundCalc::sub()
{
	return m_number1 - m_number2;
}
newcalc.h
#ifndef _NEWCALC_H_
#define _NEWCALC_H_

#include "fundcalc.h"

class NewCalc : public FundCalc
{
public:
	// outputs the multiplication of two numbers
	double mul();
	// outputs the division of two numbers
	double div();
};

#endif
newcalc.cpp
#include <iostream>
#include "fundcalc.h"
#include "newcalc.h"

using namespace std;

double NewCalc::mul(void)
{
	return m_number1 * m_number2;
}

double NewCalc::div(void)
{
	return m_number1 / m_number2;
}
main.cpp
#include <iostream>
#include "newcalc.h"
 
using namespace std;
 
int main(void)
{
	NewCalc n;
	n.setNumber1(10);
	n.setNumber2(2);
	cout << n.getNumber1() << " + " << n.getNumber2() << " = " << n.add() << endl;
	cout << n.getNumber1() << " - " << n.getNumber2() << " = " << n.sub() << endl;
	cout << n.getNumber1() << " * " << n.getNumber2() << " = " << n.mul() << endl;
	cout << n.getNumber1() << " / " << n.getNumber2() << " = " << n.div() << endl;

	return 0;
}

ポリモーフィズム(7日目)

prob7-1.

counter.h
#ifndef _COUNTER_H_
#define _COUNTER_H_

class Counter
{
private:
	int m_count;
public:
	// constructor
	Counter();
	// reset counter
	void reset();
	// get counted times
	int getCount();
	// count by 1
	void count();
	// count by n
	void count(int n);
};

#endif
counter.cpp
#include "counter.h"

// constructor
Counter::Counter() : m_count(0)
{

}

// reset counter
void Counter::reset()
{
	m_count = 0;
}

// get counted times
int Counter::getCount()
{
	return m_count;
}

// count by 1
void Counter::count()
{
	m_count++;
}

// count by n
void Counter::count(int n)
{
	while (n--)
	{
		m_count++;
	}
}
main.cpp
#include <iostream>
#include "counter.h"

using namespace std;

int main(void)
{
	// generate counter
	Counter* pC = new Counter();
	pC->count(); // 1 time count
	pC->count(); // 1 time count
	cout << "Frequency : " << pC->getCount() << " times" << endl;
	pC->count(4); // 4 time count
	cout << "Frequency : " << pC->getCount() << " times" << endl;
	// reset counter
	pC->reset();
	cout << "Frequency : " << pC->getCount() << " times" << endl;
	// delete counter
	delete pC;
	return 0;
}

prob7-2.

vector.h
#ifndef _VECTOR_H_
#define _VECTOR_H_

class Vector
{
private:
	double m_x;
	double m_y;
public:
	// constructor
	Vector();
	// constructor with arguments
	Vector(double x, double y);
	// component setting
	void set(double x, double y);
	// get component of x
	double getX();
	// get component of y
	double getY();
};
 
#endif
vector.cpp
#include "vector.h"

// constructor
Vector::Vector() : m_x(0), m_y(0)
{

}

// constructor with arguments
Vector::Vector(double x, double y)
{
	m_x = x;
	m_y = y;
}

// component setting
void Vector::set(double x, double y)
{
	m_x = x;
	m_y = y;
}

// get component of x
double Vector::getX()
{
	return m_x;
}

// get component of y
double Vector::getY()
{
	return m_y;
}
main.cpp
#include <iostream>
#include "vector.h"

using namespace std;

int main()
{
	Vector *v1, *v2;
	// generated by constructor with no arguments
	v1 = new Vector();
	// generated by constructor with arguments
	v2 = new Vector(1.1, 2.3);
	v1->set(3.8, 2.7);
	cout << "v1 =(" << v1->getX() << " , " << v1->getY() << ")" << endl;
	cout << "v2 =(" << v2->getX() << " , " << v2->getY() << ")" << endl;
	delete v1;
	delete v2;
	return 0;
}

発展編

C言語との違い(1日目)

probex1-1.

#include <iostream>

using namespace std;

int main(void)
{
	int a = 7;
	int &n = a;
	cout << "a= " << a << endl;
	n += 3;
	cout << "a= " << a << endl;
	return (0);
}

probex1-2.

#include <iostream>

using namespace std;

void changeNumber(int& n)
{
	n *= 2;
}

int main(void)
{
	int n = 5;
	cout << "Before change : " << n << endl;
	changeNumber(n);
	cout << "After change : " << n << endl;
	return (0);
}

probex1-3.

#include <iostream>

using namespace std;

void swap(int &a, int &b)
{
	int tmp;
	tmp = a;
	a = b;
	b = tmp;
}

int main(void)
{
	int a = 1, b = 2;
	cout << "a = " << a << " b = " << b << endl;
	swap(a, b);
	cout << "a = " << a << " b = " << b << endl;
	return (0);
}

クラス間の相互参照(2日目)

probex2-1.

bar.h
#ifndef _BAR_H_
#define _BAR_H_

class Foo;

class Bar
{
private:
	Foo *pFoo;
public:
	void func1(Foo *pFoo);
	void func2() const;
	// constructor and destructor
	Bar();
	~Bar();
};

#endif
bar.cpp
#include "bar.h"
#include "foo.h"
#include <iostream>

using namespace std;

Bar::Bar()
{
	// Nothing to do
}

Bar::~Bar()
{
	// Nothing to do
}

void Bar::func1(Foo *pFoo)
{
	pFoo->hoge();
}

void Bar::func2() const
{
	cout << "Bar::func2()" << endl;
}
foo.h
#ifndef _FOO_H_
#define _FOO_H_

class Bar;

class Foo
{
private:
	Bar *pBar;
public:
	void hoge() const;
	void fuga(Bar *pBar);
	// constructor and destructor
	Foo();
	~Foo();
};

#endif
foo.cpp
#include "bar.h"
#include "foo.h"
#include <iostream>

using namespace std;

Foo::Foo()
{
	// Nothing to do
}

Foo::~Foo()
{
	// Nothing to do
}

void Foo::hoge() const
{
	cout << "Foo::hoge()" << endl;
}

void Foo::fuga(Bar* pBar)
{
	cout << "Foo::fuga()" << endl;
	pBar->func2();
}
main.cpp
#include "foo.h"
#include "bar.h"
#include <iostream>

using namespace std;

int main(void)
{
	Foo *pFoo;
	Bar *pBar;
	pFoo = new Foo();
	pBar = new Bar();
	pFoo->hoge();
	pBar->func2();
	pFoo->fuga(pBar);
	pBar->func1(pFoo);
	delete pFoo;
	delete pBar;
	return (0);
}

テンプレートとSTL(3日目)

probex3-1.

main.cpp
#include <iostream>
#include <string>

using namespace std;

template <typename T>
T add(T a, T b)
{
	if (a > b)
		return (a);
	return (b);
}

int main(void)
{
	cout << max<int>(1, 2) << endl;
	cout << max<double>(1.75, 3.12) << endl;
	string s1 = "aiu",s2 = "eo";
	cout << max<string>(s1, s2) << endl;
	return (0);
}

probex3-2.

collectionint.h
#ifndef _COLLECTIONINT_H_
#define _COLLECTIONINT_H_

using namespace std;

template<typename T> class Collection
{
private:
	// data of array
	T *m_pArray;
	// length of array;
	int m_length;
public:
	// constructor
	Collection(T *array, int length){
		m_pArray = new T[length];
		m_length = length;
		for(int i = 0; i < m_length ; i++){
			m_pArray[i] = array[i];
		}
	}
	// destructor
	~Collection(){
		delete [] m_pArray;
	}
	// get maximum value
	T getMax(){
		T max = m_pArray[0];
		for(int i = 0; i < m_length ; i++){
			if(max < m_pArray[i]){
				max = m_pArray[i];
			}
		}
		return max;
	}
	// get minimum value
	T getMin(){
		T min = m_pArray[0];
		for(int i = 0; i < m_length ; i++){
			if(min > m_pArray[i]){
				min = m_pArray[i];
			}
		}
		return min;
	}
	// display component
	void showArray(){
		for(int i = 0; i < m_length ; i++){
			cout << m_pArray[i] << " ";
		}
		cout << endl;
	}
};

#endif
main.cpp
#include <iostream>
#include "collectionint.h"

using namespace std;

int main(void)
{
	// define array variable
	int array1[] = { 1, 5, 4, 2, 3};
	double array2[] = { 1.2, 3.5, 8.1, 4.9, 2.0, 2.2};
	Collection<int> *c1 = new Collection<int>(array1, 5);
	c1->showArray();
	cout << "Maximum value : " << c1->getMax() << endl;
	cout << "Minimum value : " << c1->getMin() << endl;
	cout << endl;
	Collection<double> *c2 = new Collection<double>(array2, 6);
	c2->showArray();
	cout << "Maximum value : " << c2->getMax() << endl;
	cout << "Minimum value : " << c2->getMin() << endl;
	return (0);
}

STL①(4日目)

probex4-1.

#include <iostream>
#include <vector>

using namespace std;

int main(void)
{
	int num;
	vector<int> even;
	vector<int> odd;
	unsigned int i;
	vector<int>::iterator itr;
	while (1)
	{
		cout << "Enter a positive integer : ";
		cin >> num;
		if (num == -1)
		{
			cout << endl;
			break;
		}
		else if (num % 2 == 0)
		{
			even.push_back(num);
		}
		else
		{
			odd.push_back(num);
		}
	}
	cout << "Even number :";
	for (i=0; i<even.size(); i++)
	{
		cout << " " << even[i];
	}
	cout << endl;

	cout << "Odd number  :";
	for (itr=odd.begin(); itr != odd.end(); itr++)
	{
		cout << " " << *itr;
	}
	cout << endl;
	return (0);
}

probex4-2.

#include <iostream>
#include <vector>

using namespace std;

int find_max(vector<int> array)
{
	int max;
	
	max = array[0];
	for (int i=1; i<array.size(); i++)
	{
		if (array[i] > max)
			max = array[i];
	}
	return (max);
}

int find_min(vector<int> array)
{
	int min;

	min = array[0];
	for (int i=1; i<array.size(); i++)
	{
		if (array[i] < min)
			min = array[i];
	}
	return (min);
}

int main(void)
{
	int num;
	vector<int> array;
	while (1)
	{
		cout << "Enter a positive integer : ";
		cin >> num;
		if (num == -1)
		{
			cout << endl;
			break;
		}
		array.push_back(num);
	}
	cout << "Maximum value : " << find_max(array) << endl;
	cout << "Minimum value : " << find_min(array) << endl;
	return (0);
}

probex4-3.

#include <iostream>
#include <vector>

using namespace std;

void check_the_first_digit(vector<int> array)
{
	int count;

	for (int i=0; i<10; i++)
	{
		count = 0;
		cout << "position 1 is " << i << " : ";
		for (int j=0; j<array.size(); j++)
		{
			if (array[j] % 10 == i)
			{
				cout << array[j] << " ";
				count++;
			}
		}
		if (count == 0)
			cout << "Nothing";
		cout << endl;
	}
}

int main(void)
{
	int num;
	vector<int> array;
	while (1)
	{
		cout << "Enter a positive integer : ";
		cin >> num;
		if (num == -1)
		{
			cout << endl;
			break;
		}
		array.push_back(num);
	}
	check_the_first_digit(array);
	return (0);
}

probex4-4.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void find_longest_words(vector<string> array)
{
	int max_len;

	// Find the length of the longest word
	max_len = array[0].length();
	for (int i=1; i<array.size(); i++)
	{
		if (array[i].length() > max_len)
			max_len = array[i].length();
	}
	// Output the longest word
	for (int i=0; i<array.size(); i++)
	{
		if (array[i].length() == max_len)
			cout << array[i] << " ";
	}
	cout << endl;
}

void find_shortest_words(vector<string> array)
{
	int min_len;

	// Find the length of the shortest word
	min_len = array[0].length();
	for (int i=1; i<array.size(); i++)
	{
		if (array[i].length() < min_len)
			min_len = array[i].length();
	}
	// Output the shortest word
	for (int i=0; i<array.size(); i++)
	{
		if (array[i].length() == min_len)
			cout << array[i] << " ";
	}
	cout << endl;
}

int main(void)
{
	string word;
	vector<string> array;
	while (1)
	{
		cout << "Enter string : ";
		getline(cin , word);
		if (word == "\0")
		{
			cout << endl;
			break;
		}
		array.push_back(word);
	}
	cout << "Longest word : ";	find_longest_words(array);
	cout << "Shortest word : ";	find_shortest_words(array);
	return (0);
}

probex4-5.

#include <iostream>
#include <list>

using namespace std;

int main(void)
{
	int num;
	list<int> array;
	list<int>::iterator itr;
	list<int>::iterator tmp;

	while (1)
	{
		cout << "Enter a positive digit : ";
		cin >> num;
		if (num == -1)
		{
			cout << endl;
			break;
		}
		array.push_back(num);
	}
	for (itr = array.begin(); itr != array.end(); itr++)
	{
		if (*itr == 2)
		{
			tmp = itr;
			tmp++;
			array.remove(*itr);
			itr = tmp;
		}
	}
	for (itr = array.begin(); itr != array.end(); itr++)
	{
		cout << *itr << " ";
	}
	return (0);
}

probex4-6.

#include <iostream>
#include <list>

using namespace std;

int main(void)
{
	int num;
	list<int> array;
	list<int>::iterator itr;

	while (1)
	{
		cout << "Enter a positive digit : ";
		cin >> num;
		if (num == -1)
		{
			cout << endl;
			break;
		}
		cout << "Number of entries : ";

		if (array.empty())
		{
			array.push_back(num);
		}
		else
		{
			itr = array.begin();
			while (1)
			{
				if (*itr > num)
				{
					array.insert(itr, num);
					break;
				}
				else if (itr == array.end())
				{
					array.push_back(num);
					break;
				}
				itr++;
			}
		}
		// display
		for (itr = array.begin(); itr != array.end(); itr++)
		{
			cout << *itr << " ";
		}
		cout << endl;
	}
	return (0);
}

probex4-7.

#include <iostream>
#include <list>
#include <string>

using namespace std;

void display(list<string> array)
{
	list<string>::iterator itr;

	for (itr = array.begin(); itr != array.end(); itr++)
	{
		cout << *itr << " ";
	}
	cout << endl;
}

void delete_words_five_or_more_characters(list<string> &array)
{
	string word;
	list<string>::iterator itr;
	list<string>::iterator tmp;

	itr = array.begin();
	while (itr != array.end())
	{
		word = *itr;
		if (word.length() >= 5)
		{
			tmp = itr;
			tmp++;
			array.remove(*itr);
			itr = tmp;
		}
		else
		{
			itr++;
		}
	}
}

int main(void)
{
	string word;
	list<string> array;
	while (1)
	{
		cout << "Enter string : ";
		getline(cin , word);
		if (word == "\0")
		{
			cout << endl;
			break;
		}
		array.push_back(word);
	}
	delete_words_five_or_more_characters(array);
	display(array);
	return (0);
}

STL②(5日目)

probex5-1.

#include <iostream>
#include <map>

using namespace std;

int main(void)
{
	map<string, string> table;
	string english[] = {"cat", "dog", "bird", "tiger"};
	table[english[0]] = "neko";
	table[english[1]] = "inu";
	table[english[2]] = "tori";
	table[english[3]] = "tora";
	string animal;

	cout << "Write an animal name in English and Press Enter : ";
	cin >> animal;
	if (table.find(animal) == table.end())
		cout << "Corresponding data not registered" << endl;
	else
		cout << "Japanese [ " << table[animal] << " ]" << endl;
	return (0);
}

probex5-2.

#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
#include <stack>

using namespace std;

string convert_kansuuji(map<int, string> table, int num)
{
	string kansuuji;
	stack<string> stk;
	int counter;

	counter = 0;
	while (num)
	{
		stk.push(table[num % 10]);
		num /= 10;
		counter++;
		if (counter % 3 == 0 && num != 0)
			stk.push(",");
	}
	while (!stk.empty())
	{
		kansuuji.append(stk.top());
		stk.pop();
	}
	return (kansuuji);
}

int main(void)
{
	map<int, string> corresponding_table;
#if 1
	corresponding_table[0] = "〇";
	corresponding_table[1] = "一";
	corresponding_table[2] = "二";
	corresponding_table[3] = "三";
	corresponding_table[4] = "四";
	corresponding_table[5] = "五";
	corresponding_table[6] = "六";
	corresponding_table[7] = "七";
	corresponding_table[8] = "八";
	corresponding_table[9] = "九";
#else
	corresponding_table[0] = " zero ";
	corresponding_table[1] = " ichi ";
	corresponding_table[2] = " ni ";
	corresponding_table[3] = " san ";
	corresponding_table[4] = " shi ";
	corresponding_table[5] = " go ";
	corresponding_table[6] = " roku ";
	corresponding_table[7] = " shichi ";
	corresponding_table[8] = " hachi";
	corresponding_table[9] = " kyu ";
#endif
	bool isStringNumber = true;
	string number;
	int num;

	cout << "Input a digit : ";
	cin >> number;
	for (int i = 0; i < number.length(); i++)
	{
		if (isdigit(number[i]) == 0)
			isStringNumber = false;
	}
	if (isStringNumber)
	{
		num = atoi(number.c_str());
		cout << "Result of conversion : " << convert_kansuuji(corresponding_table, num) << endl;
	}
	else
	{
		cout << "Input a digit." << endl;
	}
	return (0);
}

probex5-3.

#include <random>
#include <iostream>
#include <set>

using namespace std;

std::random_device rd;
std::mt19937 gen(rd());

int random(int low, int high)
{
	std::uniform_int_distribution<> dist(low, high);
	return dist(gen);
}

int main(void)
{
	set<int> appearance;
	set<int>::iterator itr;
	int n;

	cout << "random number : ";
	for (int i=0; i<10; i++)
	{
		n = random(1, 10) % 10 + 1;
		cout << n << " ";
		appearance.insert(n);
	}
	cout << endl;
	cout << "Number of appearances : ";
	for (itr = appearance.begin(); itr != appearance.end(); itr++)
	{
		cout << *itr << " ";
	}
	cout << endl;
	return (0);
}

probex5-4.

#include <iostream>
#include <string>
#include <set>

using namespace std;

int main(void)
{
	set<char> alphabet;
	set<char>::iterator itr;
	string word;

	cout << "Input English word : ";
	cin >> word;
	for (int i=0; i<word.length(); i++)
	{
		alphabet.insert(word[i]);
	}
	cout << "Alphabet used :";
	for (itr = alphabet.begin(); itr != alphabet.end(); itr++)
	{
		cout << " " << *itr;
	}
	cout << endl;
	return (0);
}

probex5-5.

#include <iostream>
#include <string>
#include <queue>

using namespace std;

int main(void)
{
	queue<string> str_que;
	string word;

	while (1)
	{
		cout << "Input character string : ";
		getline(cin, word);
		if (word == "\0")
		{
			cout << endl;
			break;
		}
		str_que.push(word);
	}
	while (!str_que.empty())
	{
		cout << str_que.front() << endl;
		str_que.pop();
	}
	return (0);
}

probex5-6.

#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main(void)
{
	stack<string> str_stk;
	string word;

	while (1)
	{
		cout << "Input character string : ";
		getline(cin, word);
		if (word == "\0")
		{
			cout << endl;
			break;
		}
		str_stk.push(word);
	}
	while (!str_stk.empty())
	{
		cout << str_stk.top() << endl;
		str_stk.pop();
	}
	return (0);
}

probex5-7.

#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main(void)
{
	stack<char> char_stk;
	string word;

	cout << "Input English word : ";
	cin >> word;
	for (int i=0; i<word.length(); i++)
	{
		char_stk.push(word[i]);
	}
	cout << endl;
	while (!char_stk.empty())
	{
		cout << char_stk.top();
		char_stk.pop();
	}
	cout << endl;
	return (0);
}

probex5-8.

#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
#include <queue>

using namespace std;

string convert_kansuuji(map<char, string> table, string num)
{
	string kansuuji;
	queue<string> char_que;
	int counter;

	counter = 0;
	for (int i=0; i<num.length(); i++)
	{
		char_que.push(table[num[i]]);
		counter++;
		if ((num.length() - counter) % 3 == 0 && num.length() - counter != 0)
			char_que.push(",");
	}
	while (!char_que.empty())
	{
		kansuuji.append(char_que.front());
		char_que.pop();
	}
	return (kansuuji);
}

int main(void)
{
	map<char, string> corresponding_table;
	char num_str[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
	corresponding_table[num_str[0]] = "〇";
	corresponding_table[num_str[1]] = "一";
	corresponding_table[num_str[2]] = "二";
	corresponding_table[num_str[3]] = "三";
	corresponding_table[num_str[4]] = "四";
	corresponding_table[num_str[5]] = "五";
	corresponding_table[num_str[6]] = "六";
	corresponding_table[num_str[7]] = "七";
	corresponding_table[num_str[8]] = "八";
	corresponding_table[num_str[9]] = "九";
	bool isStringNumber = true;
	string number;

	cout << "Input a digit : ";
	cin >> number;
	for (int i = 0; i < number.length(); i++)
	{
		if (isdigit(number[i]) == 0)
			isStringNumber = false;
	}
	if (isStringNumber)
	{
		cout << "Result of conversion : " << convert_kansuuji(corresponding_table, number) << endl;
	}
	else
	{
		cout << "Input a digit." << endl;
	}
	return (0);
}

probex5-9.

#include <iostream>
#include <string>
#include <map>

using namespace std;

int searching_words(string words[], string str)
{
	for (int i=0; i<words->length(); i++)
	{
		if (words[i] == str)
			return (1);
	}
	return (0);
}

int main(void)
{
	map<string, string> siritori;
	string words[] = {"room", "wonderful", "pork", "trap", "kind", "money", "dog", "given", "yellow", "eat", "apple", "neighbor"};
	siritori[words[0]] = "money";		// room → money
	siritori[words[2]] = "kind";		// pork → kind
	siritori[words[3]] = "pork";		// trap → pork
	siritori[words[4]] = "dog";			// kind → dog
	siritori[words[5]] = "yellow";		// money → yellow
	siritori[words[6]] = "given";		// dog → given
	siritori[words[7]] = "neighbor";	// given → neighbor
	siritori[words[8]] = "wonderful";	// yellow → wonderful
	siritori[words[9]] = "trap";		// eat → trap
	siritori[words[10]] = "eat";		// apple → eat
	siritori[words[11]] = "room";		// neighbor → room
	string str;

	cout << "room wonderful pork trap kind money dog given yellow eat apple neighbor" << endl << endl;
	cout << "Please choose one of these." << endl;
	cout << "input a word : ";
	cin >> str;
	cout << endl;
	while (1)
	{
		if (siritori.find(str) == siritori.end())
		{
			if (searching_words(words, str) == 0)
			{
				cout << "Please choose one of the words above." << endl;
			}
			else
			{
				cout << endl << "Could not find the rest of the siritori." << endl;
			}
			break;
		}
		else
		{
			cout << " → " << siritori[str];
			str = siritori[str];
		}
	}
	return (0);
}

virtualと仮想関数(6日目)

probex6-1

baseballplayer.h
#ifndef _BASEBALLPLAYER_H_
#define _BASEBALLPLAYER_H_
 
#include <iostream>
#include <string>
 
using namespace std;

class BaseballPlayer
{
protected:
	// number on player's back
	int m_number;
	// Player Type
	string m_kind;
	// name
	string m_name;
public:
	// get number
	int getNumber();
	// get type
	string getKind();
	// get name
	string getName();
	// func of play
	virtual void play()=0;
};

#endif
baseballplayer.cpp
#include "baseballplayer.h"

int BaseballPlayer::getNumber()
{
	return m_number;
}

string BaseballPlayer::getKind()
{
	return m_kind;
}

string BaseballPlayer::getName()
{
	return m_name;
}
catcher.h
#ifndef _CATCHER_H_
#define _CATCHER_H_

#include "baseballplayer.h"

class Catcher : public BaseballPlayer
{
public:
	// Constructor
	Catcher(string name, int number);
	// catcher plays
	void play();
};

#endif
catcher.cpp
#include "catcher.h"

Catcher::Catcher(string name, int number)
{
	m_name = name;
	m_number = number;
	m_kind = "catcher";
}

// the catcher plays
void Catcher::play()
{
	cout << "take the ball from the pitcher" << endl;
}
fielder.h
#ifndef _FIELDER_H_
#define _FIELDER_H_

#include "baseballplayer.h"

class Fielder : public BaseballPlayer
{
public:
	// Constructor
	Fielder(string name,int number);
	// fielder plays
	void play();
};
 
#endif
fielder.cpp
#include "fielder.h"
 
Fielder::Fielder(string name,int number) 
{
	m_name = name;
	m_number = number;
	m_kind = "fielder";
}

// the fielder plays
void Fielder::play()
{
	cout << "handle a batted ball" << endl;
}
pitcher.h
#ifndef _PITCHER_H_
#define _PITCHER_H_

#include "baseballplayer.h"

class Pitcher : public BaseballPlayer
{
public:
	// Constructor
	Pitcher(string name,int number);
	// Pitcher plays.
	void play();
};

#endif
pitcher.cpp
#include "pitcher.h"

Pitcher::Pitcher(string name,int number)
{
	m_name = name;
	m_number = number;
	m_kind = "pitcher";
}

// Pitcher plays
void Pitcher::play()
{
	cout << "Pitching" << endl;
}
main.cpp
#include "baseballplayer.h"
#include "pitcher.h"
#include "catcher.h"
#include "fielder.h"

int main()
{
	// Creating an array of baseball players
	BaseballPlayer* players[9];
	players[0] = new Pitcher("Yamada",8);
	players[1] = new Catcher("Takasaka",16);
	players[2] = new Fielder("Gomez",16);
	players[3] = new Fielder("Nakamura",6);
	players[4] = new Fielder("Kasugai",32);
	players[5] = new Fielder("Hotta",5);
	players[6] = new Fielder("Osaka",54);
	players[7] = new Fielder("Tomas",11);
	players[8] = new Pitcher("Saitoh",34);

	for(int i = 0; i < 9; i++)
	{
		cout << "---------------------------------------------" << endl;
		cout << "Name: " << players[i]->getName() << endl;
		cout << "Number on player's back: " << players[i]->getNumber() << endl;
		cout << "Type: " << players[i]->getKind() << endl;
	}
	// delete instance
	for(int i = 0; i < 9; i++)
	{
		delete players[i];
	}
	return 0;
}

probex6-2.

airplane.h
#ifndef _AIRPLANE_H_
#define _AIRPLANE_H_

#include <string>

using namespace std;

class AirPlane
{
protected:
	string m_type;
public:
	virtual void fly() = 0;
};

#endif
fighteraircraft.h
#ifndef _FIGHTERAIRCRAFT_H_
#define _FIGHTERAIRCRAFT_H_

#include <iostream>
#include <string>
#include "airplane.h"

using namespace std;

class FighterAircraft : public AirPlane
{
public:
	// constructor
	FighterAircraft();
	// get type
	string getType();
	// fly
	void fly();
	// fight
	void fight();
};

#endif
fighteraircraft.cpp
#include "fighteraircraft.h"

// constructor
FighterAircraft::FighterAircraft()
{
	m_type = "fighter aircraft";
}

// get type
string FighterAircraft::getType()
{
	return m_type;
}

// fly
void FighterAircraft::fly()
{
	cout << "flying to attack" << endl;
}

// fight
void FighterAircraft::fight()
{
	cout << "Flying to fight" << endl;
}
passengerplane.h
#ifndef _PASSENGERPLANE_H_
#define _PASSENGERPLANE_H_

#include <iostream>
#include <string>
#include "airplane.h"

using namespace std;

// Passenger Plane class
class PassengerPlane : public AirPlane
{
public:
	// constructor
	PassengerPlane();
	// get type
	string getType();
	// fly()
	void fly();
	// carry passengers
	void carryPassengers();
};

#endif
passengerplane.cpp
#include "passengerplane.h"

// Constructor
PassengerPlane::PassengerPlane()
{
	m_type = "passenger plane";
}

// get the type
string PassengerPlane::getType()
{
	return m_type;
}

// Fly
void PassengerPlane::fly()
{
	cout << "Fly to the destination with passengers." << endl;
}

// Carry passengers
void PassengerPlane::carryPassengers()
{
	cout << "Carry passengers to their destinations." << endl;
}
main.cpp
#include <iostream>
#include "airplane.h"
#include "fighteraircraft.h"
#include "passengerplane.h"

using namespace std;

int main()
{
	// create an instance of the fighter plane class
	FighterAircraft* fighter = new FighterAircraft();
	PassengerPlane* airlinear = new PassengerPlane();
	// Processing of the fighter class
	fighter->fly(); // fly
	fighter->fight(); // fighter->fight()
	// Passenger Plane class processing
	airlinear->fly(); // fly
	airlinear->carryPassengers(); // carry passengers
	// delete process
	delete fighter;
	delete airlinear;
	return 0;
}

演算子の多重定義(7日目)

probex7-1.

vector3.h
#ifndef _VECTOR3_H_
#define _VECTOR3_H_

#include <iostream>
#include <string>

using namespace std;

class Vector3
{
public:
	double x;
	double y;
	double z;
public:
	Vector3& operator=(const Vector3 &v);
	Vector3& operator+=(const Vector3 &v);
	Vector3& operator-=(const Vector3 &v);
};

	Vector3 operator+(const Vector3&, const Vector3&);
	Vector3 operator-(const Vector3&, const Vector3&);
	Vector3 operator*(const double, const Vector3&);

#endif
vector3.cpp
#include "vector3.h"

// overloading the + operator
Vector3 operator+(const Vector3& v1,const Vector3& v2)
{
	Vector3 v;
	v.x = v1.x + v2.x;
	v.y = v1.y + v2.y;
	v.z = v1.z + v2.z;
	return v;
}

// -operator overloading
Vector3 operator-(const Vector3& v1,const Vector3& v2)
{
	Vector3 v;
	v.x = v1.x - v2.x;
	v.y = v1.y - v2.y;
	v.z = v1.z - v2.z;
	return v;
}

// scalar doubling
Vector3 operator*(const double d, const Vector3& v)
{
	Vector3 r;
	r.x = d * v.x;
	r.y = d * v.y;
	r.z = d * v.z;
	return r;
}

// = operator overloading
Vector3& Vector3::operator=(const Vector3& v)
{
	x = v.x;
	y = v.y;
	z = v.z;
	return *this;
}

// overloading the += operator
Vector3& Vector3::operator+=(const Vector3& v)
{
	x += v.x;
	y += v.y;
	z += v.z;
	return *this;
}

// Overloading the -= operator
Vector3& Vector3::operator-=(const Vector3& v)
{
	x -= v.x;
	y -= v.y;
	z -= v.z;
	return *this;
}
main.cpp
#include <iostream>
#include "vector3.h"

using namespace std;

void vec(string vecname, Vector3& v)
{
	cout << vecname << "(" << v.x << "," << v.y << "," << v.z << ")" << endl;
}

int main()
{
	Vector3 v1, v2, v3;

	v1.x = 1.0;
	v1.y = 2.0;
	v1.z = 3.0;
	v2 = v1;
	v3 = 4.0 * v1 + 1.0 * v1 - 1.0 * v1;
	vec("v1=", v1);
	vec("v2=", v2);
	v2 += v1;
	vec("v1 + v2=", v2);
	vec("v3=", v3);
	v3 += 5.0 * v1;
	v3 -= 4.0 * v1;
	vec("v1=", v3);
	v2 = 0.0 * v2;
	vec("v2=", v2);
	return 0;
}

probex7-2.

NewString.h
#ifndef _NEWSTRING_H_
#define _NEWSTRING_H_

#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <string>

using namespace std;

class NewString
{
private:
	// string
	string m_value;
public:
	// constructor
	NewString();
	// constructor to assign a value (from string)
	NewString(string value);
	// constructor to assign a value (from another class)
	NewString(NewString& value);
	// assign value
	NewString& operator= (NewString& n);
	// Compare equal values
	bool operator==(NewString& n) const;
	// Compare if values are not equal
	bool operator!=(NewString& n) const;
	// get value by string
	string getValue();
private:
	// Make the string all uppercase
	string str_toupper(string s) const;
};

#endif
NewString.cpp
#include "NewString.h"

// Constructor
NewString::NewString()
{
	m_value = "";
}

// constructor to assign value (1) (from string)
NewString::NewString(string value)
{
	m_value = value;
}

// constructor to assign value (2)(from other class)
NewString::NewString(NewString& value)
{
	m_value = value.getValue();
}

// assign value
NewString& NewString::operator=(NewString& n)
{
	m_value = n.getValue();
	return *this;
}

// Compare equal values
bool NewString::operator==(NewString& n) const
{
	string s1, s2;

	s1 = str_toupper(this->m_value);
	s2 = str_toupper(n.m_value);
	if (s1.length() != s2.length())
		return false;
	for (int i=0; i<s1.length(); i++)
	{
		if (s1[i] != s2[i])
			return false;
	}
	return true;
}

// Compare if values are not equal
bool NewString::operator!=(NewString& n) const
{
	return !(*this == n);
}

// Get value by string
string NewString::getValue()
{
	return m_value;
}

// Make the string all uppercase
string NewString::str_toupper(string s) const
{
	string ss;

	for (int i=0; i<s.length(); i++)
	{
		ss = toupper(s[i]);
	}
	return ss;
}
main.cpp
#include <iostream>
#include <string>
#include "NewString.h"

using namespace std;

int main()
{
	NewString s1("HelloWorld"),s2;
	cout << s1.getValue() << endl;
	s2 = s1; // assign value
	cout << s2.getValue() << endl;
	NewString s3(s2); // call constructor with NewString as argument
	cout << s3.getValue() << endl;
	NewString s4("HELLOWORLD");
	cout << s4.getValue() << endl;
#if 1
	if(s1 == s2)
	{
		cout << "s1==s2" << endl;
	}
	if(s1 == s4)
	{
		cout << "s1==s4" << endl;
	}
#endif
	return 0;
}

問題URL

GitHub

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?