Last night, I was reading up on the STL (Standard Template Library) for C++. That's one area I haven't had much experience yet. Using vectors isn't very hard, but learning the meaning behind them and how to use them properly is a good thing to know. Today in my C++ class, we went over some of that same stuff. We got a nice little crash course in iterators, vectors, and some of the algorithm header functions from the STL. It was a great class. One thing I found particuarly interesting was function pointers. You can pass a function to another function as an argument and use it within that function. An example that uses this is "algorithm"'s for_each function. To use this function, you pass it two iterators and a function to execute. So if I had a function called "printIt" that is implemented as so:
void printIt(int i)
{
cout << i << " ";
}
All this does is print the value passed to it with a space after it. Once you had this implemented, you need to create a vector object and pass the values you want to iterate through to the for_each function:
vector<int> vec;
for(int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), printIt);
This would print out all of the values in the vector using my printIt function. This works because functions are really just pointers to machine instructions for that function. By passing "printIt" to the for_each function, you're telling it where in memory the instructions for that function are so it can use the function. If you want to see the implementation for the for_each function, you can look it up online. It's actually pretty simple, but you need to know templates for it. We actually made our own implementation of it in class both with templates and without.
Anyway, I have to get back to some more programming. I hope this was insightful for someone. I thought it was really interesting. Once I get more done, I'll make another post and share some more.
EDIT: Sorry about the formatting. This was my first try at putting source code in a blog post and I had to edit HTML to do so. In the process, I accidently deleted some of the post. Let me know if something doesn't make sense and I'll clarify!
No comments:
Post a Comment