PTA乙级 (1059 C语言竞赛 (20分)(map.find()、vector中的find))
一、vector中的find
注意find不属于vector的成员,而存在于算法中,应加上头文件#include <algorithm>
1 #include <vector> 2 #include <algorithm> 3 #include <iostream> 4 using namespace std; 5 int main( ) 6 { 7 vector<int> L; 8 L.push_back( 1 ); 9 L.push_back( 2 ); 10 L.push_back( 3 ); 11 L.push_back( 4 ); 12 L.push_back( 5 ); 13 vector<int>::iterator result = find( L.begin( ), L.end( ), 3 ); //查找3 14 if ( result == L.end( ) ) 15 cout << "No" << endl; 16 else 17 cout << "Yes" << endl; 18 }
二、map.find()和map.count()方法
使用find,返回的是被查找元素的位置,没有则返回map.end();
使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。注意,map中不存在相同元素,所以返回值只能是1或0.
1 // map::find 2 #include <iostream> 3 #include <map> 4 5 int main () 6 { 7 std::map<char,int> mymap; 8 std::map<char,int>::iterator it; 9 10 mymap['a']=50; 11 mymap['b']=100; 12 mymap['c']=150; 13 mymap['d']=200; 14 15 it = mymap.find('b'); 16 if (it != mymap.end()) 17 mymap.erase (it); 18 19 // print content: 20 std::cout << "elements in mymap:" << '\n'; 21 std::cout << "a => " << mymap.find('a')->second << '\n'; 22 std::cout << "c => " << mymap.find('c')->second << '\n'; 23 std::cout << "d => " << mymap.find('d')->second << '\n'; 24 25 return 0; 26 }
1 #include<string> 2 #include<cstring> 3 #include<iostream> 4 #include<map> 5 #include<algorithm> 6 using namespace std; 7 int main(){ 8 map<string,int> mp; 9 mp.insert(make_pair("a",1)); 10 mp.insert(make_pair("b",2)); 11 map<string,int>::iterator it; 12 cout<<mp.count("a")<<endl; 13 mp.insert(make_pair("a",2)); 14 it=mp.find("a"); 15 if(it==mp.end()) cout<<"No!"<<endl; 16 else cout<<it->second<<endl; 17 cout<<mp.count("a")<<endl; 18 return 0; 19 }
三、1059 C语言竞赛 (20分)
https://pintia.cn/problem-sets/994805260223102976/problems/994805269828059136
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <cmath> 6 #include <algorithm> 7 #include <vector> 8 #include <map> 9 bool is_prime(int a) 10 { 11 int i; 12 for(i=2;i<=(int)(sqrt(a));i++) 13 { 14 if(a%i==0) return false; 15 } 16 if(i>(int)(sqrt(a))) return true; 17 } 18 using namespace std; 19 int main() 20 { 21 int n,k; 22 string str; 23 bool flag[10002]={false}; 24 cin>>n; 25 map<string,int> mp; 26 for(int i=1;i<=n;i++) 27 { 28 cin>>str; 29 mp[str]=i; 30 flag[i]=false; 31 } 32 cin>>k; 33 for(int i=0;i<k;i++) 34 { 35 cin>>str; 36 if(mp.find(str)!=mp.end()) 37 { 38 if(flag[mp[str]]==true) cout<<str<<": Checked\n"; 39 else{ 40 flag[mp[str]]=true; 41 if(mp[str]==1) cout<<str<<": Mystery Award\n"; 42 else if(is_prime(mp[str])) cout<<str<<": Minion\n"; 43 else cout<<str<<": Chocolate\n"; 44 } 45 } 46 else cout<<str<<": Are you kidding?\n"; 47 } 48 return 0; 49 }
天晴了,起飞吧