passing vector to function c++

眉间皱痕 提交于 2019-11-30 07:35:09

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*>*);

Pass it as std::vector<Item *> & (reference to vector) and use iterator to iterate through it.

  1. You should #include <string>.
  2. string name should read std::string name etc. Same goes for std::vector.
  3. You're calling tester() with a vector, yet it expects an array (the two are not interchangeable).
  4. s.sizeof() is incorrect for both an array and a vector; for the latter, use s.size() or, better yet, use an iterator.

These are just the errors that immediately jump out; there may be more.

A vector is not an array.

int tester(vector<Item *> &s)

(pass as a reference to avoid copying or if you need to modify)

You also need to modify your code inside the tester function to work correctly as a vector.

You should fix

test.h:5: error: âstringâ does not name a type

first, probably by using namespace std; and #include <string>

You are missing includes

#include <string>
#include <vector>

and you need to use std::string and std::vector<>. A std::vector is not an array, so you should pass the vector as reference

int tester(std::vector<Item*> & vec) { //... }

or even as const std::vector<Item*> & if you are not going to modify the passed vector.

Also, are you sure, that you'll need a vector of pointers? What are you trying to achieve?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!