//----1,2,3为利用C++完成实现类似C的实现
1。string 对象转为C风格的字符串
2。c++中实现读取一行和设置输出宽度
3。c++中设置输出的精度
4。new的另类用法
5。申请和释放2维或3维数组的写法和示例
1.string::c_str()
int len=strlen(a.c_str()); //equeal to the bellow 转化为c格式
2。getline和设置宽度setw
#include<iomanip.h>
cout<<setw(30)<<(long)p<<" "<<*p<<" "<<(void*)p<<endl;
while(cin.getline(c,5))
3.c++ 精度问题
float a=2.000030;
cout.setf(ios::fixed);
cout.precision(4); //输出4位有效数字
4.new 新用法:在给定的位置动态创建对象。
char a[10];
然后想在地址a 开始的内存中构造一个 X 类型的对象.
X* px = new (a) X ();
它不申请内存. 所以这个X类型的对象你用完了不要delete px;
只要显式调用它的析构函数:px->X::~X();
5.申请与释放2至3维数组的函数
template<class T>
inline void Intialize2DArray(T **&xxx, long rows, long cols)
{
long i, j;
for (i=0; i<rows; i++)
for (j=0; j<cols; j++)
xxx[i][j] = T(0);
}
template<class T>
void Create2DArray(T **&xxx, long rows, long cols) //add '&'
{
xxx = new T *[rows];
for (long i=0; i<rows; i++)
xxx[i]=new T[cols];
Intialize2DArray(xxx, rows, cols);
}
//删除2维数组时只需2个参数,不需要传数组的第2维大小
template<class T>
void Delete2DArray(T **&xxx, long rows)
{
for(long i=0; i<rows; i++)
delete []xxx[i];
delete []xxx;
xxx=0;
}
template<class T>
void Create3DArray(T ***&xxx, long n1, long n2, long n3)
{
xxx = new T **[n1];
for (long i=0; i<n1; i++)
{
Create2DArray(xxx[i], n2, n3);
Intialize2DArray(xxx[i], n2, n3);
}
}
//删除3维数组时只需3个参数,不需要传数组的第3维大小
template<class T>
void Delete3DArray(T ***&xxx, long n1, long n2)
{
for (long i=0; i<n1; i++)
Delete2DArray(xxx[i], n2);
delete []xxx;
xxx=0;
}
举例:使用3维数组
int n1 = 100;
int n2 = 100;
int n3 = 100;
float ***array_3D;
Create3DArray(array_3D, n1, n2, n3);
...//use the 3d array in form "array_3D[i][j][k]"
Delete3DArray(array_3D, n1, n2);