I have a main.cpp test.h and test.cpp> I am trying to pass my vector through so i can use it in test.cpp but i keep getting errors.
//file: main.cpp
int main(){
vector <Item *> s;
//loading my file and assign s[i]->name and s[i]-address
tester(s);
}
//file: test.h
#ifndef TEST_H
#define TEST_H
struct Item{
string name;
string address;
};
#endif
//file: test.cpp
int tester(Item *s[]){
for (i=0; i<s.sizeof();i++){
cout<< s[i]->name<<" "<< s[i]->address<<endl;
}
return 0;
}
---------------errors--------
In file included from main.cpp:13:
test.h:5: error: âstringâ does not name a type
test.h:6: error: âstringâ does not name a type
main.cpp: In function âint main()â:
main.cpp:28: error: cannot convert âstd::vector<Item*, std::allocator<Item*> >â to âItem**â for argument â1â to âint tester(Item**)â
However, to pass a vector there are two ways to do so: Pass By value. Pass By Reference.
An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C.
Need of Passing by reference For example when the function does not modify the vector it is better to pass by reference so as to make the code faster.
vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor. So, you must use vector<int>& (preferably with const , if function isn't modifying it) to pass it as a reference.
A std::vector<T>
and T* []
are not compatible types.
Change your tester()
function signature as follows:
//file: test.cpp
int tester(const std::vector<Item>& s) // take a const-reference to the std::vector
// since you don't need to change the values
// in this function
{
for (size_t i = 0; i < s.size(); ++i){
cout<< s[i]->name<<" "<< s[i]->address<<endl;
}
return 0;
}
There are several ways you could pass this std::vector<T>
and all have slightly different meanings:
// This would create a COPY of the vector
// that would be local to this function's scope
void tester(std::vector<Item*>);
// This would use a reference to the vector
// this reference could be modified in the
// tester function
// This does NOT involve a second copy of the vector
void tester(std::vector<Item*>&);
// This would use a const-reference to the vector
// this reference could NOT be modified in the
// tester function
// This does NOT involve a second copy of the vector
void tester(const std::vector<Item*>&);
// This would use a pointer to the vector
// This does NOT involve a second copy of the vector
// caveat: use of raw pointers can be dangerous and
// should be avoided for non-trivial cases if possible
void tester(std::vector<Item*>*);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With