New blog location
New blog location
std::vector
#include <iostream> using namespace std; int main() { vector<int> nums; nums.push_back(3); nums.push_back(1); nums.push_back(2); vector<int>::iterator first = nums.begin(); vector<int>::iterator onePastLast = nums.end(); for(vector<int>::iterator i = first; i != onePastLast; i++) { cout << "Next Element is " << *i << endl; } //sorting a vector sort(first,onePastLast); //after sorting 1,2,3 }
size()
member function that returns the size. Vector can be accessed using the indexing operator []
. However using that operatorvec.at(2)
which can throw index out of range exception. C++11 style of traversing a vector is:for(auto& v : vec) { cout << "Element is "<< v << endl; }
empty()
can check if the container is empty. size
provides the size of the container. clear()
removes all items in the container. swap
swaps the contents of two containers.deque<int> q = {1,2,3}; deq.push_front(5); deq.push_back(10); cout << deq[2] << endl;
list<int> lst = {5,2,9}; lst.push_back(6); lst.push_front(10); list<int>::iterator foundLoc = find(lst.begin(), lst.end(), 2); lst.insert(foundLoc,8); //{5,8,2,9} foundLoc++; //iterator points to 9 lst.erase(foundLoc); //removes 9
lst.splice(itr,mylist2,itr_one, itr_two);
array<int 3>a = {3,4,5};
push_back()
or push_front()
.find
takes O(log N) time. insert
function returns a pair of values (pair<set<int>::iterator, bool>ret
).set<int> st; st.insert(3); st.insert(1); st.insert(2); {1,2,3}
multiset
allows duplicate items. Insertion is always successful. For set and multiset, the value of the elements cannot be modified.map<char,int> mymap; mymap.insert(make_pair('a',100)); map<char,int>::iterator it = mymap.begin(); it = mymap.find('a'); //O(log(n)) //printing out: for(it = mymap.begin() ; it != mymap.end(); it++) { cout << (*it).first << "=>" << (*it).second << endl; }
unordered_set<string> myset = {"Red", "Green", "Blue"}; unordered_set<string>::const_iterator it = myset.find("Green"); //Amortized O(1) if(it != myset.end()) //need to check! { cout << "Found " << *it << endl; } vector<string> myvec = {"Teal","Purple"}; myset.insert(myvec.begin(), myvec.end());
unordered_map<char, string> day = {{'S',"Sunday"}, {'M',"Monday"}}; cout << day['S'] << endl; //has no range check cout <<day.at['S'] << endl; //has range check day['W'] = "Wednesday"; //same as inserting. Can modify existing member day.insert(make_pair('T',"Thursday"));
[]
operator.
Comments
Post a Comment