유 길재
유 길재

Reputation: 65

C++ Passing vector to a function that is already passed

#include<bits/stdc++.h> 
using namespace std; 

void func(vector<int> &vect) 
{ 
   vect.push_back(30); 
   extra_func(vect);
} 

void extra_func(vector<int> &vect) 
{ 
   vect.push_back(40); 
} 

int main(){ 
    vector<int> vect; 
    vect.push_back(10); 
    vect.push_back(20); 

    func(vect); 

    for (int i=0; i<vect.size(); i++) 
       cout << vect[i] << " "; 

    return 0; 
} 

I want to pass a vector again to other function that has been passed. But this seems to not work. How could I implement something like this

Upvotes: 0

Views: 53

Answers (2)

Jack
Jack

Reputation: 222

The problem arises as you are calling extra_func without func knowing about it so you must initialize extra_func before func Your code should be like

#include<bits/stdc++.h> 
using namespace std; 

void extra_func(vector<int> &vect) 
{ 
   vect.push_back(40); 
} 

void func(vector<int> &vect) 
{ 
   vect.push_back(30); 
   extra_func(vect);
} 

int main(){ 
    vector<int> vect; 
    vect.push_back(10); 
    vect.push_back(20); 

    func(vect); 

    for (int i=0; i<vect.size(); i++) 
       cout << vect[i] << " "; 

    return 0; 
} 

Upvotes: 0

Blastfurnace
Blastfurnace

Reputation: 18652

You code doesn't compile because func() doesn't know about extra_func(). You either need a function declaration (sometimes called a function prototype) or to rearrange your functions.

void extra_func(vector<int> &); // declaration

void func(vector<int> &vect) 
{ 
   vect.push_back(30); 
   extra_func(vect);
} 

void extra_func(vector<int> &vect) // definition
{ 
   vect.push_back(40); 
} 

or

void extra_func(vector<int> &vect) // now it's visible to func()
{ 
   vect.push_back(40); 
} 

void func(vector<int> &vect) 
{ 
   vect.push_back(30); 
   extra_func(vect);
} 

Upvotes: 4

Related Questions