简体   繁体   English

将结构数组传递给 C++ 中的函数

[英]passing an array of structs to a function in c++

I have already written a program that in functioning properly.我已经编写了一个运行正常的程序。 I need to break it off into functions.我需要把它分解成函数。 I have 3 arrays of structs.我有 3 个结构数组。 I would like to make a function that reads the information from the file and echoprints it out.我想做一个从文件中读取信息并将其回显出来的函数。 I just need an example on how I would pass it.我只需要一个关于如何通过它的例子。 I would post my code but I do not want the other students to take it.我会发布我的代码,但我不希望其他学生接受它。 Thanks.谢谢。

If you are using C arrays:如果您使用 C 数组:

struct A { int v; }
A data[10];

void func(A *array, size_t n) {
}

func(data, 10);

Or if you are using a vector:或者,如果您使用的是向量:

std::vector<A> vec;

void func(std::vector<A>& array) {
}

func(vec);

Since you are tagging this as "C++", I assume you are using vectors ( :-) )由于您将其标记为“C++”,因此我假设您使用的是向量(:-))

void f1 ( yourVector& yourVector )
{
  // do something with the vector as read-write (for example fill the vector with somthing).
}


void f2 ( const yourVector& yourVector )
{
  // do something with the vector as read-only.
}

int main()
{
  std::vector <yourStruct> yourVector;
  f1( yourVector );
  f2( yourVector );
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM