c/c++的常用函数和STL使用

一个超好用的c++网站:http://www.cplusplus.com/reference/string/string/erase/

一、函数头中包含的函数

1.qsort函数对数组、结构体等进行排序

#include <stdlib.h>//必须用stdlib.h,没用.h不用namespace不行

参数:1待排序数组首地址 2数组中待排序元素数量 3各元素的占用空间大小 4指向函数的指针,用于确定排序的顺序

eg:

(1)重写cmp,固定参数,变化的只是比较内容

int cmp(const void *a,const void *b){
return (*(XianDuan*)b).xd_num - (*(XianDuan*)a).xd_num;

}

此处为降序,后者大于前者时,交换位置;a-b为升序

此处(*(XianDuan*)b).xd_num进行强转时,最前面的*不能丢,因为这里用的是指针而非引用,*b表示访问其值,另外:使用void* (void指针)类型,在给指针赋值时,必须把void指针强制转换为所需要类型的指针以保证赋值的正常进行。(void*见:https://www.cnblogs.com/sybil-hxl/p/10422649.html

(2)调用qsort函数

qsort(xd,num,sizeof(struct XianDuan),cmp);

2.使用freopen输入重定向,输入数据将从in.txt文件中读取

freopen("G:/in.txt","r",stdin); 

必须使用using namespace std;否则不能使用

3.C++的char数组与string对象相互转化

char t[100];
strcpy(t, s2.c_str());//函数头<string.h>或<cstdlib>

由于strtok方法参数只能是char[]和char*必须转化

参考:https://www.cnblogs.com/fnlingnzb-learner/p/6369234.html

4.int和string转化

long int strtol (const char* str, char** endptr, int base);
str:C-string beginning with the representation of an integral number.char型数组
endptr:
Reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.
base:
Numerical base (radix) that determines the valid characters and their interpretation.
If this is 0, the base used is determined by the format in the sequence (see above).

int len = strtol((v1[i].substr(t1+1,t2-t1-1)).c_str(),NULL,0);//字符串转为long int类型,函数头<cstdlib>

由于vc6.0实在太难用,只支持86%的C++,stoi等函数都不能用,只能用这个凑合。java多简单。

5.char转为string

这个,找不到好办法??

二、string类的函数

1.string& erase (size_t pos = 0, size_t len = npos);

pos:

Position of the first character to be erased.
If this is greater than the string length, it throws out_of_range.
Note: The first character in str is denoted by a value of 0 (not 1).
len:

Number of characters to erase (if the string is shorter, as many characters as possible are erased).
A value of string::npos indicates all characters until the end of the string.

2.size_t pos1 = s.find(";",index);

每次使用find函数时,不要忘记第二个参数(开始查询下标),这个每一轮查询都不一样,这个是查完整个字符串的保证

size_t,本质是unsigned int,用typedef起了个名

3.s.substr(pos1,pos2-pos1);

第一个参数是起始位置,第二个参数是长度

1.qsort函数对数组、结构体等进行排序

#include <stdlib.h>//必须用stdlib.h,没用.h不用namespace不行

参数:1待排序数组首地址 2数组中待排序元素数量 3各元素的占用空间大小 4指向函数的指针,用于确定排序的顺序

eg:

(1)重写cmp,固定参数,变化的只是比较内容

int cmp(const void *a,const void *b){
return (*(XianDuan*)b).xd_num - (*(XianDuan*)a).xd_num;

}

此处为降序,后者大于前者时,交换位置;a-b为升序

此处(*(XianDuan*)b).xd_num进行强转时,最前面的*不能丢,因为这里用的是指针而非引用,*b表示访问其值,另外:使用void* (void指针)类型,在给指针赋值时,必须把void指针强制转换为所需要类型的指针以保证赋值的正常进行。(void*见:https://www.cnblogs.com/sybil-hxl/p/10422649.html

(2)调用qsort函数

qsort(xd,num,sizeof(struct XianDuan),cmp);

2.使用freopen输入重定向,输入数据将从in.txt文件中读取

freopen("G:/in.txt","r",stdin); 

必须使用using namespace std;否则不能使用

 

猜你喜欢

转载自www.cnblogs.com/sybil-hxl/p/10493363.html