(C++) std::vector
June 10, 2019 · View on GitHub
STL container for storing instances of any data type.
Example: create a std::vector
//Create an empty std::vector
std::vector<int> v;
//Create a std::vector with size 10, all elements zero
std::vector<int> v(10);
//Create a std::vector with size 10, all elements 42
std::vector<int> v(10, 42);
//Create a std::vector with one element: 10
std::vector<int> v{10};
std::vector<int> v = {10};
//Create a std::vector with two elements: 10 and 42
std::vector<int> v{10, 42};
std::vector<int> v = {10, 42};
Example: create a std::vector for another STL container
//Create a copy of a std::vector
std::vector<int> v(some_other_vector);
std::vector<int> v = some_other_vector; //Calls copy constructor, like above
//Create a std::vector with same elements as an STL container
std::vector<int> v(std::begin(some_container), std::end(some_container));
Example: convert argv to std::vector<std::string>
Because you can create a std::vector from two iterators, you can
use argc and argv to get the
command-line arguments in a std::vector<std::string>:
#include <cassert>
#include <string>
#include <vector>
int main(int argc, char* argv[])
{
const std::vector<std::string> args(argv, argv + argc);
assert(argc == static_cast<int>(args.size()));
assert(argv[0] == args[0]);
}
Example: sorting a std::vector
#include <algorithm>
#include <cassert>
#include <vector>
int main()
{
std::vector<int> v = {4, 2, 3, 1};
std::sort(std::begin(v), std::end(v));
const std::vector<int> expected = {1, 2, 3, 4};
assert(v == expected);
}
std::vector versus plain array
Advantages of a std::vector over an array are:
- std::vector allocates memory from the free space when increasing in size
- std::vector is not a pointer in disguise [3]
- std::vector can increase/decrease in size run-time
- std::vector can do range checking (using at())
There is an urban myth that arrays are faster. See this benchmark of array versus std::vector to see they are equally fast.
The erase-remove idiom
Calling std::remove to remove a certain value from a std::vector does not change a std::vector its size * std::remove does return an iterator to where the removed elements are put. This iterator can be used to call std::vector its 'erase' member function. These two operations are called the erase-remove idiom.
Use the erase-remove idiom the really remove a value from a std::vector.
std::vector code snippets
Note that among these are also more general container code snippets.
- AddOne: benchmark of adding one to all elements of a std::vector
- AllAboutEqual, check if all doubles in a std::vector are about equal
- Append two std::vectors, Append
- Append, append two std::vectors
- Check if all doubles in a std::vector are about equal, AllAboutEqual
- CreateVector, create a std::vector from three values
- Convert Matrix<X> to Matrix<Y>, ConvertMatrix
- Convert std::vector<std::vector<X> > to std::vector<std::vector<Y> >, ConvertMatrix
- Convert two 2D std::vector<X> to 2D std::vector<Y>, ConvertMatrix
- ConvertMatrix, convert Matrix<X> to Matrix<Y>
- ConvertMatrix, convert std::vector<std::vector<X> > to std::vector<std::vector<Y> >
- ConvertMatrix, convert two 2D std::vector<X> to 2D std::vector<Y>
- CoutVector, std::cout on a std::vector
- GetIncVector, get a std::vector of incremented values (for example with values 0,1,2,3,etc)
- GetLongestString, find the length of the std::string with the most characters in a container
- GetShortestString, find the length of the std::string with the least characters in a container
- HugeVector, class that can contain more elements than std::vector
- LoopReader, reading a container looped
- RandomShuffle, shuffle a std::vector to a random order
- Read and write a std::vector from/to a std::stream
- Read and write two std::vectors from/to a std::stream
- Reading a container looped, LoopReader
- Save a container to file, SaveContainer
- SaveContainer, save a container to file
- SumStringLength, sum the lengths of std::strings irn a container
- Shuffle a std::vector to a random order, RandomShuffle
- Sort a std::vector, SortVector
- SortVector, sort a std::vector
- Write and read a std::vector to/from a std::stream
- Write and read two std::vectors to/from a std::stream
- std::cout on a std::vector, CoutVector
Advice
- Prefer using a std::vector over an array [1-4]
- Use std::vector as your default container [5]
- Don't use iterators into a resized std::vector or std::deque [6]
- Don't assume performance benefits from reserve() without measurements [7]
- When necessary, use reserve() to make performance predictable [8]
- Do not assume that operator[] range checks [9]
- Use the 'at' member function when you need guaranteed range checks [10]
- Use
emplace()for notational convenience [11] - Use
emplace()to avoid having to pre-initialize variables [12] - Consider using
emplace_backby default [13]
External links
References
- [1] Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Chapter 76: 'Use vector by default. Otherwise, choose an appropriate container'.
- [2] Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. 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). 1997. ISBN: 0-201-88954-4. Chapter C.14.11 'Prefer vector over array'.
- [5] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 924: '[2] Use vector as your default container'
- [6] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 924: '[21] Don't use iterators into a resized vector or deque'
- [7] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 924: '[19] Don't assume performance benefits from reserve() without measurements'
- [8] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 924: '[22] When necessary, use reserve() to make performance predictable'
- [9] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 924: '[23] Do not assume that [] range checks'
- [10] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 924: '[24] Use at() when you need guaranteed range checks'
- [11] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 924: '[25] Use emplace() for notational convenience'
- [12] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 31.6. Advice. page 925: '[27] Use emplace() to avoid having to pre-initialize variables'
- [13] Jason Turner * C++ Weekly - Ep 108 - Understanding emplace_back