Using C++, I would like to create an instance of a vector object input, as shown in the main() function of the test program below. The input vector is filled with data, and then passed by reference to a compute() function. The compute function is to return two vector objects real and imag.
Is it possible to return these two vector objects in the manner shown in the code snippet below?
Compiling this code using gcc gives the following errors:
In function ‘void compute(const std::vector<double>&, std::vector<double>&, std::vector<double>&)’:
error: declaration of ‘std::vector<double> real’ shadows a parameter
error: declaration of ‘std::vector<double> imag’ shadows a parameter
Perhaps there is a better way to do this? Here is the complete test program:
#include <iostream>
#include <vector>
void compute(const std::vector<double> &input,
std::vector<double> &real, std::vector<double> &imag)
{
unsigned int N = input.size();
unsigned int csize = (N / 2) + 1;
// the error occurs here
std::vector<double> real(csize);
std::vector<double> imag(csize);
for (int i = 0; i < csize; i++)
{
real[i] = input[i] * i;
imag[i] = input[i] * -i;
}
} // end
int main()
{
const int num = 10;
std::vector<double> input(num);
for(int i = 0; i < num; i++)
input[i] = i;
std::vector<double> real;
std::vector<double> imag;
compute(input, real, imag);
} // end
The vectors already exist and so you don’t want to create them again, instead resize them to be the proper size:
Your code was actually valid, but since you’re compiling on -Werror it’s rejected. By “shadowing” it means that you would be creating and modifying vectors local to the function and so the ones passed by reference wouldn’t have been updated.