C++ Vector部分用法记录
vector< int >和vector< char >用法类似
在对链表进行操作时,一种常用的技巧是添加一个哑节点(dummy),它的 next 指针指向链表的头节点。这样一来,就不需要对头节点进行特殊的判断了。
#include <vector>
vector<int>vec;
vec.size();//表示vec容量大小
vec.push_back();//向向量末尾插入数据
vec.begin();//指向当前容器的起始位置
vec.end();//指向当前容器末尾位置的下一个位置
vec.front();//返回当前容器起始位置的引用
vec.back();//返回当前容器末尾位置的引用
//用迭代器访问vector
vector<int>::iterator v = vec.begin();
while (v!=vec.end()){
cout<<*v<<endl;
v++;
}
vector<int> fx(vector<int> &nums){
vector<int> another;
for (int num:nums){//遍历
//对num进行一系列运算
}
}
//将answer中的值复制到nums中
nums.assign(answer.begin(),answer.end());
//返回一个vector数组
return vector<int>{-1,-1};
//求string字符串的长度
int l=s.length();
//初始化一个链表指向某链表头结点
vector<ListNode*> A={head};
while (A.back()->next != NULL)//当其指向非空时,将该元素添加到链表中
A.push_back(A.back()->next);
//快慢指针找中间节点
ListNode* MiddleNode(ListNode * head){
ListNode* slow=head,*fast=head;
for (fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
//插入一个哑结点
ListNode* dummy = new ListNode(0,head);
ListNode* fast = head;
ListNode* slow = dummy;
...................
ListNode* ans = dummy -> next;
delete dummy;