为什么我的代码需要这么长时间才能运行,为什么它的运行时会有很大的变化


#include <iostream>
struct IntVector
{
int N;
int* dimensions;
IntVector(int N): N(N)
{
dimensions = new int[N];
for(auto i=0; i<N; i++)
dimensions[i] = 0;
}
IntVector(const IntVector& other) : N(other.N), dimensions(other.dimensions){}
~IntVector()
{
delete[] dimensions;
}
void set(int index, int value)
{
dimensions[index] = value;
}
void print()
{
std::cout << "N: " << N << std::endl;
for(auto i=0; i<N; i++)
std::cout <<"dimension[" << i << "] : " << dimensions[i] << std::endl;
}
void operator=(const IntVector& other)
{
N = other.N;
dimensions = other.dimensions;
}
};
int main(){
int N;
std::cin >> N;
auto v1 = IntVector(N);
for(auto i=0; i<N; i++)
v1.set(i, i+1);
auto v2 = IntVector(v1);
v2.print();
auto v3 = IntVector(N);
v3.print();
v3 = v1;
v3.print();
return 0;
}

我有一个简单的家庭作业,如上所述。为了简要解释代码的作用,它从用户那里获取一个整数,并使用该整数来确定IntVector结构中的维度数。它动态地分配与用户输入的整数一样多的内存空间。

有趣的是,当我第一次运行代码时,显示我打印的部分不到1秒,但代码完全运行大约需要3秒。更有趣的是,当我第二次运行代码时,不到1秒的时间就可以再次显示我打印的部分,但这次代码花了30秒才完全运行完毕。

(注意:我在运行代码时输入了3(

我不明白为什么会这样,如果你能帮忙,我将不胜感激,感谢你提前给出的答案。

当程序退出并执行析构函数时,程序可能会崩溃或经历未定义的行为,析构函数会添加到运行时中。operator=和默认的复制构造函数有点缺陷:复制时,被分配给的对象直接获取另一个对象的指针。当这些对象(在本例中为v1v2(稍后被销毁时,它们都试图释放同一指针。您想让您的复制构造函数和operator=分配新内存并复制旧值。

正如Anonymous1847给出的答案中所指出的,您的程序表现出未定义的行为(这可能包括花很长时间做一些模糊的事情…有时(,因为在删除三个类对象时(就在程序退出之前(,您会多次删除分配的指针。

这是因为,在复制构造函数中,您只需复制已分配的指针,而不是制作数据的(新(副本(在赋值运算符中也是如此(。

因此,您的复制构造函数应该是:

IntVector(const IntVector& other) : N(other.N) {
dimensions = new int[N];
for (auto i = 0; i < N; i++)
dimensions[i] = other.dimensions[i];
}

类似地,对于您的赋值运算符(它应该返回对类对象的引用,而不是void(:

IntVector& operator=(const IntVector& other) {
delete[] dimensions; // First, delete the existing array
N = other.N;
dimensions = new int[N]; // Create a new block ...
for (auto i = 0; i < N; i++) // ... then copy contents.
dimensions[i] = other.dimensions[i];
return *this;
}

但是,如注释中所述,最好使用标准库提供的std::vector容器类。以下是使用该容器的类的实现(main函数无需更改即可使用(:

#include <iostream>
#include <vector>
struct IntVector {
std::vector<int> dimensions;
IntVector(int N) : dimensions(N, 0) { }
IntVector(const IntVector& other) : dimensions(other.dimensions) {}
~IntVector() {}
void set(int index, int value) {
dimensions[index] = value;
}
void print() {
std::cout << "N: " << dimensions.size() << std::endl;
for (auto i = 0u; i < dimensions.size(); i++)
std::cout << "dimension[" << i << "] : " << dimensions[i] << std::endl;
}
IntVector& operator=(const IntVector& other) {
dimensions = other.dimensions;
return *this;
}
};

请随时要求任何进一步的澄清和/或解释。

相关内容

最新更新