Marilag Ang Malaya

Sunday, February 8, 2009

From C pointers to C++ iterators

Yesterday, we discussed C++ vectors as one of the ways to improve the representation of an C array. C++ iterators allow easy access to elements in a vector safely. However, one must not mistake an iterator to be a pointer, even if it acts like one. Additionally, your vanilla pointers still exist in C++. Don't forget to put #include <vector>
std::vector<int> grades;   // dynamically-sized vector

// push items into the vector
grades.push_back(grade);
...

for (std::vector<int>::iterator grade_itr=grades.begin();
grade_itr < grades.end();
grade_itr++)
std::cout << (*grade_ptr);

Labels: , , ,

Saturday, February 7, 2009

From C arrays to C++ vectors

The C++ STL (Standard Template Library) includes some very useful templates. The main idea behind STL is to re-use some of the best implementations of the most common data structures, such as queues, lists, stacks. One of these implementations is the C++ vector.

In C, we could declare an array of integers like this:
int grades[MAX_SIZE];
This statement will still work with C++, and is still valid. However, a more "C++"-centric way of doing the same thing would be to use vectors:
vector<int> grades(MAX_SIZE);
You can still access each element using:
grades[i]
but now you can use STLĀ vector functions.

Labels: , , , ,