I am a beginner and I want to write a loop in cpp in which a vector has unknown size which is determined by a if funcion. 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 before the loop starts, how can I write this code in cpp?
We can set the size of a Vector using setSize() method of Vector class. If new size is greater than the current size then all the elements after current size index have null values. If new size is less than current size then the elements after current size index have been deleted from the Vector.
The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.
If the vector container is empty what will size() and empty() returns? Size will return 0 and empty will return 1 because if there is no element in the vector the size of that vector will be 0 and empty will be true so it will return 1.
In C++, if we want a container of values that we can add values to and it expands at run-time, we use an std::vector
. As you can see, it is aptly named for your purpose. The matlab line v=[v;A(i)];
, which concatenates a value from A
with v
, is equivalent to using the std::vector::push_back
function: v.push_back(A[i]);
.
The standard C++ library has a class std::vector
as indicated by one of the comments. The vector
class doesn't have a pre-defined size; as you add member objects, the size of the vector grows dynamically. It might be worthwhile to read about standard C++ library in general and vector in particular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With