C ++没有指针的复制结构

时间:2014-12-15 14:15:05

标签: c++ arrays structure

我想将数据结构复制到另一个

struct times{
    QString name;
    double time1;
    double time2;
    double time3;
};

/..../

times *abc = new times[10];
times *abc2 = new times[10];

如何在不复制指针的情况下将abc复制到abc2中?

4 个答案:

答案 0 :(得分:5)

std::copy(abc, abc+10, abc2);

虽然,除非你有充分的理由来处理原始指针,否则请使用更友好的容器:

std::vector<times> abc(10);
std::vector<times> abc2 = abc;  // copy-initialisation
abc2 = abc;                     // copy-assignment

答案 1 :(得分:1)

for(int i = 0; i < 10; ++i)
   abc2[i] = abc[i];

或者

std::copy_n(abc, 10, abc2);

答案 2 :(得分:1)

或者,您可以在结构中使用复制构造函数。

struct times{
    times(const &A) {
        this->name = A.name;
        this->time1 = A.time1;
        this->time2 = A.time2;
        this->time3 = A.time3;
    }
};

答案 3 :(得分:0)

简单,与分配char指针相同。

struct TestStruct
{
int a;
float c;
char b;
};

main()
{
    struct TestStruct *structa = new TestStruct;

    structa->a = 1121;
    structa->b = 'D';
    structa->c = 12.34;

    struct TestStruct *abc = structa;
    cout<<abc->a;
}