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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With