Skip to content

Instantly share code, notes, and snippets.

@wfwei
Created October 9, 2013 14:24
Show Gist options
  • Save wfwei/6902146 to your computer and use it in GitHub Desktop.
Save wfwei/6902146 to your computer and use it in GitHub Desktop.
basic operations of c++ containers
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
static int cmp(int a, int b) {
return a > b;
}
void testVector() {
std::vector<int> v1; // declare a vector
for(int i=0; i<10; i++)
v1.push_back(i); // append to tail
v1.pop_back(); // remove the last element
v1[0] = 100; // alter value (by random access)
v1.insert(v1.begin() + 1, 10); // insert somewhere a value
v1.erase(v1.begin()+1); // erase element at the position
v1.erase(v1.begin(), v1.end()-2); // erase elements in an interval
v1.resize(5); // resize vector(add 0 for default)
std::reverse(v1.begin(), v1.end()); // reverse vector
// traverse by random access
for (unsigned int i = 0; i < v1.size(); i++) {
std::cout << v1[i] << "\t";
}
std::cout<<std::endl;
// sort
std::sort(v1.begin(), v1.end());
// sort with a specified compare function
std::sort(v1.begin(), v1.end(), cmp);
// traverse by a iterator
for (std::vector<int>::iterator iter = v1.begin(); iter != v1.end();
iter++) {
std::cout << *iter << "\t";
}
std::cout<<std::endl;
}
void testSet(){
std::set<int> s;
// insert elements, duplicated element will not insert twice
for(int i=0; i<10; i++)
s.insert(i), s.insert(i);
s.erase(2); // erase a key
for(int i=0; i<5; i++){
// search element
std::set<int>::iterator f = s.find(i); // search key
if(f!=s.end()) // if not found, iterator will go to the last
std::cout << " found " << *f << std::endl;
else
std::cout << "not found " << i << std::endl;
}
for(std::set<int>::iterator iter = s.begin(); iter!=s.end(); iter++){
std::cout << *iter << " ";
}
std::cout << std::endl;
s.clear();
}
void testMap(){
std::map<int, int> tree_mp;
for(int key=1; key<10; key++)
tree_mp[key] = key*10; // add key-values
tree_mp.erase(2); // remove by key
// traverse key-values
std::map<int, int>::iterator iter = tree_mp.begin();
while(iter != tree_mp.end()){
std::cout << iter->first << " : " << iter->second << std::endl;
iter ++;
}
for(int key=0; key<5; key++){
std::map<int, int>::iterator f = tree_mp.find(key); // search key
if(f!=tree_mp.end()) //if not found, iterator will go to the last
std::cout << "found " << f->first << " : " << f->second << std::endl;
else
std::cout << "not found " << f->first << " : " << f->second << std::endl;
}
}
int main() {
testVector();
testSet();
testMap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment