How to define a vector with size undefined
I am a beginner and I want to write a loop in cpp where the vector has an unknown size which is determined by the if function. basically i want to convert this MATLAB code to cpp code:
v(1)=A(1);
for i=2:length(A)
if (abs((A(i)-v))>10^(-5))
v=[v;A(i)];
end
end
It is clear in the code that the size of v is not determined until the start of the loop, how can I write this code to cpp?
source to share
In C ++, if we need a value container that we can add values ββto and it expands at runtime, we use std::vector
. As you can see, this is aptly named for your purpose. String matlab v=[v;A(i)];
, which combines the value of A
a v
is equivalent to the use of functions std::vector::push_back
: v.push_back(A[i]);
.
source to share
The C ++ Standard Library has a class std::vector
as pointed out by one of the comments. The class vector
has no specified size; as member objects are added, the vector grows dynamically. It might be worth reading the C ++ standard library in general and vector in particular.
source to share
The following code can be used to define a vector of size undefined.
vector<string> v;
Remember that <string>
you need the following header file for:
#include<string>
After that, you can push items using a function push_back()
like this:
v.push_back('a');
v.push_back('b');
v.push_back('c');
v.push_back('c');
There are other useful functions for vectors that you can look at -
front();
back();
begin();
end();
rbegin();
rend();
max_size();
capacity();
resize();
empty();
at(n);
Read the information about these features and how to use them.
source to share