C++编程调试秘笈----读书笔记(3)(二)

2014-11-24 08:38:17 · 作者: · 浏览: 1
EST_ASSERT(index < N,
"Index " << index << " must be less than " << N);
return data_[index];
}
T* begin() { return &data_[0]; }
const T* begin() const { return &data_[0]; }
T* end() { return &data_[N]; }
const T* end() const { return &data_[N]; }
private:
T data_[N];
};
}
template
inline std::ostream &operator << (std::ostream &os, const scpp::array& v)
{
for (unsigned index = 0; index < v.size(); ++index)
{
os << v[index];
if (index + 1 < v.size())
{
os << " ";
}
}
return os;
}
#endif // __SCPP_ARRAY_H__
测试代码(vs2012+win7环境):
[cpp]
#include "stdafx.h"
#include "scpp_assert.h"
#include "iostream"
#include "scpp_vector.h"
#include "scpp_array.h"
#include "algorithm"
#define SIZE 10
int _tmain(int argc, _TCHAR* argv[])
{
scpp::array str(1);
str[0] = 7;
str[1] = 2;
str[2] = 8;
str[3] = 4;
std::cout << str << std::endl;
std::sort(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
这个数组的行为和C的静态数组完全一样。但是,在编译时激活了表示安全检查的SCPP_TEST_ASSERT_ON宏时,他会提供索引边界检查。提供了begin和end方法,所以可以使用algorithm的一些算法
3、多维数组
其实多维数组也就是矩阵,如果矩阵的大小在编译时时已知的,可以很方便地把它实现为数组的数组。因此将注意力集中在当矩阵的大小是在运行时计算产生的这种情况。内部可以用一个vector来存储,返回的时候只需要加上index就行
scpp_matrix.h:
[cpp]
#ifndef __SCCP_MATRIX_H__
#define __SCCP_MATRIX_H__
#include "ostream"
#include "vector"
#include "scpp_assert.h"
namespace scpp
{
template
class matrix
{
public:
typedef unsigned size_type;
public:
matrix(size_type numRows, size_type numCols)
:rows_(numRows), cols_(numCols), data_(numCols * numRows)
{
SCPP_TEST_ASSERT(numRows > 0,
"Number of rows in a matrix must be positive");
SCPP_TEST_ASSERT(numCols > 0,
"Number of cols in a matrix must be positive");
}
matrix(size_type numRows, size_type numCols, const T& initValue)
:rows_(numRows), cols_(numCols), data_(numCols * numRows)
{
SCPP_TEST_ASSERT(numRows > 0,
"Number of rows in a matrix must be positive");
SCPP_TEST_ASSERT(numCols > 0,
"Number of cols in a matrix must be positive");
}
size_type numRows() const { return rows_; }
size_type numCols() const { return cols_; }
T& operator() (size_type row, size_type col)
{
return data_[ index(row, col) ];
}
const T& operator() (size_type row, size_type col) const
{
return data_[ index(row, col) ];
}
private:
size_type index(size_type row, size_type col) const
{
SCPP_TEST_ASSERT(row < rows_,
"Row" << row << " must be less than " << rows_);
SCPP_TEST_ASSERT(col < cols_,
"Col" << col << " must be less than " << cols_);
return cols_ * row + col;
}
private:
size_type rows_;
size_type cols_;
vector data_;
};
}
template
inline std::ostream &operator << (std::ostream &os, const scpp::matrix& m)
{
for (unsigned rowIndex = 0; rowIndex < m.numRows(); ++rowIndex)
{
for (unsigned colIndex = 0; colIndex < m.numCols(); ++colIndex)
{
os << m(rowIndex, colIndex);
if (colIndex < m.numCols())
{
os << "\t";
}
}
}
return os;
}
#endif
测试代码(vs2012+win7环境):
[cpp]
#include "stdafx.h"
#i