// STL——vector
#include <vector>
#include <algorithm>
#include <iostream>
#include <typeinfo>
#include <iomanip>
using namespace std;
static void printVec(const vector<int>& a) {
for (auto it : a) {
cout << it << " ";
}
cout << endl;
}
vector<string> sortRule = { "chinese", "math" };
static bool myComp(vector<int> a, vector<int> b) {
/*int youxian = 1; // 10行代码,圈复杂度 2
int qihou = 2;
if (rule[0] == "chinese") {
youxian = 1;
qihou = 2;
}
else {
youxian = 2;
qihou = 1;
}*/
int youxian = sortRule[0] == "chinese" ? 1 : 2; // 2行代码,圈复杂度 0
int qici = sortRule[0] == "chinese" ? 2 : 1;
if (a[1] + a[2] == b[1] + b[2]) {
if (a[youxian] == b[youxian]) {
if (a[qici] == b[qici]) {
return a[0] < b[0];
}
return a[qici] > b[qici];
}
return a[youxian] > b[youxian];
}
return a[1] + a[2] > b[1] + b[2];
}
int main() {
vector<int> vec;
//vector<int> vec(10); // 初始话10个长度,值为0
cout << "type = " << typeid(vector<int>).name() << endl; // 头文件<typeinfo>
if (typeid(vec).name() == typeid(vector<int>).name()) {
cout << "变量类型正确为 vector<int>" << endl << endl;
}
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
vec.resize(10);
vec[4] = 50; // resize后vec[4] 才可以使用
vec[5] = 60;
cout << setw(32);
printVec(vec);
vec.pop_back();
cout << setw(30) << "弹出一个元素:" ;
printVec(vec);
cout << setw(30) << "擦除下标为 2 的元素:";
vec.erase(vec.begin() + 2);
printVec(vec);
cout << setw(30) << "擦除下标 1 - 3 的元素:";
vec.erase(vec.begin() + 1, vec.begin() + 4); // 擦除下标 1 - 3 的元素
printVec(vec);
cout << setw(30) << "在下标2处插入元素:";
vec.insert(vec.begin() + 2, 39);
printVec(vec);
cout << setw(30) << "通过迭代器修改:";
for (vector<int>::iterator it = vec.begin(); it != vec.end(); it++) {
if (*it == 39) {
*it = 100;
}
}
printVec(vec);
// 二维数组排序
//vector < vector<int>> vec2d;
vector<vector<int>> vec2d(2, vector<int>(3));
//vector<vector<int>> vec2d(3, vector<int>());
cout << vec2d.size() << " " << vec2d[0].size() << endl;
cout << vec2d.size() << " " << vec2d.front().size() << endl;
if (vec2d.front().size() == 0) {
cout << "长度为0 " << endl;
}
vector<vector<int>> vecStudents(5, vector<int>(3));
vecStudents = {
{8, 70, 80},
{3, 80, 70},
{2, 80, 70},
{4, 95, 95},
{5, 80, 65}
}; // 学生编号、语文成绩、数学成绩
// 对学生排序,首先按总分排序,其次按 sortRule里的参数依次排序,如果都相等,按学号从小到大排序。
sort(vecStudents.begin(), vecStudents.end(), myComp);
for (auto it : vecStudents) { // 只读迭代器
for (auto it2 : it) {
cout << it2 << " ";
}
cout << it[1] + it[2] << endl;
}
system("pause");
}