c++ - 将 vector 传递给函数 c++

标签 c++ vector parameter-passing

我有一个 main.cpp test.h 和 test.cpp> 我正在尝试传递我的 vector ,以便我可以在 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**)â

最佳答案

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

关于c++ - 将 vector 传递给函数 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7677007/

相关文章:

c++ - c++构造对象时圆括号和大括号有什么区别

c++ - 如何将 double vector 传递给构造函数,然后在子类中访问其数据(在 C++ 中)?

c++ - 优化小型 3d vector 结构以提高性能

c++ - 返回一个对象:值,指针和引用

c++ - 使用指针传递引用和值

java - 为什么我无法重新分配传递给静态方法的 LinkedList 引用?

c++ - 错误: 'varName' was not declared in this scope

c++ - 常规迭代器(或类似的范围/ View 类)是否应该从 const_iterator 派生?

C++ For 循环遍历结构 vector (包含更多结构 vector )

function - 在 Clojure 中创建一个函数,该函数在其他命名空间中创建 'n' 个 JButton,每个 JButton 具有不同的 'actionPerformed' 方法