[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppVector

(C++) std::vector

std::vector< [type] > [identifier];
std::vector< [type] > [identifier] ( [initialSize] );
std::vector< [type] > [identifier] ( [initialSize] , [initialValueAllElements] );
std::vector<double> myVector;
std::vector<double> myVector(10);   
std::vector<double> myVector(10, 3.14159265); 


The std::vector is a STL container class that has extended functionality over a plain array.

Use a std::vector instead of a plain 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 (see example below).
  • They are NOT a pointer in disguise [3].
  • They can increase/decrease in size run-time.
  • They can do range checking (using at())

Page overview

Using a vector instead of an array

Code using an array:

const int size = 100;
int myArray[size];
for (int i=0; i<size; ++i) myArray[i]=i;


Same code using a vector:

const int size = 100;
std::vector<int> myArray(size); //Only line that changed
for (int i=0; i<size; ++i) myArray[i]=i;


== Common operations ==

=== Read/write ===
const int myValue = myVector[0]; //Gets value at index 0
const int myValue = myVector.at(0); //Gets value at index 0, does range-check
myVector[0]=10; //Sets value at index 0 to value of 10
myVector.at(0)=10; //Sets value at index 0 to value of 10, does range-check
const int myValue = myVector.first(); //Gets first value (at index 0)
const int myValue = myVector.last(); //Gets last value (at size-1)


=== Change the std::vector's size ===
myVector.resize(10); //Set size to 10
myVector.empty(); //Same as resize(0);
myVector.push(v); //Increase vector's size by one, put v at index 0
myVector.pop(); //Decrease vector's size by one, removing element 0
myVector.push_back(v); //Increase size by one, put v at last index
myVector.pop_back(); //Decrease size by removing last element


=== Using push and push_back often === A vector has a certain amount of memory allocated for a certain amount of elements. When using push and push_back often, sometimes this reserved space is not enough. Then new memory is allocated and the old elements are copied to the new memory space. So, to increase speed, you could reserve this memory space at the start of your program, saving you these copies. This does not resize your vector.

myVector.reserve(10000); //Reserves storage space for 10000 elements


== Range checking ==

Unlike an array, a vector can do range checking. Range checking is done by using the at() method instead of the index operator []. The use of it is demonstrated by the program below, which often runs successfully.

  1. include <vector>
int main() { std::vector<double> myVector(10); //myVector[10]=69.69; //ACCESS VIOLATION! Often runs successfully myVector.at(10)=69.69; //Always gives an out-of-range exception }


Read/writing beyond an array's or std::vector's range results in an access violation. For optimal safety AND speed, use e.g. the debugging macro NDEBUG (which is also used for assert):

  1. include <vector>
int main() { std::vector<double> myVector(10);
      1. ifdef NDEBUG
myVector[10]=69.69;
      1. else
myVector.at(10)=69.69;
      1. endif
}


=== Removing elements from a std::vector without changing the element's order ===

Unlike a std::list, it is not easily possible to remove random elements from a std::vector. Here is a code snippet, showing how to use an  ?iterator to do so anyway.
  1. include <iostream>
  2. include <vector>
//Function that removes all indices of myVector //that are equal to myElement void removeElements(std::vector<std::string>& myVector, const std::string& myElement) { std::vector<std::string>::iterator i; while (1) { i = find(myVector.begin(),myVector.end(),myElement); if (i==myVector.end()) break; myVector.erase(i); } } int main () { std::vector<std::string> v; v.push_back("A"); v.push_back("B"); v.push_back("C"); v.push_back("X"); v.push_back("X"); v.push_back("D"); v.push_back("E"); v.push_back("X"); removeElements(v,"X"); const int size = v.size(); for(int i=0; i<size; ++i) { std::cout << i << '\t' << v[i] << std::endl; } }


You can click here from the templated version of this function.

== Two-dimensional vectors ==

Click here.

== Comparing memory use of vector and array ==

See Talkpage for a discussion

The code below shows that the bigger a statically allocated array is, the more stack memory is consumed. When a std::vector is used, its stack consumption is always the same. This is because a std::vector manages a dynamically allocated array, in other words, it manages a pointer. And pointers always take up the same memory consumption, regardless of the amount of memory it points to.

  1. include <iostream>
  2. include <vector>
int main() { const unsigned int smallSize = 10; const unsigned int bigSize = 10000; int smallArray[smallSize]; int bigArray[bigSize]; std::vector<int> smallVector(smallSize); std::vector<int> bigVector(bigSize); std::cout << "Small array: " << sizeof(smallArray) << std::endl; std::cout << "Big array: " << sizeof(bigArray) << std::endl; std::cout << "Small vector: " << sizeof(smallVector) << std::endl; std::cout << "Big vector: " << sizeof(bigVector) << std::endl; }


== Using those 'good old' pointer functions == First: avoid this! Prefer a vector over an array by default [1,2]. The standard states that the elements of a vector must be stored in memory like a plain array.

But IF you have a function using a pointer to an array, e.g.
double sumArray(const double* pArray, const unsigned int& arraySize)
you can still use it with a std::vector! Just call it like:
const double sum = sumArray(myVector.begin(),myVector.size());
However, it would be better to define the 'good old' pointer function to :
double sumVector(const std::vector<double>& myVector)


Alternatives to std::vector

Example functions using std::vector

'vector' links

  • C# (in which it is called an ArrayList)
== Code links ==

Links

== References ==

last edited (February 28, 2007) by bilderbikkel, Number of views: 28209, Current Rev: 43 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.