预备知识:
输入语句
头文件:#include<iostream> 表示1: std::cin 表示2: using namespace std; cin 读取结束条件:enter、space、tab 对结束符的处理:丢掉
存储知识
基本的存储: int、char、string 高级的存储: 其中T指代上述基本的存储类型。 vector<T> var; 基本操作: var.push_back(val);//按顺序存储 var[i];//下标读取 vector<pair<T1,T1>> vpr; //关联容器 例子:(1,2)(2,3)(1,4)类似数组,但更方便 再如(1,‘d’)(2,'dfs')(3,'dafd') 注:pair<T1,T2>仅一对,用vector即可实现多对 基本操作: vpr.push_back(make_pair(a,b));//存储数据 vpr[i].first; vpr[i].second; //下标索引相应的元素,第一个访问T1的数据,第二个访问T2的数据 向量常用初始化方式 **************************** 二维向量初始化,之后使用下标索引即可,因为这里为每个单位分配了内存 void init_vec(vector<vector<int>> vec,int row, int col) { vec.resize(row); //行初始化 for(int i=0;i<row;i++) { vec[i].resize(col); //列初始化 for(int j=0;j<col;j++) { vec[i][j]=0; } } } ****************************
将输入的字符作为字符存储
例子:
输入:123456 (数值)
存储:vector<char> '1','2','3','4','5','6'
不可直接用于数值计算
#include <iostream>
#include <vector>
using namespace std;
int main() {
/************************************************************
*
*将每个数值转化为单个字符,如12345-》‘1’、‘2’、‘3’、‘4’、‘5’、‘6’
*
*************************************************************/
vector<char> str;//**
char cstr;
while ((cstr = cin.get())!='\n') {
if (cstr == ' ') //若结尾为空格,则退出,可省略
break;
str.push_back(cstr);//**
}
for (int i = 0; i <= str.size() - 1; i++)
cout << str[i] << endl;
system("pause");
return 0;
}
将输入的字符作为数值存储
例子:
输入:123456 (数值)
存储:vector<int> 1,2,3,4,5,6
以上数值可用于数值计算
#include <iostream>
#include <vector>
using namespace std;
int main() {
/************************************************************
*
*将每个数值转化为单个字符,如12345-》1、2、3、4、5、6
*
*************************************************************/
//修改
vector<int> str;//**存储为数值
char cstr;
while ((cstr = cin.get())!='\n') {
if (cstr == ' ') //若结尾为空格,则退出,可省略
break;
//修改
str.push_back(cstr-‘0’);//将字符转化为数值
}
for (int i = 0; i <= str.size() - 1; i++)
cout << str[i] << endl;
system("pause");
return 0;
}
存储一对数值
示例:
输入:
5 //5组数据 1 2 2 3 3 4 4 5 5 6
输出:
1 2 2 3 3 4 4 5 5 6
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<pair<int,int>> vpr;//关联容器,int类型可以替换基本类型,相应的下面读取的存储变量也要修改
int fir, sec, N;
cin >> N;
while (N--) {
cin >> fir >> sec;
vpr.push_back(make_pair(fir, sec));//存储组合
}
for (int i = 0; i <= vpr.size() - 1; i++)
cout << vpr[i].first<<" "<< vpr[i].second << endl;
system("pause");
return 0;
}