How to determine the size of a vector at runtime?

At runtime, you can determine the size of vector ?

for instance

input: 25 // which shows the size of the vector

  code : int N ; cin << N ; vector <int> data[N]; 
+4
source share
4 answers

Two methods that may interest you:

Fragment Example

  std::vector<int> v; for (int i =0; i < 25; ++i) v.push_back (i); v.reserve (100); std::cerr << "Elements: " << v.size () << std::endl; std::cerr << "Capacity: " << v.capacity () << std::endl; 

Output

 Elements: 25 Capacity: 100 

I assume that your sample fragment in the original message contains at least one typo, you do not declare std::vector<int> elements with N , writing below.

What you wrote will be that the data is an array of vector<int> size N , and it would compile if N were known at compile time (or if your compiler had a variable length extension).

 vector<int> data[N]; 

To create vector and insert N elements from the very beginning:

 std::vector<int> data (N); 
+13
source

You are using vector in the (possibly) wrong way ... so you are defining a C-style array of N vectors (by the way, this syntax is not standard, since N will need to be known at compile time), while you, you probably want to define a vector containing N elements that execute as follows:

 vector<int> data(N); 

(which calls the one-parameter vector constructor, which builds a default initialized array of N long elements)

To get your size at run time 1, you just need to call its size() method:

 cout<<"The vector contains "<<data.size()<<" elements.\n" 

  • Actually, even during compilation it didnโ€™t even make sense to set our size, since the size of vector (specified as the number of elements stored in it) is determined only at runtime.
+9
source

You are almost there:

use

 vector <int> data(N); 

instead

 vector <int> data[N]; 

If you need to set all the elements of your vector to a value other than zero, say -1 , use vector <int> data(N, -1);

+3
source

Matteo is right. Just to add to his answer. You do not have to determine the size of the vector at runtime. I assume you are using C ++.

You can just write

 vector<int> data; 

and then every time you want the element to be until the end of the vector, just

 data.push_back(<some integer>) 

Its a different array, where you need to give them size before use. Vectors can dynamically grow and shrink. This way you do not need to worry about memory allocation. It is handled by the compiler and the vector class at runtime.

+2
source

Source: https://habr.com/ru/post/1386821/


All Articles