代码功能:
将二维向量转成一维数组,查找每一行的最小值并在每一行减去该值,形成新的一维数组,见图像
代码结果:
代码展示:
#include <vector>
#include <iostream>
#include <chrono>
#include <assert.h>
int main(int,char**)
{
std::vector<std::vector<double> >testMatrix={{10,19,8,15},
{10,18,7,17},
{13,16,9,14},
{12,19,8,18}};
int nRows = testMatrix.size();
int nCols = testMatrix[0].size();
for(int i=0;i<nRows;i++){
for(int j=0;j<nCols;j++){
std::cout<<testMatrix[i][j]<<" ";
}
printf("\n");
}
std::vector<double>tmpMat;
tmpMat.resize(16,0);
for(size_t row=0;row<nRows;row++){
for(size_t col=0;col<nCols;col++){
tmpMat[row+nRows*col]=testMatrix[row][col];
}
}
printf("一维向量形式:\n");
//遍历一维向量,向量形式:2 5 9 9 4 11 13 2 14 9 5 10 5 6 7 6
std::cout<<"rows:"<<nRows<<"\n";
std::cout<<"cols:"<<nCols<<"\n";
for(size_t i=0;i<tmpMat.size();i++){
std::cout<<tmpMat[i]<<" ";
}
std::cout<<"\n";
#ifdef VEC
auto start=std::chrono::system_clock::now();
int elementCount=tmpMat.size();
for(int i=0;i<nRows;i++){
double minValue=tmpMat[i];//per row first element
int rowEleLabel=nRows+i; // the row label
while(rowEleLabel<elementCount){
double value=tmpMat[rowEleLabel];
if(value<minValue){
minValue=value;
}
rowEleLabel+=nRows;
}
printf("per row minValue:%.0f\n",minValue);
rowEleLabel=nRows+i;
tmpMat[i]-=minValue;
while (rowEleLabel<elementCount) {
tmpMat[rowEleLabel]-=minValue;
rowEleLabel+=nRows;
}
}
std::cout<<"subtract the minimum value in the row:\n";
for(size_t i=0;i<tmpMat.size();i++){
std::cout<<tmpMat[i]<<" ";
}
std::cout<<"\n";
auto end=std::chrono::system_clock::now();
auto duration=std::chrono::duration_cast<std::chrono::microseconds>(end-start);
std::printf("vector format cost time:%f s\n",double(duration.count()) *std::chrono::microseconds::period::num/std::chrono::microseconds::period::den);
#endif
printf("pointer format\n");
auto start=std::chrono::system_clock::now();
size_t nOfElem=nRows*nCols;
double* tmpArr=(double*)malloc(nOfElem*sizeof (double));
double* tmpArrEnd=tmpArr+nOfElem;
for(size_t row=0;row<nOfElem;row++){
double value=tmpMat[row];
assert(value>=0);
tmpArr[row]=value;
}
for(size_t row=0;row<nRows;row++){
/* find the smallest element in the row */
double* tmpArrTemp = tmpArr + row;
double minValue = *tmpArrTemp;
tmpArrTemp += nRows;
while (tmpArrTemp < tmpArrEnd)
{
double value = *tmpArrTemp;
if (value < minValue)
{
minValue = value;
}
tmpArrTemp += nRows;
}
/* subtract the smallest element from each element of the row */
tmpArrTemp = tmpArr + row;
while (tmpArrTemp < tmpArrEnd)
{
*tmpArrTemp -= minValue;
tmpArrTemp += nRows;
}
}
for(size_t i=0;i<nOfElem;i++){
std::cout<<*tmpArr<<" ";
tmpArr++;
}
std::cout<<"\n";
auto end=std::chrono::system_clock::now();
auto duration=std::chrono::duration_cast<std::chrono::microseconds>(end-start);
std::printf("vector format cost time:%f s\n",double(duration.count()) *std::chrono::microseconds::period::num/std::chrono::microseconds::period::den);
return 0;
}