将向量传递给函数c ++

时间:2011-10-06 15:53:43

标签: c++ vector parameter-passing

我有一个main.cpp test.h和test.cpp>我试图通过我的矢量,所以我可以在test.cpp中使用它,但我一直在收到错误。

   //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**)â

6 个答案:

答案 0 :(得分:13)

std::vector<T>T* []不兼容。

更改tester()功能签名,如下所示:

//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;
}

有几种方法可以传递此std::vector<T>,并且所有方法都有不同的含义:

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

答案 1 :(得分:2)

将其作为std::vector<Item *> &(对vector的引用)传递,并使用迭代器迭代它。

答案 2 :(得分:2)

  1. 你应该#include <string>
  2. string name应该阅读std::string namestd::vector
  3. 您使用tester()调用vector,但它需要一个数组(这两个数据不可互换)。
  4. s.sizeof()对于数组和向量都不正确;对于后者,使用s.size()或者更好的是使用迭代器。
  5. 这些只是立即跳出的错误;可能会有更多。

答案 3 :(得分:1)

vector不是数组。

int tester(vector<Item *> &s)

(作为参考传递以避免复制或如果您需要修改)

您还需要修改tester函数中的代码才能正常工作。

答案 4 :(得分:0)

你应该修复

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

首先,可能是using namespace std;#include <string>

答案 5 :(得分:0)

您缺少包含

#include <string>
#include <vector>

您需要使用std::stringstd::vector<>std::vector不是数组,因此您应该将向量作为参考传递

int tester(std::vector<Item*> & vec) { //... }
如果您不打算修改传递的矢量,则

或甚至const std::vector<Item*> &

另外,你确定,你需要一个指针向量吗?你想要实现什么目标?

相关问题