C++ std::vector Primer Tutorial

C++ std::vector Primer Tutorial

C++ std::vector Primer Tutorial

Today we answer a Yahoo Answers question (thanks) to point out an advantage C++ std::vector “container” datatype has over a base array datatype. We use Xcode (on a Mac laptop) as our IDE for this work.

Read more here about std::vector but let’s quote from that same useful link (thanks) where we define std::vector as “sequence containers representing arrays that can change in size”. And that is the essence of today’s first bit of code that reads a very simple text file containing two integer numbers of ranges of numbers between which we find a list of prime numbers.

Are you into syntax? Does “template < class T, class Alloc = allocator > class vector; ” (via that same previous link) turn you on? Hmmmmmmm. Seriously though, syntax is good to learn well, so that you don’t have to look back at books (because, rest assured, they’re looking back at you with a kind of dumb stupid look) or other reference stuff all the time.

So we have a progression … and regression … of code below:

  • main.cpp uses std::vector container with dynamic container resizing (using resize() method)
  • main.cpp uses std::vector container with dynamic container resizing (and using resize() and size() and push_back() methods)
  • main.cpp reverts back to array usage by declaring the array after a first pass of just getting the array size requirement … this doesn’t appear too much more complicated than the way with std::vector but imagine if you had more work to do with the records of the file as you read them (and then you’d have had to reread the file, which is awkward) … (C has malloc and realloc and calloc (and C++ probably can as well)) but the “spirit” of C++ is to use std::vector (methinks)

Any good programming language will have several ways to kill simple cats (so feed your cat fishoil to avoid this) and another approach would be to use a List. Read about some of the debate regarding Lists versus Vectors here.

Enjoy today’s tutorial.

If this was interesting you may be interested in this too.

This entry was posted in eLearning, Tutorials, Xcode and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>