// Example of some basic STL use // Written by Adam Meadows for CS 141 // stl_example.cc //include the libraries #include #include #include #include //declare what you're going to use using std::cout; using std::endl; using std::vector; using std::string; using std::set; //main function int main(int argc, char **argv) { //first let's make some strings string s1("Hello"); string s2 = "Goodbye"; string s3 = s1 + s2; //now let's look at some cool operations we can use //string addition cout << "String output:" << endl; cout << "s1 = " << s1 << endl; cout << "s2 = " << s2 << endl; cout << "s1 + s2 = " << s1 + s2<< endl; //size function (many more available - check online) cout << "size of s3 = " << s3.size() << endl; cout << endl << endl; //now let's look at vectors vector v1; //adding to vector v1.push_back(2); v1.push_back(4); v1.push_back(1); v1.push_back(3); //here's a couple ways to loop through them cout << "Vector output:" << endl; cout << "Looping using v1[i]: " << endl; for(unsigned int i = 0; i < v1.size(); i++) { cout << "v1[" << i << "] = " << v1[i] << endl; } //end of first for loop cout << endl; //here's an example of using iterators cout << "Looping using an iterator:" << endl; vector::iterator viter; for(viter = v1.begin(); viter != v1.end(); viter++) { cout << "next element = " << *viter << endl; } //end of second for loop cout << endl; // clear function wipes out the vector cout << "Size before clear = " << v1.size() << endl; v1.clear(); cout << "Size after clear = " << v1.size() << endl << endl; //now let's look at sets cout << endl; cout << "Set output:" << endl; set set1; //fill it w/ some stuff cout << "Insterting (2, 4, 1, 3) into set" << endl; set1.insert(2); set1.insert(4); set1.insert(1); set1.insert(3); cout << endl; //size function cout << "Size of set = " << set1.size() << endl << endl; //try to find an element cout << "Looking for 4 in set: "; if(set1.end() != set1.find(4)) cout << "\tFound!" << endl; else cout << "\tNot Found!" << endl; cout << "Looking for 5 in set: "; if(set1.end() != set1.find(5)) cout << "\tFound!" << endl; else cout << "\tNot Found!" << endl; cout << endl << endl;; //loop through it, just like w/ vector cout << "Looping through set:" << endl; set::iterator siter; for(siter = set1.begin(); siter != set1.end(); siter++) { cout << "Next element = " << *siter << endl; } //end of set for loop cout << "Notice the elements are stored sorted" << endl << endl; return 0; } // end of main function