I am a complete beginner to C++ and was assigned to write a function that returns the factors of a number. Below, I have included the function I also created called print_vector
that will print all of the elements of a vector to the Console.
In my assignment, in order to check if the factorize
function is working, we have to use the test_factorize
function provided, which I have also included. However, the issue I've run in to is that the given test_factorize
does not work due to the error "Initial value of reference to a non-const must be an lvalue." I'm unsure what this means and why the test_factorize
runs into an issue because the output of factorize
is a vector and the input of print_vector
is also a vector, so I don't see why the contents of test_factorize
result in an error, though I suspect it might be something within the `factorize' function I defined that causes this error.
#include <iostream>
#include <vector>
using namespace std;
void print_vector(std::vector<int>& v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}
std::vector<int> factorize(int n) {
std::vector<int> answer;
for (int i = 1;i < n + 1; ++i) {
if (n % i == 0) {
answer.push_back(i);
}
}
return answer;
}
void test_factorize() {
print_vector(factorize(2));
print_vector(factorize(72));
print_vector(factorize(196));
}