如何在c++中传递结构向量给函数

how to pass a structure vector to a function in C++?

本文关键字:结构 向量 函数 c++      更新时间:2023-10-16

在下面的示例代码中,我需要将结构向量传递给函数。

class A {
public:
    struct mystruct {   
        mystruct (int _label, double _dist) : label(_label), dist(_dist) {}   
        int label;
        double dist;
    };
}

我如下声明了vector:

 vector<A:: mystruct > mystry;

现在在类"A"中有一个函数如下:

  myfunc ( vector<mystruct> &mystry );

如何将结构向量传递给我的"myfunc"?

试试这个

#include <iostream>
#include <vector>
using namespace std;
class A {
public:
    struct mystruct {   
        mystruct (int _label, double _dist) : label(_label), dist(_dist) {}   
        int label;
        double dist;
    };
    void myfunc ( vector<mystruct> &mystry ){
        cout << mystry[0].label <<endl;
        cout << mystry[0].dist <<endl;
    }
};
int main(){
    A::mystruct temp_mystruct(5,2.5); \create instance of struct.
    vector<A:: mystruct > mystry; \ create vector of struct 
    mystry.push_back(temp_mystruct); \ add struct instance to vector
    A a; \ create instance of the class
    a.myfunc(mystry); \call function
    system("pause");
    return 0;
}

首先,您需要创建一个A的实例,如下所示:

A a;

然后,您需要在a上调用myfunc,将值mystry传递给它。

a.myfunc(mystry);