Reputation: 51
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?
Upvotes: 5
Views: 8063
Reputation: 776
Following code can be used to define vector of undefined size.
vector<string> v;
Remember that, for <string>
you need following header file:
#include<string>
After all this you can push elements using push_back()
function as follows-
v.push_back('a');
v.push_back('b');
v.push_back('c');
v.push_back('c');
There are some other useful functions for vectors you can give watch into-
front();
back();
begin();
end();
rbegin();
rend();
max_size();
capacity();
resize();
empty();
at(n);
Read details of these function and their usage.
Upvotes: 1
Reputation: 3119
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.
Upvotes: 2
Reputation: 110658
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]);
.
Upvotes: 5