lecture9 notes

Insert8 12 isetinsert3 13 14 cout iset contains 15

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: : 1 #include <iostream> 2 #include <set> 3 #include <algorithm> 4 using namespace std; 5 6 int main() { 7 set<int> iset; 8 iset.insert(5); 9 iset.insert(9); 10 iset.insert(1); 11 iset.insert(8); 12 iset.insert(3); 13 14 cout << "iset contains:"; 15 set<int>::iterator it; 16 for(it=iset.begin(); it != iset.end(); it++) 17 cout << " " << *it; 18 cout << endl; 19 20 int searchFor; 21 cin >> searchFor; 22 if(binary_search(iset.begin(), iset.end(), searchFor)) 23 cout << "Found " << searchFor << endl; 24 else 25 cout << "Did not find " << searchFor << endl; 26 27 return 0; 28 } In this example, we create an integer set and insert several integers into it. We then create an iterator corresponding to the set at lines 14 and 15. An iterator is basically a pointer that provides a view of the set. (Most of the other containers also provide iterators.) By using this iterator, we display all the elements in the set and print out iset contains: 1 3 5 8 9. Note that the set automatically sorts its own items. Finally, we ask the user for an integer, search for that integer in the set, and display the result. Here is another example: 1 2 3 #include <iostream> #include <algorithm> using namespace std; 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 void printArray(const int arr, const int len) { for(int i=0; i < len; i++) cout...
View Full Document

This document was uploaded on 03/18/2014 for the course EECS 6.096 at MIT.

Ask a homework question - tutors are online