Best way to store variables in a function that will be used multiple times (c++) -


main idea:

i wrote piece of code dijkstra's algorithm , i'm dandy. however, need call function (from header file) in other codes , stuff. need store variables when function called (so once function called return variables won't return variable previous calls). , need reference these variables other codes/files.

how i'm storing variables:

a structure contains 2 vector.

my question:

would best create .h file store structure , change variables there or there way call variable function in file , use without having worry memory issues , whatnot?

also... how set .h file dijkstra algorithm if my int main takes no arguments?......

-edit-

typedef struct {  int a;  int b; } str;  str func() {  str str;  str.a = 5; str.b = 6; return str; } 

basic model of code. need reference structure , it's variable in file function. undefined reference 'main' error when compiling added int main() calls func(). suggestions?

-edit dos-

proposed fix

.h should include:

struct_name dijkstra(input variables) 

.cpp should include:

#include "dijkstra.h"  typedef struct{ blah... }struct_name;  struct_name dijkstra{ struct_name retval;  function def... return retval; } 

main.cpp should include:

#include "dijkstra.h" #include "dijkstra.cpp"  int main(){  initialize variables... blah struct_name return_struct = dijkstra(input variables);  return 0; } 

usually pass in input data algorithm needs input parameters, , return useful output data algorithm creats return type. create separate c++ struct or class if need bundle few pieces of information together.

for data structures used internally algorithm - declare them in .cpp file, not .h file. so, user not have access / visibility of internals (which useful if want change how works later).

so, header file should have function declaration - input arguments , output return type. algorithm code goes .cpp file, includes .h file. header file 'interface' , cpp file 'implementation', try keep separate.

edit : (summarizing useful points subsequent discussion)

this tutorial shows how 2 .cpp files , 1 .h file fit together. both .cpp files include .h file. .h file includes declarations (for both function type , struct type) not function definition :

www.learncpp.com/cpp-tutorial/19-header-files/

since using g++, can compile them single executable using :

g++ -o executable_name main.cpp dijkstra.cpp


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -