C++常用操作
数组
输入二维数组
#include <iostream>
#include <vector>
using namespace std;
int main() {
int r = 0, c = 0;
cout << "输出行数 r:";//规定二维数组行数
cin >> r;
cout << "输入列数 c:";//规定二维数组列数
cin >> c;
vector<vector<int>> array(r, vector<int>(c));//定义二维数组
for (int i = 0; i < r; i++)//输入r*c的二维数组
{
for (int j = 0; j < c; j++) {
cin >> array[i][j];
}
}
return 0;
}
链表
创建、初始化并打印链表
#include <iostream>
using namespace std;
struct Node{
int val;
Node* prev;// 上一个节点
Node* next;// 下一个节点
};
class List{
public:
Node * head;
List(){
head = nullptr;
}
void Create(){
Node* p = new Node();
p->val = 0;
p->next = NULL;
head = p;
int n;
cout << "请输入链表的长度:";
cin >> n;
cout << "请输入第 1 个值:";
cin >> p->val;
for(int i = 1;i < n;i++){
Node *q = new Node();
q->next = NULL;
cout << "请输入第 " << i+1 <<" 个值:";
cin >> q->val;
p->next = q; // 连接两个节点
p = q; // 指针指向添加的节点,方便之后添加
}
}
void Output()//输出链表的数据域和指针域
{
if (head == NULL) {
cout << "该表为空表" << endl;
}
Node *current = head;
while (current != NULL) {
cout << current->val << endl;
current = current->next;
}
}
~List(){
}
};
int main() {
List A;
A.Create();
A.Output();
return 0;
}
在pos位置后面插入节点
//在pos位置后面插入一个节点
void ListInsertPos(int pos, int val)
{
Node* newNode = new Node();
newNode->val = val;
newNode->next = NULL;
Node* cur = head;
int i = 0;
while(cur != nullptr && i < pos - 1)
{
i++;
cur = cur->next;
}
Node* tmp = cur->next;
cur->next = newNode;
newNode->next = tmp;
}
删除pos位置节点
void ListDeletePos(int pos)
{
if(head != nullptr && pos == 0)
{
Node* tmp = head;
head = head->next;
delete tmp;
}
else{
int i = 0;
Node* cur = head;
while(cur != nullptr && i < pos - 1)
{
i++;
cur = cur->next;
}
Node* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
}