Click here to Skip to main content
15,905,148 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
XML
#include<vector>
#include<iostream>
using std::vector;

void add (vector<int> & a )
{
    for(int i=0;i<=9;i++)
        a.push_back(i);
}

int main()
{
    vector <int> a;
    add(a);
}




are these elements valid?
will they be free when the function add end?
Posted
Comments
P Uday kishore 15-May-13 0:59am    
It is storing the elements right.nothing wrong there.
whats your doubt in that??

1 solution

Hi,

the elements that you inserted in the add() function will be valid after the function add() ends. It is because, the vector is a local variable of the main() function and in the add() function you only reference it.

For this reason, you can write all the elements to the console just after the add() call:
C++
#include<vector>
#include<iostream>
#include<stdio.h>
using std::vector;

void add (vector<int> & a )
{
    for(int i=0;i<=9;i++)
        a.push_back(i);
}
 
int main()
{
    vector<int> a;
    add(a);
    
    // write all the lements
    for (vector<int>::iterator it = a.begin(); it != a.end(); it++)
    {
        printf("Element: %d\n", *it);
    }
}

In the moment when the main() function ends The vector <int> a</int> vill stop being valid and all the elements are destroyed. It is because the vector<int> a</int> is a local variable of the main() function.

Hope it helps.

Best regards,
J.K.
 
Share this answer
 
v7
Comments
CPallini 15-May-13 3:31am    
Please check your code: in order to use printf you have to include cstdio, you should write it++ instead of i++ in your for loop.
By the way my 5.
Kucera Jan 15-May-13 3:39am    
Definitelly, thanx for comment.
RHsoul 15-May-13 3:54am    
thanks a lot!
Kucera Jan 15-May-13 4:25am    
You are very welcome, dont hesitate to ask more if needed...
RHsoul 16-May-13 22:53pm    
Ha ha!I won't!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900