c++ - Storing an array in a separate class file -
i coding ludum dare right , trying make separate class give me array return type of function. have array set up, can't figure out how make return type array can use in main function. how go returning array , setting variable in main.cpp array?
here couple of examples, each own advantages:
#include <iostream> // c++11 #include <array> #include <vector> void myvectorfunc1(std::vector<int>& data) { (unsigned = 0; < data.size(); ++i) data[i] = 9; data.push_back(1); data.push_back(2); data.push_back(3); } std::vector<int> myvectorfunc2(void) { std::vector<int> data; data.push_back(1); data.push_back(2); data.push_back(3); return data; } /* c++ 11 template<std::size_t s> void myarrayfunc1(std::array<int, s>& arr) { (auto = arr.begin(); != arr.end(); ++it) *it = 9; } std::array<int,5> myarrayfunc2(void) { std::array<int,5> myarray = { 0, 1, 2, 3, 4 }; return myarray; } */ int main(int argc, char** argv) { // method 1: pass vector reference std::vector<int> myvector1(10, 2); myvectorfunc1(myvector1); std::cout << "myvector1: "; (unsigned = 0; < myvector1.size(); ++i) std::cout << myvector1[i]; std::cout << std::endl; // method 2: return vector std::vector<int> myvector2 = myvectorfunc2(); std::cout << "myvector2: "; (unsigned = 0; < myvector2.size(); ++i) std::cout << myvector2[i]; std::cout << std::endl; /* c++11 // method 3: pass array reference std::array<int, 3> myarray1; std::cout << "myarray1: "; myarrayfunc1(myarray1); (auto = myarray1.begin(); != myarray1.end(); ++it) std::cout << *it; std::cout << std::endl; // method 4: return array std::cout << "myarray2: "; std::array<int,5> myarray2 = myarrayfunc2(); (auto = myarray2.begin(); != myarray2.end(); ++it) std::cout << *it; std::cout << std::endl; */ return 0; }
Comments
Post a Comment