一、while(cin>>a)的终止
1、Ctrl + Z结束while循环
cin读取函数是从内核缓冲区中读取,遇到文件结束符EOF时会返回0,否则返回cin对象,而Windows下输入"Ctrl + Z"表示读到文件末尾,可在终端结束输入。
以下是输入后:
5
0 10
5 10
20 20
^Z
2、getline()与cin的一些小东西
cin在输入时如果遇见换行符\n会直接跳过,但若是cin>>A,在键盘上输入A后,再输入回车。
内核会将回车转化为换行符’\n‘存储在内核缓冲区内,cin从缓冲区中读取A后,换行符还留在缓冲区中。
getline()可以读取缓冲区内的换行符,所以若执行如下代码:
int A;
cin>>A;
cin.getline()
则会读取缓冲区内的换行符;若想读取到正确的输入,则需要在cin以后,先cin.get(),将滞留的换行符读取,再调用cin.getline(),读入一行内容。
二、sort函数对结构体向量进行排序
博主的题要求按照结构体的第一个int数字递增排序。
1、定义compare函数
碎碎念:不晓得为啥在main函数内部定义compare函数会报错,俺记得以前写代码的时候可以嵌套定义别的函数捏!
(定义compare函数后,直接调用sort函数即可:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 定义内存块结构体
struct MemoryBlock {
int start; // 起始地址
int size; // 大小
};
bool compare(MemoryBlock& a, MemoryBlock& b)
{
return a.start < b.start;
}
int main() {
MemoryBlock temp = { 0,1 };
MemoryBlock temp1 = { 1,2 };
MemoryBlock temp2 = { 3,4 };
vector<MemoryBlock> allocated(3);
allocated.push_back(temp);
allocated.push_back(temp1);
allocated.push_back(temp2);
sort(allocated.begin(), allocated.end(),compare);
}
2、运算符重载:<符号
在结构体内声明重载函数,此时就可直接调用sort函数,而不用再给出compare(因为重载了<符号,而sort默认是递增顺序)。
// 定义内存块结构体
struct MemoryBlock {
int start; // 起始地址
int size; // 大小
bool operator<(const MemoryBlock& other) const {
return start < other.start;
}
};
// 按起始地址排序
sort(allocated.begin(), allocated.end());