Can someone please explain the output to this program. For example what the capa
ID: 3705399 • Letter: C
Question
Can someone please explain the output to this program. For example what the capacity is vs the size and what does boris(5) and bw(5,'Q') mean? As well as the output to the program. Thank you in advance.
Program:
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
int peachfuzz[]={16,22,47,9,19,2};
vector <int> rocky;
vector <double> boris(5);
vector <char> bw(5,'Q');
vector <string> natasha (3,"hello");
vector <int> cloyd(peachfuzz,peachfuzz+3);
vector <int>::iterator i1,i2,i3;
int i;
cout<<"rocky"<<rocky.capacity()<<" "<<rocky.size()<<endl;
cout<<"boris"<<boris.capacity()<<" "<<boris.size()<<endl;
cout<<"bw"<<bw.capacity()<<" "<<bw.size()<<endl;
cout<<"natasha"<<natasha.capacity()<<" "<<natasha.size()<<endl;
rocky.push_back(1);
cout<<"rocky"<<rocky.capacity()<<" "<<rocky.size()<<endl;
cout<<rocky[0]<<" "<<rocky[1]<<endl;
// cout<<rocky.at(0)<<" "<<rocky.at(1)<<endl;
rocky.push_back(15);
cout<<"rocky"<<rocky.capacity()<<" "<<rocky.size()<<endl;
cout<<"front element of rocky is"<<rocky.front()<<endl;
for (i=0; i<=5; i++)
cout<<cloyd[i]<<" ";
cout<<endl;
cout<<"rocky could grow to "<<rocky.max_size()<<endl;
natasha.pop_back();
cout<<"natasha "<<natasha.size()<<endl;
i1=cloyd.begin();
i2=cloyd.end();
for (i3=i1; i3<i2; i3++)
cout <<*i3<<endl;
return 0;
}
Explanation / Answer
I guess this program is to familiarize you with the vector in c++. Vector is nothing but an array that is allocated space dynamically by the system.
As you asked what does boris(5) and bw(5,'Q') mean?
vector <double> boris(5);
This means you are creating a vector of type double of 5 elements.
vector <char> bw(5,'Q');
This means you are creating a vector of type char of 5 elements, and initializing all the 5 elements by value 'Q'.
As vectors are nothing but dynamically space managed arrays. So it has following functions:
1.size()
It returns the number of elements in the vector container.
2.capacity()
As vector is dynamically space managed array, so for efficiency, most of the time, space for some more elements is allocated than required.So this function returns the size of allocated elements. So capacity()>= size()
3.max_size()
It returns the maximum number of elements that the vector can hold ie. maximum capacity.
4.begin()
It gives the iterator of the start element of the vector.
5.end()
It gives the iterator of the last element of the vector.
See the output of your code and relate the things: