每日编程中遇到任何疑问、意见、建议请公众号留言或加入每日编程群聊739635399
给出一系列字符串及其对应id,要求找出某个字符串对应的id。
输入n+1行,第一行输入字符串个数,接下来输入n行,每行输入字符串及对应的id。
最后输入其中的一个字符串,输出该字符串对应的id。
输入格式:
数据的条数
输入每条数据的字符串和对应的id
要查询的字符串
输出格式:
对应的id输入样例:
5boring 5interesting 8hello 4world 2test 9world
输出样例:
word对应的id是2
通过结构体数组来存储各个字符串以及对应的id,字符串采用string类型,调用string对象的compare()方法来进行字符串的匹配,查找对应的ID。
(2)代码实现:
#includeusingnamespacestd;typedefstruct {int id;string str;} dic;intmain(void){int n;cout << "请输入数据条数:" << endl;cin >> n; dic data[n];cout << "请输入每条数据的字符串和对应id:" << endl;for (int i = 0; i < n; i++) {cin >> data[i].str;cin >> data[i].id; }cout << "请输入要查询的字符串:" << endl;string str;cin >> str;int result = -1;for (int i = 0; i < n; i++) {if (data[i].str.compare(str) == 0) { result = i;break; } }if (result != -1) {cout << data[result].str << "对应的id是" << data[result].id << endl; } else {cout << "不存在该字符串" << endl; }return0;}
输入一组学生的成绩,以及一个给定区间,输出区间中成绩最高的学生的排名和成绩最低的学生排名。输入格式:
输入成绩的条数
输入成绩(以空格隔开)
输入要查询成绩的区间【m,n】m,n以空格隔开
输出格式:
输出最高排名和最低排名输入样例:
1075 82 67 88 90 56 43 95 70 3260 90
输出样例:
2 7
