Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

s12-lab-book

.pdf
Скачиваний:
6
Добавлен:
20.04.2015
Размер:
448.77 Кб
Скачать

ООП - лабораторные работы (весна 2012), Release 0

119}

120}

121

122template<typename T>

123bool

124TplStack<T>::empty() const

125{

126return (0 == m_pHead);

127}

128

129template<typename T>

130int&

131TplStack<T>::top()

132{

133return m_pHead->m_val;

134}

135

136template<typename T>

137const int&

138TplStack<T>::top() const

139{

140return m_pHead->m_val;

141}

Основная программа с тестирующим кодом (lab-03-03.cpp).

1#include "tplstack.h"

2

3#include <iostream>

4#include <cassert>

5

6using namespace std;

7

8

9

10

template<class T>

void print(ostream& ostr, const T& st)

{

11ostr << "]";

12for (T stCopy(st); 0 == stCopy.empty(); )

13{

14

15

16

17

18

19

ostr << stCopy.top(); stCopy.pop();

if (0 == stCopy.empty())

{

ostr << " ";

}

20}

21ostr << "]";

22}

23

24int main()

25{

26using namespace std;

27TplStack<int> stDef;

28cout << "create stDef, stDef.empty() -> " << stDef.empty();

29cout << "\n stDef -> ";

30print(cout, stDef);

31

32TplStack<int> stFirst;

33stFirst.pop();

34stFirst.push(1);

35cout << "\npush into stFirst, stFirst.empty() -> " << stDef.empty();

36stFirst.push(2);

37stFirst.push(3);

3.4. Пример - создание шаблонного класса для стека на односвязном списке

28

ООП - лабораторные работы (весна 2012), Release 0

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58 }

cout << "\n stFirst -> "; print(cout, stFirst);

cout << "\n\nLet's copy stFirst to stSec"; TplStack<int> stSec(stFirst);

cout << "\n stFirst -> "; print(cout, stFirst);

cout << "\n stSec -> "; print(cout, stSec);

cout << "\n copy stFirst to stSec,\n stSec -> "; print(cout, stSec);

cout << "\n\nLet's stSec"; stSec = stSec;

cout << "\n stSec -> "; print(cout, stSec);

// FIXME - other test

return 0;

Результаты работы программы (lab-03-03.cpp)

3.4. Пример - создание шаблонного класса для стека на односвязном списке

29

ООП - лабораторные работы (весна 2012), Release 0

3.5 Задания (лабораторная работа 3)

3.5.1 Стек на динамическом массиве с нагрузочным тестированием

Задача - реализовать класс шаблонного стека на динамическом массиве (new[]/delete[]) и провести для него нагрузочный тест для оценки времени работы стека.

3.5. Задания (лабораторная работа 3)

30

CHAPTER

FOUR

ЛАБОРАТОРНАЯ РАБОТА (КЛАСС МАТРИЦЫ И РАЗЛИЧНЫЕ ВАРИАНТЫ ЕГО РЕАЛИЗАЦИИ)

Теория

абстрактный тип данных Матрица (АТД Матрица)

способы хранения элементов матрицы (по строкам/столбцам, в одном массиве с использованеим приведенного индекса)

31

ООП - лабораторные работы (весна 2012), Release 0

4.1Пример - класс матрицы с использованием std::vector<> и приведенного индекса

Задача - написать реализацию матрицы с использованием std::vector<>. Исходный текст (файл lab-04-00.cpp).

1#include <iostream>

2#include <vector>

3#include <cassert>

4

5using namespace std;

6

7class Matrix

8{

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27 };

28

public:

typedef int value_type; public:

Matrix(const int nRow, const int nCol); Matrix(const Matrix& matr); ~Matrix();

Matrix& operator=(const Matrix& rhs); value_type& at(const int iRow, const int iCol);

const value_type& at(const int iRow, const int iCol) const; ostream& writeAsTxt(ostream& ostr) const;

int nRow() const { return m_nRow; } int nCol() const { return m_nCol; }

private:

int m_nRow; int m_nCol;

vector<value_type> m_data; private:

int idx(const int iRow, const int iCol) const;

29ostream&

30operator<<(ostream& ostr, const Matrix& rhs);

31

32int main()

33{

34Matrix m1(3, 4);

35cout << "Create matrix [" << m1.nRow() << ' ' << m1.nCol() << ']' << endl;

36cout << m1;

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

cout << "\nSet elements values" << endl; m1.at(1, 2) = 8;

m1.at(m1.nRow() - 1, m1.nCol() - 1) = 3; cout << m1;

Matrix m2(m1);

cout << "\nCopy of matrix" << endl; cout << m1;

cout << "is" << endl; cout << m2;

cout << "\nTry assign itself" << endl; cout << m2;

m2 = m2;

cout << "result is" << endl; cout << m2;

const Matrix& constMatr(m2);

4.1. Пример - класс матрицы с использованием std::vector<> и приведенного индекса

32

ООП - лабораторные работы (весна 2012), Release 0

56cout << "\nRight bottom element has index [" << (constMatr.nRow() - 1) << ' '

57<< (constMatr.nCol() - 1) << "] and value "

58<< constMatr.at(constMatr.nRow() - 1, constMatr.nCol() - 1) << endl;

59

60

61return 0;

62}

63

64

65Matrix::Matrix(const int nRow, const int nCol)

66: m_nRow(nRow)

67, m_nCol(nCol)

68, m_data(nRow * nCol)

69{

70assert(0 < nRow);

71assert(0 < nCol);

72}

73

74Matrix::Matrix(const Matrix& matr)

75: m_nRow(matr.m_nRow)

76, m_nCol(matr.m_nCol)

77, m_data(m_nRow * m_nCol)

78{

79for (int i(0); i < m_nRow * m_nCol; ++i)

80{

81m_data[i] = matr.m_data[i];

82}

83}

84

85Matrix::~Matrix()

86{

87}

88

89Matrix&

90Matrix::operator=(const Matrix& matr)

91{

92if (this != &matr)

93{

94

95

96

97

98

99

100

m_nRow = matr.m_nRow; m_nCol = matr.m_nCol; m_data.resize(m_nRow * m_nCol);

for (int i(0); i < m_nRow * m_nCol; ++i)

{

m_data[i] = matr.m_data[i];

}

101}

102return *this;

103}

104

105Matrix::value_type&

106Matrix::at(const int iRow, const int iCol)

107{

108return m_data.at(idx(iRow, iCol));

109}

110

111const Matrix::value_type&

112Matrix::at(const int iRow, const int iCol) const

113{

114return m_data.at(idx(iRow, iCol));

115}

116

117ostream&

118Matrix::writeAsTxt(ostream& ostr) const

4.1. Пример - класс матрицы с использованием std::vector<> и приведенного индекса

33

130

ООП - лабораторные работы (весна 2012), Release 0

119{

120for (int iRow(0); iRow < m_nRow; ++iRow)

121{

122for (int iCol(0); iCol < m_nCol; ++iCol)

123{

124ostr << at(iRow, iCol) << ' ';

125}

126ostr << endl;

127}

128return ostr;

129}

131int

132Matrix::idx(const int iRow, const int iCol) const

133{

134return iRow * m_nCol + iCol;

135}

136

137ostream&

138operator<<(ostream& ostr, const Matrix& rhs)

139{

140return rhs.writeAsTxt(ostr);

141}

Результаты работы программы (lab-04-00.exe)

4.1. Пример - класс матрицы с использованием std::vector<> и приведенного индекса

34

ООП - лабораторные работы (весна 2012), Release 0

4.2Пример - класс матрицы с использованием std::vector<> и массива строк

Исходный текст (файл lab-04-01.cpp).

1#include <iostream>

2#include <vector>

3#include <cassert>

4

5using namespace std;

6

7class Matrix

8{

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23 };

24

public:

typedef int value_type; public:

Matrix(const int nRow, const int nCol); Matrix(const Matrix& matr); ~Matrix();

Matrix& operator=(const Matrix& rhs); value_type& at(const int iRow, const int iCol);

const value_type& at(const int iRow, const int iCol) const; ostream& writeAsTxt(ostream& ostr) const;

int nRow() const { return m_rows.size(); }

int nCol() const { return m_rows.at(0).size(); } private:

vector<vector<value_type> > m_rows;

25ostream&

26operator<<(ostream& ostr, const Matrix& rhs);

27

28int main()

29{

30Matrix m1(3, 4);

31cout << "Create matrix [" << m1.nRow() << ' ' << m1.nCol() << ']' << endl;

32cout << m1;

33

34

35

36

37

38

cout << "\nSet elements values" << endl; m1.at(1, 2) = 8;

m1.at(m1.nRow() - 1, m1.nCol() - 1) = 3; cout << m1;

39

40

41

42

43

44

Matrix m2(m1);

cout << "\nCopy of matrix" << endl; cout << m1;

cout << "is" << endl; cout << m2;

45

46

47

48

49

50

cout << "\nTry assign itself" << endl; cout << m2;

m2 = m2;

cout << "result is" << endl; cout << m2;

51const Matrix& constMatr(m2);

52cout << "\nRight bottom element has index [" << (constMatr.nRow() - 1) << ' '

53<< (constMatr.nCol() - 1) << "] and value "

54<< constMatr.at(constMatr.nRow() - 1, constMatr.nCol() - 1) << endl;

55

56

return 0;

57 }

4.2. Пример - класс матрицы с использованием std::vector<> и массива строк

35

ООП - лабораторные работы (весна 2012), Release 0

58

59

60

61Matrix::Matrix(const int nRow, const int nCol)

62: m_rows(nRow)

63{

64assert(0 < nRow);

65assert(0 < nCol);

66for (size_t i(0); i < m_rows.size() ; ++i)

67{

68m_rows[i].resize(nCol);

69}

70}

71

72Matrix::Matrix(const Matrix& matr)

73: m_rows(matr.m_rows)

74{

75}

76

77Matrix::~Matrix()

78{

79}

80

81Matrix&

82Matrix::operator=(const Matrix& matr)

83{

84if (this != &matr)

85{

86m_rows = matr.m_rows;

87}

88return *this;

89}

90

91Matrix::value_type&

92Matrix::at(const int iRow, const int iCol)

93{

94return m_rows.at(iRow).at(iCol);

95}

96

97const Matrix::value_type&

98Matrix::at(const int iRow, const int iCol) const

99{

100return m_rows.at(iRow).at(iCol);

101}

102

103ostream&

104Matrix::writeAsTxt(ostream& ostr) const

105{

106const int nRow(m_rows.size());

107const int nCol(m_rows.at(0).size());

108for (int iRow(0); iRow < nRow; ++iRow)

109{

110

111

112

113

114

for (int iCol(0); iCol < nCol; ++iCol)

{

ostr << at(iRow, iCol) << ' ';

}

ostr << endl;

115}

116return ostr;

117}

118

119ostream&

120operator<<(ostream& ostr, const Matrix& rhs)

4.2. Пример - класс матрицы с использованием std::vector<> и массива строк

36

ООП - лабораторные работы (весна 2012), Release 0

121{

122return rhs.writeAsTxt(ostr);

123}

Результаты работы программы (lab-04-01.exe)

4.2. Пример - класс матрицы с использованием std::vector<> и массива строк

37

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]