C常用函数实现

Softmax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//查找最大元素
float max_element(float* src, int count){
float max = src[0];
for (size_t i = 0; i < count; i++)
{
if(src[i] > max)
max = src[i];
}
return max;
}

//对一行进行softmax
void softmax(float *src, float *dst, int count)
{
float max = max_element(src, count);
float denominator = 0.;
for (size_t i = 0; i < count; i++)
{
dst[i] = std::exp(src[i] - max);
denominator += dst[i];
}
for (size_t i = 0; i < count; i++)
{
dst[i] /= denominator;
}
}

去除空格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
void deleteAllMark(string &s, const string &mark)
{
size_t nSize = mark.size();
while(1)
{
size_t pos = s.find(mark); // 尤其是这里
if(pos == string::npos)
{
return;
}

s.erase(pos, nSize);
}
}


char *Trim(char *str)
{
unsigned int uLen = strlen(str);

if(0 == uLen)
{
return str;
}

char *strRet = (char *)malloc(uLen + 1);
memset(strRet, 0, uLen+1);

unsigned int i = 0, j = 0;
for(i=0; i<uLen+1; i++)
{
if(str[i] != ' ')
{
strRet[j++] = str[i];
}
}
strRet[j] = '\0';

return strRet;
}

切片

1
2