开发者

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

开发者 https://www.devze.com 2023-01-20 04:22 出处:网络
The structure is defined as struct state{ string node_name; int node_no; int node_val; int occupant; vector<int>node_con;

The structure is defined as

struct state{

    string node_name;
    int node_no;
    int node_val;
    int occupant;
    vector<int>node_con;
        };

state s[100][100]

I want to send it to a function along with i and j values 开发者_StackOverflow社区, where s[i][j] , (i->rows , j-> columns) . How will the struct be sent with both i and j ?


This way

void f(StructName (*a)[100], int i, int j) {

}

Please read about two dimensional arrays and pointer to arrays. Alternatively in C++ you can pass it by a reference, which will make it not decay to its first element

void f(StructName (&a)[100][100], int i, int j) {

}


in C there is no way (AFAIK) in C++ you could do this

template <class T, int N, int M>
void f(T (&a)[N][M])
{
//...
}

Alternatively, you could pass the dimensions manually, or hard-code them


In C, you can wrap it up in another structure :-)

I see stuff that doesn't look like C in your code ...

struct state {
    string node_name;
    int node_no;
    int node_val;
    int occupant;
    vector<int>node_con;
};

struct wrap {
  int i;
  int j;
  struct state (*ps)[];
};

int main(void) {
  struct state s[100][100];
  struct wrap x;

  x.i = 100;
  x.j = 100;
  x.ps = s;

  fx(x);

  return 0;
}


You mean passing an array of structures. I think it should be this:

struct state{
    string node_name;
    int node_no;
    int node_val;
    int occupant;
    vector<int>node_con;
};

state s[100][100];

void doSomething(state theState[][100], int i, int j)
{
    cout << theState[i][j].node_name << endl;
}

int main()
{
    s[0][1].node_name = "s[0][1]";
    doSomething(s, 0, 1);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消