I'm trying to create a function to copy an vector into another one:
#include <iostream>
#include <vector>
int clone(std::vector <char> X, std::vector <char> Y){
for(int i(0);i<X.size();i++){
Y[i]=X[i];
}
return 0;
}
When I call the function, nothing appears on the prompt window.
There are 2 issues with your code. The first is that any modification to Y
will not be visible at the call site, since you are passing the vector
by value. Instead, you need to pass it by reference.
Second, you are indexing X
incorrectly (assuming X
is not as large as Y
). Instead, you could just push_back
the values.
However, you can even copy vector
s directly, so you could do:
int clone(std::vector <char> const &X, std::vector <char> &Y){
Y = X;
return 0;
}
At this point, having a named function is rather pointless, since instead of doing something like:
std::vector<char> y;
clone(x, y);
you could simply do:
auto y = x;
which is much more readable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.