模拟、查找类
1.Map
map<char, int> myMap = {
{'a', 1}, {'b', 2}, {'c', 3},
{'d', 1}, {'e', 2},{'f', 3},
};
map<int, string> myMap;
for (int i=0 ; i<n ; i++){
int key;
string value;
cin >> key >> value;
myMap[key] = value;
}
//map会默认按键的升序来输出
for (auto it=mymap.begin() ; it != mymap.end() ; it++) {
cout << it->first << ": " << it->second << endl;
}
//如果想要倒序
for (auto it=mymap.rbegin() ; it != mymap.rend() ; it++) {
cout << it->first << ": " << it->second << endl;
}
//只输出第一个
auto it = mymap.begin();
cout << it->first << ' ' << it->second << endl;
2.sort函数
sort
函数是C++标准库 <algorithm>
中的一个函数,用于对容器中的元素进行排序
sort(vec.begin(), vec.end());
//对于数组
sort(arr, arr + n);
默认升序,如果要降序,可以写:
bool compare(int a, int b) {
return a > b; // 降序排序
}
// 对于容器
sort(vec.begin(), vec.end(), compare);
3.C++的函数重载
C++可以定义多个函数具有相同的名称但具有不同的参数列表,编译器根据函数调用时提供的参数来确定调用哪个函数。
4.struct
// 定义一个结构体
struct Person {
string name;
int age;
double height;
};
// 声明结构体变量
Person person1;
person1.name = "Alice";
person1.age = 25;
person1.height = 1.65;
// 访问结构体成员
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Height: " << person1.height << "m" << endl;
// 结构体作为函数参数
void printPersonInfo(Person p) {
cout << "Name: " << p.name << endl;
cout << "Age: " << p.age << endl;
cout << "Height: " << p.height << "m" << endl;
}
printPersonInfo(person1);
// 结构体数组
Person people[3];
people[0] = {"Bob", 30, 1.75};
people[1] = {"Charlie", 35, 1.80};
people[2] = {"David", 40, 1.70};
// 结构体指针
Person* ptrPerson = &person1;
cout << "Name: " << ptrPerson->name << endl;
cout << "Age: " << ptrPerson->age << endl;
cout << "Height: " << ptrPerson->height << "m" << endl;
一个应用:
struct Student{ //结构体定义
int sno;
int grade;
};
bool comp(Student a, Student b){ //类的元素的比较
if (a.grade < b.grade)
return true;
else if (a.grade == b.grade && a.sno <b.sno)
return true;
else
return false;
}
//sort的调用
sort(stu, stu+n, comp);
5.continue和break在for语句中的用法
break
用于提前结束循环。continue
用于跳过当前迭代,直接进入下一次迭代。
6.二分查找
bool bSearch(int n, int x){
int left = 0;
int right = n-1;
while(left <= right){
int mid = (left + right) /2;
if(a[mid] == x)
return true;
else if (a[mid] > x)
right = mid - 1;
else
left = mid + 1;
}
return false;
}
一定要注意,先sort(a,a+n)再二分查找,二分查找的基础是有序数组
7. map函数替换二分查找
int main(){
map <int, int> FindMap;
int n, m;
int arr[100];
while (cin >> n){
for (int i=0 ; i<n ; i++){
cin >> arr[i];
//也就是说,map里是{arr[i], i},前面是键,后面是值
FindMap[arr[i]] = i;
}
cin >> m;
for (int j=0 ; j<m ; j++){
int curr;
cin >> curr;
//FindMap.end()指向最后一个元素的下个位置
if (FindMap.find(curr) == FindMap.end()){
cout << "NO" <<endl;
}else{
cout << "YES" << endl;
}
}
}
return 0;
}