|
3驿站币
// main.cpp
#include "Sort.h"
int main(int argv, char *argc[])
{
// double *pDouble = new double[]{4.4, 3.5,86.4,34.1,45.9}; // 程序崩溃
double *pDouble = new double[5]{4.4, 3.5, 86.4, 34.1, 45.9}; // 程序正确
std::cout << "double type:" << std::endl;
Print(pDouble, 5);
std::cout << std::endl << "double type sort:" << std::endl;
Sort(pDouble, 5);
Print(pDouble, 5);
delete[] pDouble;
system("pause");
return 0;
}
// Sort.h
#ifndef SORT_H
#define SORT_H
#include <iostream>
#define UINT unsigned int
template<typename T>
void Sort(T *pArray, UINT nSize);
template<typename T>
void Print(T *pArray, UINT nSize);
/////////////////////////////////////////////////////////////
template<typename T>
void Sort(T *pArray, UINT nSize)
{
if(!pArray || nSize < 1)return;
for(UINT nCount = 1; nCount < nSize; nCount++)
{
for(UINT nIndex = 0; nIndex < nSize - nCount; nIndex++)
{
if(*(pArray + nIndex) > *(pArray + nIndex + 1))
{
T temp = *(pArray + nIndex);
*(pArray + nIndex) = *(pArray + nIndex + 1);
*(pArray + nIndex + 1) = temp;
}
}
}
}
template<typename T>
void Print(T *pArray, UINT nSize)
{
if(!pArray || nSize < 1)return;
for(UINT nIndex = 0; nIndex < nSize; nIndex++)
std::cout << pArray[nIndex] << "\t";
}
#endif // SORT_H |
最佳答案
查看完整内容
我真是第一次见这种 new 的用法,编译是通过了,不过访问数组中的元素的时候直接崩溃了!
貌似内存模型有问题,最好还是按照标准的做法吧
上一篇: 想了解一下,公司里一般用哪个IDE开发C++项目软件?下一篇: 求助程序无法编译到C:\Windows\System32该何解决?
|