#mastery23 #TC1017

23 1017

Creation and use of vectors in C++

Vector is a template class that is a perfect replacement for the good old C-style arrays. It allows the same natural syntax that is used with plain arrays but offers a series of services that free the C++ programmer from taking care of the allocated memory and help operating consistently on the contained objects.The first step using vector is to include the appropriate header:

Note that the header file name does not have any extension; this is true for all of the Standard Library header files. The second thing to know is that all of the Standard Library lives in the namespace std. This means that you have to resolve the names by prepending std:: to them:

  1. std::vector v; // declares a vector of integers

For small projects, you can bring the entire namespace std into scope by inserting a using directive on top of your cpp file:

  1. using namespace std;
  2. //…
  3. vector v; // no need to prepend std:: any more

This is okay for small projects, as long as you write the using directive in your cpp file. Never write a using directive into a header file! This would bloat the entire namespace std into each and every cpp file that includes that header. For larger projects, it is better to explicitly qualify every name accordingly. I am not a fan of such shortcuts. In this article, I will qualify each name accordingly. I will introduce some typedefs in the examples where appropriate—for better readability.

CC BY 4.0 #mastery23 #TC1017 by Mitzi Hernandez is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.