Thursday, October 7, 2010

C++ - Maps and Vectors

 I have been learning something really exciting this semester. It is a grad course called Object oriented software development using C++. Apart from learning the pillars of object orientation i.e. encapsulation, inheritance and polymorphism, I have got a chance to delve into game programming. It is a challenging domain and I will post some of my animation/game videos sometime soon.
The other day, I was writing some code to familiarize myself with vectors and maps. Here it goes -
#include <iostream>
#include
<map>
#include
<vector>
using std::string;
using std::cout;
using std::endl;
using std::vector;

//Todo: check how to use overloading for 'print' function
void print(std::map
<string,int> &m) {
  std::map
<string,int>::const_iterator it;
  for(it=m.begin();it!=m.end();++it) {
    std::cout << (it)->first << " = " << (it)->second << std::endl; 
  }
}
//Todo: check how to use overloading for 'print' function
void print(vector
<int> v) {
  vector
<int>::const_iterator it;
  for(it=v.begin();it!=v.end();++it) {
    std::cout<< (*it) << std::endl;
  }
}

void initializevec(vector
<int> &vec) {
  for (unsigned int i = 0 ; i < 20; ++i) {
    vec.push_back(i);
    //demonstrates how capacity grows as size of vector increases
    cout << "size = " << vec.size() << " capacity = " << vec.capacity() << endl;
  }
}

int main() {
  cout<< " MAP " << endl;
  std::map
<string,int> mymap;
  mymap["b"] = 1;
  mymap["a"] = 2;
  mymap["c"] = 5;
  mymap["d"] = 3;

  print(mymap);
  cout << "size = " << mymap.size() << endl;

  std::map
<string,int>::iterator it = mymap.find("c");
  cout<< "Deleting 'c' ... " <
  mymap.erase(it);
  print(mymap);
  cout << "size = " << mymap.size() << endl;   
  std::cout << std::endl;

  cout<< " VECTOR " << endl;
  vector
<int> vec;
  initializevec(vec);

  vec.push_back(13);
  print(vec);

  return 0;
}

Compile using -
g++ -W -Wall -Weffc++ -ggdb -O0 filename.cpp

It demonstrates some basic operations of maps and vectors. It was nice to understand how vectors increase their 'capacity' to accommodate new elements.