简体   繁体   English

将 char 向量复制到另一个向量

[英]Copy a char vector to another vector

I'm trying to create a function to copy an vector into another one:我正在尝试创建一个 function 来将一个向量复制到另一个向量中:

#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.当我调用 function 时,提示 window 上什么也没有出现。

There are 2 issues with your code.您的代码有 2 个问题。 The first is that any modification to Y will not be visible at the call site, since you are passing the vector by value.第一个是对Y的任何修改在调用站点都将不可见,因为您是按值传递vector Instead, you need to pass it by reference.相反,您需要通过引用传递它。

Second, you are indexing X incorrectly (assuming X is not as large as Y ).其次,您对X的索引不正确(假设X没有Y大)。 Instead, you could just push_back the values.相反,您可以push_back值。

However, you can even copy vector s directly, so you could do:但是,您甚至可以直接复制vector ,因此您可以这样做:

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:在这一点上,命名为 function 是毫无意义的,因为与其做类似的事情:

std::vector<char> y;
clone(x, y);

you could simply do:你可以简单地做:

auto y = x;

which is much more readable.这更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM