鏈表&string&sort

string相關

string.substr有用法:string.substr(start, length) 其中 start取值範圍爲[0,string.size()]當start 爲string.size()時返回空串,length可省略

數與string的互轉

數轉string: to_string()
string 轉 數:stoi ();stol();stoul();stoll();stod();stof() 及函數原型

  1. int stoi (const string& str, size_t* idx = 0, int base = 10);
  2. long stol (const string& str, size_t* idx = 0, int base = 10);
  3. unsigned long stoul (const string& str, size_t* idx = 0, int base = 10);
  4. long long stoll (const string& str, size_t* idx = 0, int base = 10);
  5. double stod (const string& str, size_t* idx = 0);
  6. float stof (const string& str, size_t* idx = 0);

sort函數

對vector排序使用

  1. sort(vector.begin(),vector.end(),cmp)
  2. sort(vector.begin(),vector.end())

默認的cmp是從小到大 ,也可以自己定義cmp

 bool cmp(const int &a, const int &b)
 {
     return a > b;
 }
 // 此時的話就是定義的從大到小的排序

struct中的構造函數與new的使用

當結構體中定義了構造函數之後需要按照構造函數的方式申請內存

struct ListNode
{
	int val;
	ListNode* next;
	ListNode(int x): val(x), next(NULL){} // 構造函數
};
ListNode *s = new ListNode; // 此時會報錯
ListNode s = ListNode(0); // 需要以這樣的方式聲明一個val爲0的節點

當循環生成節點的時候需要使用new爲節點指針申請內存空間

頭插法生成鏈表演示

//如果結構體是這樣的; 沒有構造函數
struct ListNode
{
	int val;
	ListNode* next;
};
ListNode* head = NULL;
for(int i=0; i<4; i++)
{
	ListNode* temp = new ListNode;
	temp->val = i;
	temp->next = head;
	head = temp;
}
//遍歷得到 3 2 1 0

尾插法生成鏈表演示

//如果結構體是這樣的; 有構造函數
struct ListNode
{
	int val;
	ListNode* next;
	ListNode(int x): val(x), next(NULL){} // 構造函數
};
ListNode* head = new ListNode(0);
ListNode* p = head;
for(int i=0; i<4; i++)
{//在for循環中如果不用new的形式生成新的node
	ListNode* temp = new ListNode(0);
	temp->val = i;
	p->next = temp;
	p = temp;
}
head = head->next;
p->next = NULL;
//遍歷得到 0 1 2 3 

循環中用 ListNode temp(0) 則每次temp都是同一個地址空間,因爲在for循環中每次循環結束存儲空間會被釋放掉,而在下一次循環開始的時候再次定義;並且在循環中每次定義的地址都是同一個地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章