0

In the below example code I need to pass the structure vector to a function.

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

I declared the vector as below:

 vector<A:: mystruct > mystry;

Now in this class "A" there is a function as below.

  myfunc ( vector<mystruct> &mystry );

How to pass the structure vector to my "myfunc"?

2vision2
  • 4,933
  • 16
  • 83
  • 164

2 Answers2

4

Try this

#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;
}
Nayana Adassuriya
  • 23,596
  • 30
  • 104
  • 147
  • This seems excessively complicated. The OP only asked how to pass the vector to `myfunc`. – Michael Dorst Apr 08 '13 at 05:02
  • @MichaelDorst - 1. This is a working example so OP can debug and get the idea. 2. I commented the impotent points that OP need to understand and make the program understandable. 3. I don't see any complected in this simple program that mostly copied from OPs code. =) – Nayana Adassuriya Apr 08 '13 at 05:44
0

Well, first you need to create an instance of A, like so:

A a;

Then, you need to call myfunc on a, passing it the value mystry.

a.myfunc(mystry);
Michael Dorst
  • 8,210
  • 11
  • 44
  • 71