#include <iostream> #include <set> #include <vector> using namespace std; int main() { set<int> setInt; vector<int> ivec; for(vector<int>::size_type i = 0; i != 11; ++i) ivec.push_back(i); setInt.insert(ivec.begin(), ivec.end()); setInt.insert(11); set<int>::iterator itor1 = setInt.find(9);// 这个也对,为什么const类型的键值可以用非const的迭代器????? set<int>::const_iterator itor2 = setInt.find(10); if(itor1 != setInt.end()) cout << *itor1 << endl; /* *itor1 = 12; //error:keys in a set are read-only 正如不能修改mao中元素的键部分一样,set中的键也是const,在获取迭代器后只能对其进行读操作 */ if(itor2 != setInt.end()) cout << *itor2 << endl; system("pause"); return 0; }
1 #include <iostream> 2 #include <string> 3 #include <utility> 4 #include <vector> 5 #include <set> 6 #include <map> 7 8 using namespace std; 9 10 void restricted_wc( vector<string> strVec, map<string, int> &wordCount ) 11 { 12 // create a set of excluded words 13 set<string> excluded; 14 for ( vector<string>::iterator it = strVec.begin(); it != strVec.end(); ++it ) 15 { 16 excluded.insert( *it ); 17 } 18 19 string word; 20 cout << " Input some words to count the words in wordCount(map) ( ctrl + z to end): " 21 << endl; 22 cin.clear(); 23 while ( cin >> word ) 24 { 25 if ( !excluded.count( word ) ) 26 ++wordCount[ word ]; 27 } 28 } 29 30 int main(int argc, char* argv[]) 31 { 32 cout << " Input some words to vector<string> excluded ( ctrl + z to end): " << endl; 33 vector<string> excludedVec; 34 string excludedWord; 35 while ( cin >> excludedWord ) 36 excludedVec.push_back( excludedWord ); 37 38 // use restricted_wc() 39 map< string, int > wordCount; 40 restricted_wc( excludedVec, wordCount ); 41 42 // show out the map:wordCount 43 cout << " Show out the map:wordCount: " << endl; 44 for ( map< string, int >::iterator it = wordCount.begin(); it != wordCount.end(); ++it ) 45 { 46 cout << " The word '" << (*it).first << "' appears for " << (*it).second << " times. " << endl; 47 } 48 49 system("pause"); 50 return 0; 51 }