Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) std::vector

 

STL container for storing any data type.

 

Use a std::vector instead of an array [1-4]. You can also create 2-dimensional vectors (or more dimensions).

 

Advantages of a vector over an array are:

* They allocate memory from the free space when increasing in size

* They are NOT a pointer in disguise [3].

* They can increase/decrease in size run-time.

* They can do range checking (using at())

 

 

 

#include <vector>

 

const int size = 100;

std::vector<int> v(size);

for (int i=0; i!=size; ++i) v[i]=i;

 

 

std::vector code snippets

 

Note that among these are also more general container code snippets.

 

0.              Append two std::vectors, Append

1.              Append, append two std::vectors

2.              Convert Matrix<X> to Matrix<Y>, ConvertMatrix

3.              Convert std::vector<std::vector<X> > to std::vector<std::vector<Y> >, ConvertMatrix

4.              Convert two 2D std::vector<X> to 2D std::vector<Y>, ConvertMatrix

5.              ConvertMatrix, convert Matrix<X> to Matrix<Y>

6.              ConvertMatrix, convert std::vector<std::vector<X> > to std::vector<std::vector<Y> >

7.              ConvertMatrix, convert two 2D std::vector<X> to 2D std::vector<Y>

8.              CoutVector, std::cout on a std::vector

9.              LoopReader, reading a container looped

10.         RandomShuffle, shuffle a std::vector to a random order

11.         Reading a container looped, LoopReader

12.         Save a container to file, SaveContainer

13.         SaveContainer, save a container to file

14.         Shuffle a std::vector to a random order, RandomShuffle

15.         Sort a std::vector, SortVector

16.         SortVector, sort a std::vector

17.         std::cout on a std::vector, CoutVector

 

External links

* SGI: http://www.sgi.com/tech/stl/Vector.html

* CodePedia: http://www.codepedia.com/1/CppVector

References

 

[1] Bjarne Stroustrup. The C++ Programming Language (3rd edition).

    ISBN: 0-201-88954-4

[2] Herb Sutter and Andrei Alexandrescu. C++ coding standards:

    101 rules, guidelines, and best practices.

    ISBN: 0-32-111358-6, chapter 76: 'Use vector by default.

    Otherwise, choose an appropriate container',

    chapter 77: 'Use vector and string instead of arrays.'

[3] Marshall Cline,Greg Lomow and Mike Girou. C++ FAQs.

    ISBN: 0-201-3098301, FAQ 28.02: 'Are arrays good or evil?'

    (Answer: 'Arrays are evil').

[4] Bjarne Stroustrup. The C++ Programming Language (3rd edition).

    ISBN: 0-201-88954-4 Chapter C.14.11 'Prefer vector over array'.

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.