Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Passing in a vector and return a vector

Tags:

c++

vector

Sorry for the noob question, but say for example, I already have an Excel add-in written in C++ that takes a single number and return the square of the number (say inputNum and outputNum where outputNum = inputNum^2) and now I would need to modify the function such that the input is a 1xn vector and the output is a vector of same size with the numbers squared, what would I need to modify in order to have it work? Say for example, do I need to change the input to be a pointer since C++ does not take a vector directly as a native type (unlike the double in the original square function).

Thanks!

like image 870
AZhu Avatar asked May 25 '26 15:05

AZhu


1 Answers

The std::transform function is a nice way do do this:

#include <vector>
#include <algorithm>
#include <iostream>

double processElement(double e) {
    return e * e;
}

std::vector<double> processAllElements(const std::vector<double>& in) {
    // The output vector must be constructed to be the same size as the input.
    std::vector<double> out(in.size(), 0);

    // Process each element in the input vector into the output vector.
    // (input is unchanged)
    std::transform(in.begin(), in.end(), out.begin(), &processElement);
    return out;
}

int main() {
    std::vector<double> in;
    in.push_back(1);
    in.push_back(2);

    std::vector<double> out = processAllElements(in);

    std::cout << out[0] << "," << out[1];
}

If you are dealing with raw pointers to buffers of values, you can still use std::transform

int main() {
    const int n = 3;
    double in[] = {1,2,3};
    double out[n];

    std::transform(in, in+n, out, &processElement);

    std::cout << out[0] << "," << out[1];
}

But if your vector size is not known at compile time, you're much better off using std::vector to manage memory for you.

like image 106
Martin Stone Avatar answered May 28 '26 03:05

Martin Stone