All Questions
20,889
questions
720
votes
29
answers
1.1m
views
What is the easiest way to initialize a std::vector with hardcoded elements?
I can create an array and initialize it like this:
int a[] = {10, 20, 30};
How do I create a std::vector and initialize it similarly elegant?
The best way I know is:
std::vector<int> ints;
...
420
votes
33
answers
1.2m
views
How do I print out the contents of a vector?
How do I print out the contents of a std::vector to the screen?
A solution that implements the following operator<< would be nice as well:
template<container C, class T, String delim = "...
402
votes
16
answers
559k
views
Best way to extract a subvector from a vector?
Suppose I have a std::vector (let's call it myVec) of size N. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For ...
401
votes
11
answers
332k
views
Sorting a vector in descending order
Should I use
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
or
std::sort(numbers.rbegin(), numbers.rend()); // note: reverse iterators
to sort a vector in descending order?...
391
votes
6
answers
187k
views
std::vector versus std::array in C++
What are the difference between a std::vector and an std::array in C++? When should one be preferred over another? What are the pros and cons of each? All my textbook does is list how they are the ...
375
votes
27
answers
594k
views
What's the most efficient way to erase duplicates and sort a vector?
I need to take a C++ vector with potentially a lot of elements, erase duplicates, and sort it.
I currently have the below code, but it doesn't work.
vec.erase(
std::unique(vec.begin(), vec.end(...
373
votes
3
answers
720k
views
check if a std::vector contains a certain object? [duplicate]
Is there something in <algorithm> which allows you to check if a std:: container contains something? Or, a way to make one, for example:
if(a.x == b.x && a.y == b.y)
return true;
...
364
votes
13
answers
609k
views
How to sum up elements of a C++ vector?
What are the good ways of finding the sum of all the elements in a std::vector?
Suppose I have a vector std::vector<int> vector with a few elements in it. Now I want to find the sum of all the ...
352
votes
4
answers
539k
views
C++ Erase vector element by value rather than by position? [duplicate]
vector<int> myVector;
and lets say the values in the vector are this (in this order):
5 9 2 8 0 7
If I wanted to erase the element that contains the value of "8", I think I would do this:
...
311
votes
17
answers
391k
views
vector vs. list in STL
I noticed in Effective STL that
vector is the type of sequence that
should be used by default.
What's does it mean? It seems that ignore the efficiency vector can do anything.
Could anybody ...
256
votes
22
answers
239k
views
Using arrays or std::vectors in C++, what's the performance gap?
In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know Stroustrup himself suggests not to use arrays. But are there significant performance differences?
255
votes
11
answers
345k
views
What is the best way to concatenate two vectors?
I'm using multitreading and want to merge the results. For example:
std::vector<int> A;
std::vector<int> B;
std::vector<int> AB;
I want AB to have to contents of A and the contents ...
249
votes
22
answers
123k
views
Is std::vector so much slower than plain arrays?
I've always thought it's the general wisdom that std::vector is "implemented as an array," blah blah blah. Today I went down and tested it, and it seems to be not so:
Here's some test results:
...
247
votes
5
answers
196k
views
C++ STL Vectors: Get iterator from index?
So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like vector.insert(pos, first, last) is the function I want.....
243
votes
13
answers
79k
views
Thou shalt not inherit from std::vector
Ok, this is really difficult to confess, but I do have a strong temptation at the moment to inherit from std::vector.
I need about 10 customized algorithms for vector and I want them to be directly ...
240
votes
6
answers
158k
views
How do I print the elements of a C++ vector in GDB?
I want to examine the contents of a std::vector in GDB, how do I do it? Let's say it's a std::vector<int> for the sake of simplicity.
240
votes
1
answer
7k
views
std::vector performance regression when enabling C++11
I have found an interesting performance regression in a small C++ snippet, when I enable C++11:
#include <vector>
struct Item
{
int a;
int b;
};
int main()
{
const std::size_t num_items ...
233
votes
5
answers
155k
views
When vectors are allocated, do they use memory on the heap or the stack?
Are all of the following statements true?
vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack
vector<Type> *vect = new ...
231
votes
6
answers
183k
views
How to assign a std::vector using a C-style array?
What is the cheapest way to initialize a std::vector from a C-style array?
Example: In the following class, I have a vector, but due to outside restrictions, the data will be passed in as C-style ...
223
votes
5
answers
262k
views
How do I reverse a C++ vector?
Is there a built-in vector function in C++ to reverse a vector in place?
Or do you just have to do it manually?
217
votes
2
answers
720k
views
How to initialize a vector in C++ [duplicate]
I want to initialize a vector like we do in case of an array.
Example
int vv[2] = {12, 43};
But when I do it like this,
vector<int> v(2) = {34, 23};
OR
vector<int> v(2);
v = {0, 9};
...
210
votes
16
answers
48k
views
Why is a C++ Vector called a Vector? [closed]
The question's pretty self-explanatory really. I know vaguely about vectors in maths, but I don't really see the link to C++ vectors.
194
votes
13
answers
454k
views
Initializing a two-dimensional std::vector
So, I have the following:
std::vector< std::vector <int> > fog;
and I am initializing it very naively like:
for(int i=0; i<A_NUMBER; i++)
{
std::vector <int> fogRow;
for(...
185
votes
3
answers
194k
views
How to get std::vector pointer to the raw data?
I'm trying to use std::vector as a char array.
My function takes in a void pointer:
void process_data(const void *data);
Before I simply just used this code:
char something[] = "my data here";
...
180
votes
6
answers
466k
views
Is it more efficient to copy a vector by reserving and copying, or by creating and swapping? [duplicate]
I am trying to efficiently make a copy of a vector. I see two possible approaches:
std::vector<int> copyVecFast1(const std::vector<int>& original)
{
std::vector<int> newVec;
...
166
votes
6
answers
88k
views
Why isn't vector<bool> a STL container?
Item 18 of Scott Meyers's book Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library says to avoid vector <bool> as it's not an STL container and it doesn't really ...
163
votes
13
answers
224k
views
Iterating C++ vector from the end to the beginning
Is it possible to iterate a vector from the end to the beginning?
for (vector<my_class>::iterator i = my_vector.end();
i != my_vector.begin(); /* ?! */ ) {
}
Or is that only possible ...
158
votes
10
answers
258k
views
How do you copy the contents of an array to a std::vector in C++ without looping?
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called ...
142
votes
7
answers
62k
views
Are std::vector elements guaranteed to be contiguous?
My question is simple: are std::vector elements guaranteed to be contiguous? In other words, can I use the pointer to the first element of a std::vector as a C-array?
If my memory serves me well, the ...
139
votes
4
answers
205k
views
Are vectors passed to functions by value or by reference in C++
I'm coding in C++. If I have some function void foo(vector<int> test) and I call it in my program, will the vector be passed by value or reference? I'm unsure because I know vectors and arrays ...
138
votes
3
answers
221k
views
Arrays vs Vectors: Introductory Similarities and Differences
What are the differences between an array and a vector in C++? An example of the differences might be included libraries, symbolism, abilities, etc.
Array
Arrays contain a specific number of elements ...
137
votes
5
answers
500k
views
How to navigate through a vector using iterators? (C++)
The goal is to access the "nth" element of a vector of strings instead of the [] operator or the "at" method. From what I understand, iterators can be used to navigate through containers, but I've ...
137
votes
10
answers
9k
views
Is it safe to push_back an element from the same vector?
vector<int> v;
v.push_back(1);
v.push_back(v[0]);
If the second push_back causes a reallocation, the reference to the first integer in the vector will no longer be valid. So this isn't safe?
...
124
votes
7
answers
174k
views
How can you erase elements from a vector while iterating?
I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need ...
124
votes
3
answers
116k
views
C++ convert vector<int> to vector<double>
What is a good clean way to convert a std::vector<int> intVec to std::vector<double> doubleVec. Or, more generally, to convert two vectors of convertible types?
123
votes
12
answers
101k
views
Removing item from vector, while in C++11 range 'for' loop?
I have a vector of IInventory*, and I am looping through the list using C++11 range for, to do stuff with each one.
After doing some stuff with one, I may want to remove it from the list and delete ...
121
votes
6
answers
85k
views
What is the difference between std::array and std::vector? When do you use one over other? [duplicate]
What is the difference between std::array and std::vector? When do you use one over other?
I have always used and considered std:vector as an C++ way of using C arrays, so what is the difference?
120
votes
6
answers
87k
views
Initial capacity of vector in C++
What is the capacity() of an std::vector which is created using the default constuctor? I know that the size() is zero. Can we state that a default constructed vector does not call heap memory ...
115
votes
6
answers
140k
views
Why is it OK to return a 'vector' from a function?
Please consider this code. I have seen this type of code several times. words is a local vector. How is it possible to return it from a function?
Can we guarantee it will not die?
std::vector<...
111
votes
6
answers
213k
views
What is the simplest way to convert array to vector?
What is the simplest way to convert array to vector?
void test(vector<int> _array)
{
...
}
int x[3]={1, 2, 3};
test(x); // Syntax error.
I want to convert x from int array to vector in ...
111
votes
26
answers
120k
views
Convert a vector<int> to a string
I have a vector<int> container that has integers (e.g. {1,2,3,4}) and I would like to convert to a string of the form
"1,2,3,4"
What is the cleanest way to do that in C++?
In Python this is ...
111
votes
3
answers
23k
views
How to enforce move semantics when a vector grows?
I have a std::vector of objects of a certain class A. The class is non-trivial and has copy constructors and move constructors defined.
std::vector<A> myvec;
If I fill-up the vector with A ...
108
votes
5
answers
298k
views
In C++ check if std::vector<string> contains a certain value [duplicate]
Is there any built in function which tells me that my vector contains a certain element or not
e.g.
std::vector<string> v;
v.push_back("abc");
v.push_back("xyz");
if (v.contains("abc")) // I ...
107
votes
8
answers
48k
views
Alternative to vector<bool>
As (hopefully) we all know, vector<bool> is totally broken and can't be treated as a C array. What is the best way to get this functionality?
So far, the ideas I have thought of are:
Use a ...
106
votes
6
answers
118k
views
How to read a binary file into a vector of unsigned chars
Lately I've been asked to write a function that reads the binary file into the std::vector<BYTE> where BYTE is an unsigned char. Quite quickly I came with something like this:
#include <...
105
votes
5
answers
22k
views
Does C++11 allow vector<const T>?
Container requirements have changed from C++03 to C++11. While C++03 had blanket requirements (e.g. copy constructibility and assignability for vector), C++11 defines fine-grained requirements on each ...
103
votes
4
answers
77k
views
std::vector::resize() vs. std::vector::reserve()
There is a thread in the comments section in this post about using std::vector::reserve() vs. std::vector::resize().
Here is the original code:
void MyClass::my_method()
{
my_member.reserve(...
102
votes
8
answers
200k
views
How do I pass multiple ints into a vector at once?
Currently when I have to use vector.push_back() multiple times.
The code I'm currently using is
std::vector<int> TestVector;
TestVector.push_back(2);
TestVector.push_back(5);
TestVector....
102
votes
11
answers
26k
views
Using std::vector as view on to raw memory
I'm using a external library which at some point gives me a raw pointer to an array of integers and a size.
Now I'd like to use std::vector to access and modify these values in place, rather than ...
101
votes
4
answers
218k
views
C# equivalent of C++ vector, with contiguous memory?
What's the C# equivalent of C++ vector?
I am searching for this feature:
To have a dynamic array of contiguously stored memory that has no performance penalty for access vs. standard arrays.
I was ...