c++ - Suitable type of function when more than one integer is returned -
how can have function in c++ array returning type ?
for example consider simple function calculate divisors of number, in every step of loop i
has new value .
int divisordeterminer(int num) { int = 0 ; (i; < num; i++) { if (num % == 0) { return i; } } }
i want have divisors array , don't know how ?
std::array
thing, if know how many items contain @ compile time. in case number of items vary, std::vector
work. there various containers in standard library; it's worth reading them, std::vector
go-to data type.
std::vector<int> divisordeterminer(int num) { std::vector<int> divisors; (int i=1; < num; i++) //<--- start @ 1, not 0 { if (num % == 0) { divisors.push_back(i); } } return divisors; }
edit: original code checks i=0
, should 0 count divisor of anything? not. strays undefined behaviour (ub), discussed in this question, i've started loop 1.
Comments
Post a Comment