我实现了一个简单的测试来检查Derived类的内存等级,所以我发现Derive类的虚拟表中有两个虚拟析构函数地址.有人可以向我解释一下吗?
#include<iostream>
#include<ostream>
#include<cstdio>
using namespace std;
class Base1
{
public:
Base1():a(1){}
virtual ~Base1()
{
cout << "~Base1" << endl;
}
int a;
virtual void print()
{
cout << "I am base 1!" << endl;
}
};
class Base2
{
public:
Base2():b(2){}
virtual ~Base2(){
cout << "~Base2" << endl;
}
int b;
virtual void print()
{
cout << "I am base 2!" << endl;
}
};
class Derive : public Base1, public Base2
{
public:
Derive():c(3){}
virtual ~Derive(){
cout …Run Code Online (Sandbox Code Playgroud) 今天,我遇到了一个让我感到困惑的问题
题
我有数组就像:arr[a1, a2, a3....an, b1, b2, b3.....bn],如何移动数组的元素以将其转移到arr[a1, b1, a2, b2......an,bn],并且你应该就地移动(space complexity should be constant).
我尽力把它考虑一下,得到一个丑陋的算法,就像冒泡一样:
b1 moves forward by n - 1;
b2 moves forward by n - 2;
.
.
bn-1 moves forward by 1;
Run Code Online (Sandbox Code Playgroud)
但时间复杂度是O(n 2),谁可以给我一个更好的算法?我发现另一个更好的方法就像快速排序:
First we swap the element from a(n/2) to a(n) with the elements from b1 to b(n/2);now we get two independent sub problems,So we can solve it by recursion.
T(n) = 2T(n/2) + O(n)
the …Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
#include<iostream>
using namespace std;
class A
{
public:
A():age(12){}
int age;
};
int main()
{
A a();
cout << a.age << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我使用g ++编译它时,我收到一个错误:
你看不到会员的年龄,因为a不是A级()
谁可以给我解释一下这个?什么是A a()?
在C++中,我们通常检查指针是否为null,我只知道我们应该使用
if(NULL == ptr)
Run Code Online (Sandbox Code Playgroud)
代替:
if(ptr == NULL)
Run Code Online (Sandbox Code Playgroud)
我想知道为什么?
在additiol中,如果我们想将ptr初始化为null,我们应该使用ptr = NULL还是ptr = 0?是的,我知道在C++中,我们通常使用ptr = nullptr,我想知道为什么我们这样做只是想统一代码?谢谢
有一个大小为N的随机数组,找到出现次数超过N/3的数字,例如:
{1,2,14,12,12,15,12,12,8} the result is 12
Run Code Online (Sandbox Code Playgroud)
谁有更有效的算法?我这样做:
int getNum(int *arr, int left, int right, const int size)
{
srand(time(0));
int index = rand()%(right - left + 1) + left;
std::swap(arr[left], arr[index]);
int flag = arr[left];
int small = left;
int big = right;
int equal = left;
while(equal <= big)
{
if(arr[equal] == flag)
{
equal++;
}
else if(arr[equal] < flag)
{
swap(arr[equal++], arr[small++]);
}
else
{
while(big > equal && arr[big] > flag)
{
big--;
}
std::swap(arr[big], arr[equal]);
big--; …Run Code Online (Sandbox Code Playgroud)