Learn Some C++0x Part 1: auto Your Way To Victory

So the C++0x standard has been around for quite some time now, and a lot of people still haven’t really learned of its magical features. With this series, I will be going over some of the major new features and how they are awesome.

So I’m sure that many of you are familiar with how iterators work in your usual C++03 standard, which goes something along the lines of

std::map<char, int> m;
//stuff
for(std::map<char, int>::iterator it = m.begin(); it != m.end(); it++){
	//win
}

But that can get tiring to write, especially when you have something like std::map<std::string, std::vector<double>> magic. This is where auto comes into play.

On a simple level, auto is simply a way of letting the compiler decide the type of something for you. It may be as simple as something like

auto ulVal = 5UL;	//unsigned long
auto iVal = 17;		//int

Or it can save you a lot of time with iterators and complex types:

std::map<std::string, std::vector<double>> magic;
auto it = magic.begin();	//automatically assigns it to be of type std::map<std::string, std::vector<double>>::iterator because magic.begin() has a well defined return type

If your compiler is giving you an error because of auto, it is probably because it has no idea what kind of type your variable should be assigned. Otherwise, you should probably look up the error code that the compiler spits out and find out what could possibly be messing with you.

This entry was posted in C++, Code, Computer Science, Tutorial. Bookmark the permalink.

Leave a comment