[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppVector
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:
Same code using a vector:
== Common operations ==
=== Read/write ===
=== Change the std::vector's size ===
=== 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.
== 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.
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):
=== 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.
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.
== 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.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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
- Most common operations
- Read/write
- Change the std::vector's size
- Using push and push_back often
- Range checking
- Removing elements from a std::vector without changing the order of elements
- 2-dimensional vectors
- Comparing memory use of vector and array
- Using those 'good old' pointer functions
- Alternatives to std::vector
- Code links
- References
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.
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 }
- include <vector>
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):
int main() { std::vector<double> myVector(10);
- include <vector>
myVector[10]=69.69;
- ifdef NDEBUG
myVector.at(10)=69.69;
- else
}
- 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.
//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; } }
- include <iostream>
- include <vector>
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.
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; }
- include <iostream>
- include <vector>
== 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
- If you do not need use resizing at run-time, the Boost C++ Library supplies an boost::array class which lacks the overhead due to this
- If you want to perform mathematical operations on a sequence of values, you might want to use a std::valarray.
Example functions using std::vector
'vector' links
- C# (in which it is called an ArrayList)
- ::, scope operator
- <<, stream out operator
- #include
- assert
- char
- const
- cout
- endl
- iostream
- #include
- int
- main
- return
- scope operator, ::
- std
- stream out operator, <<
Links
== 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'.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
