Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a vector with undefined size

Tags:

c++

vector

size

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?

like image 806
zahra flower Avatar asked Feb 05 '13 16:02

zahra flower


People also ask

How do you specify the size of a vector?

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.

How do you set the size of a vector in C++?

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.

What is the size of an empty vector?

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.


2 Answers

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]);.

like image 161
Joseph Mansfield Avatar answered Oct 17 '22 06:10

Joseph Mansfield


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.

like image 38
Jaywalker Avatar answered Oct 17 '22 07:10

Jaywalker