Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何复制结构属性并更改副本而不是原始属性_C++_Struct - Fatal编程技术网

C++ 如何复制结构属性并更改副本而不是原始属性

C++ 如何复制结构属性并更改副本而不是原始属性,c++,struct,C++,Struct,假设这个结构 typedef struct solution { int *vector; float cost; }solution; 如何将其传递给函数以在副本中而不是在原件中进行操作?例如: solution change(solution c){ solution d; d.vector = c.vector; d.vector[1]++; return d; } int main(){ int a[3] = {1,2,3

假设这个结构

typedef struct solution {
    int *vector;
    float cost;   
}solution;
如何将其传递给函数以在副本中而不是在原件中进行操作?例如:

solution change(solution c){
    solution d;
    d.vector = c.vector;
    d.vector[1]++;
    return d;
}

int main(){
    int a[3] = {1,2,3};
    solution c;
    c->vector = a;
    solution d = change(c);

    printf("%d %d\n",c.vector[1],d.vector[1]);
}
我想把它印成32


我很抱歉问这样一个基本的问题,但从我在类似问题中搜索的内容来看,它是推荐的memcpy,但从上面的代码来看,它也是这样做的。

您的问题基本上是您正在使用原始指针:不要。改用std::vector

解决方案c和解决方案d都有一个指向相同内存位置的指针,地址为int a[3]。我想你不明白的是d.vector=c.vector,它实际上并没有复制数组,只是指向它的指针,所以c和d实际上指向同一个数组,所以当你试图打印它时,你会得到相同的值。如果你使用C++,并且试图更好地理解指针,你可能想看看MalC++。< /P>你是如何使用MeMCPY的?这是C还是C++?即使忽略std::vector,答案c/也会有所不同。
#include <vector>

struct solution { // No need for typedef - C++ does that automatically.
    std::vector<int> vec;
    float cost = 0.0f;     // Always good to initialize
};

solution change(const solution& c) { // By default, pass 'big' objects by const reference 
    solution d;
    d.vec = c.vec; // This will allocate a new vector and copy the value.
    d.vec[1]++;
    return d;
}

int main(){
    const int a[3] = {1,2,3};
    solution c;
    std::copy( std::begin(a), std::end(a), std::back_inserter(c.vec));
    const solution d = change(c);

    printf("%d %d\n",c.vec[1],d.vec[1]);
}