- C++ 矩阵相乘
#include <iostream>
using namespace std;
class Matrix{
float *data;
public:
size_t n,m;
Matrix(size_t r,size_t c):data(new float[r*c]),n(r),m(c){}
~Matrix() {delete[] data;}
float& operator() (size_t x,size_t y){
return data[x*m+y];
}
float operator() (size_t x,size_t y) const{
return data[x*m+y];
}
};
float dot(const Matrix &a,const Matrix& b) {
Matrix c(a.n,b.m);
for (size_t i=0;i<a.n;++i)
for (size_t j=0;j<b.m;++j){
float s = 0;
for (size_t k=0;k<a.m;++k)
s += a(i,k) * b(k,j);
c(i,j) = s;
}
return c(0,0);
}
void fill_rand(Matrix &a){
for (size_t i=0;i<a.n;++i){
for (size_t j = 0;j<a.m;++j)
a(i,j) = rand() / static_cast<float>(RAND_MAX) * 2 - 1;
}
}
int main(){
srand((unsigned)time(NULL));
const int n = 100,p = 200 , m = 50, T = 100;
Matrix a(n,p),b(p,m);
fill_rand(a);
fill_rand(b);
auto st = chrono::system_clock::now();
float s = 0;
for (int i = 0; i < T; ++i) {
s += dot(a, b);
}
auto ed = chrono::system_clock::now();
chrono::duration<double> diff = ed-st;
cerr << s << endl;
cout << T << " loops. average " << diff.count() * 1e6 / T << "us" << endl;
}
335.764
100 loops. average 10071.3us
- C++实现可变长度的动态数组
#include <iostream>
#include <cstring>
using namespace std;
class CArray
{
int size;
int *ptr;
public:
CArray(int s = 0);
CArray(CArray & a);
~CArray();
void push_back(int v);
CArray& operator = (const CArray &a);
int length() const{return size;}
int &operator[](int i)
{
return ptr[i];
};
};
CArray::CArray(int s) : size(s)
{
if(s == 0)
ptr = NULL;
else
ptr = new int[s];
}
CArray::CArray(CArray & a)
{
if(!a.ptr){
ptr = NULL;
size = 0;
return;
}
ptr = new int[a.size];
memcpy(ptr,a.ptr, sizeof(int) * a.size);
size = a.size;
}
CArray::~CArray() {
if(ptr) delete[] ptr;
}
CArray& CArray::operator=(const CArray &a) {
if(ptr == a.ptr)
return *this;
if (a.ptr == NULL){
if (ptr)
delete[] ptr;
ptr = NULL;
size = 0;
return *this;
}
if (size < a.size){
if(ptr)
delete[] ptr;
ptr = new int[a.size];
}
memcpy(ptr,a.ptr, sizeof(int)*a.size);
size = a.size;
return *this;
}
void CArray::push_back(int v) {
if(ptr){
int* tmpPtr = new int[size + 1];
memcpy(tmpPtr,ptr, sizeof(int) * size);
delete[] ptr;
ptr = tmpPtr;
}
else
ptr = new int[1];
ptr[size++] = v;
}
int main(){
CArray a;
for(int i=0; i<5 ; ++i)
a.push_back(i);
CArray a2,a3;
a2 = a;
for(int i = 0;i < a.length(); ++i)
cout << a2[i] << " ";
a2 = a3;
for(int i=0;i<a2.length();++i)
cout << a2[i] << " ";
cout << endl;
a[3] = 100;
CArray a4(a);
for(int i = 0;i<a4.length(); ++i)
cout << a4[i] << " ";
return 0;
}
0 1 2 3 4
0 1 2 100 4
[]是双目运算符,有两个操作数,一个在里面,一个在外面。表达式 a[i] 等价于 a.operator。按照[]原有的特性,a[i]应该能够作为左值使用,因此 operator[] 函数应该返回引用。