二进制求和
在写的过程中学到的知识
①atoi() 和 stoi()的区别
atoi()的参数是const char*
stoi()的参数是const string*
调用c_str()可以将string转换成const char*
一、stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的话则会runtime error!
二、atoi()不会做范围检查,如果超出范围的话,超出上界,则输出上界,超出下界,则输出下界;
using namespace std;
int main()
{
string s1 = "214748666666663", s2 = "-21474836488";
cout << stoi(s1) << endl; //error
cout << stoi(s2) << endl; //error
cout << atoi(s3.c_str()) << endl; //2147483647
cout << atoi(s4.c_str()) << endl; //-2147483648
return 0;
}
②string的数值转换
string和数值转换 | |
---|---|
to_string(val) | 把val转换成string |
stoi(s,p,b) | 把字符串s从p开始转换成b进制的int |
stol(s,p,b) | long |
stoul(s,p,b) | unsigned long |
stoll(s,p,b) | long long |
stoull(s,p,b) | unsigned long long |
stof(s,p) | float |
stod(s,p) | double |
stold(s,p) | long double |
③位运算
一、<<向左位移
11<<1 == 11*2;
11<<1 == 22 从二进制看 00001011<<1 == 00010110
二、>>向右位移
10>>1 == 10/2;
10>>1 == 5 从二进制看00001011 >> 1 == 00000101
三、^异或
作用一、交换整数a = 9;
b = 11;
a = a^b; 1001^1011 = 0010 //此时的a相当于排斥区
b = b^a; 1011^0010 = 1001 //此时的b和排斥区异或 变成原来的a
a = a^b; 0010^1001 = 1011 //此时的a为排斥去和现在的b(原来的a)异或 变成原来的b
2018/6/21
四、string类的insert
string的成员函数insert有以下多种重载:
string &insert(int p0, const char *s);——在p0位置插入字符串s
string &insert(int p0, const char *s, int n);——在p0位置插入字符串s的前n个字符
string &insert(int p0,const string &s);——在p0位置插入字符串s
string &insert(int p0,const string &s, int pos, int n);——在p0位置插入字符串s从pos开始的连续n个字符
string &insert(int p0, int n, char c);//在p0处插入n个字符c
iterator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置
void insert(iterator it, const_iterator first, const_iteratorlast);//在it处插入从first开始至last-1的所有字符
void insert(iterator it, int n, char c);//在it处插入n个字符c
(红色字体因为我对迭代器还不是很理解)
五、string类的erase
(1)erase(pos,n) 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position) 删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last) 删除从first到last之间的字符(first和last都是迭代器)
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str ("This is an example phrase.");
string::iterator it;
// 第(1)种用法
str.erase (10,8);
cout << str << endl; // "This is an phrase."
// 第(2)种用法
it=str.begin()+9;
str.erase (it);
cout << str << endl; // "This is a phrase."
// 第(3)种用法
str.erase (str.begin()+5, str.end()-7);
cout << str << endl; // "This phrase."
return 0;
}
报错
double free or corruption (out): 0x0000000002540130 ***
1. 内存重复释放,看程序中是否释放了两次空间(一般不会是这种情况,毕竟。。太明显)
2. 内存越界。(大部分是这种情况,如果你使用了数组,或者开辟了空间,但是在循环的时候越界了,就会出现这种情况)
3.也是我在写Leetcode的时候遇到的变态恶心脑残问题 就是
string addBinary(string a, string b){}
如果用a来继续作为容器 那么就会报这个错误,解决方法是在string一个变量 充当容器
目前理解是数组越界
2018/6/23