如果数组已满并且其大小增加 1 来插入新元素,则插入 N 个元素的时间可以计算为 1+2+ .. N = N^2/2。(声明长度为 size+1 的新数组并将元素复制到新数组)。
我无法理解如果我们不是将数组大小增加 1,而是声明一个长度为 2*size 的新数组,然后复制新数组中的元素,那么如何计算时间。
可能重复:
一个谜语(在C中)
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 既然我们现在在接口中有默认方法,那么它是不是更像是一个抽象类同时使用抽象和非抽象方法?在实际使用中,我们可以互换地使用接口和抽象类吗?是否存在两者之间的差异仍然相关的情况?
#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
另外,你如何解释表达式*(int *)&a?
#include <stdio.h>
void func(int **);
int main()
{
int *arr[2];
func(arr);
printf("value [1] = %d \n",*arr[0]);
printf("value [2] = %d \n",*arr[1]);
return 0;
}
void func(int **arr)
{
int j = 10;
arr[0] = &j;
arr[1] = &j;
}
Run Code Online (Sandbox Code Playgroud)
使用gcc成功编译代码.但是,输出是:
value [1] = 10
value [2] = 32725
Run Code Online (Sandbox Code Playgroud)
第二个值是垃圾值.为什么会这样?如何正确使用双指针访问数组?
我有一个二进制搜索树实现,其中树的每个节点都具有这种结构。
struct node {
T data;
std::unique_ptr<node> left, right;
node(T data): data(data), left(nullptr), right(nullptr) {}
};
Run Code Online (Sandbox Code Playgroud)
findmin给定树的根,我实现了一个例程,该例程返回最少的数据(最左边的节点的数据)。目前,我已经递归实现了。
template<typename T>
T Btree<T>::_findmin(std::unique_ptr<node>& curr)
{
if (curr && curr->left == nullptr)
return curr->data;
return _findmin(curr->left);
}
Run Code Online (Sandbox Code Playgroud)
这行得通,但我想迭代地实现。对于普通的指针,我们可以分配然后继续遍历最左边的节点curr = curr->left,但是这种分配对unique_ptr不起作用。
有没有办法迭代实现?
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码输出为10 20 …
class array {
public:
int arr[];
array() {
arr[0] = 1;
arr[100] = 2;
}
};
int main() {
array a;
cout << a.arr[0] << a.arr[100] << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在运行上面的代码时期待分段错误.但是,它打印了正确的输出,即使我没有提到数组大小.这是什么原因?
有人可以用例子解释为什么在c ++中重载逗号,地址,逻辑AND和逻辑OR运算符不是一个好习惯吗?
我在阅读 c++ 入门时遇到了一个问题,我想知道下面的代码有什么问题
#include<iostream>
using namespace std;
class Nodefault
{
int a;
public:
Nodefault(int j):a(j){};
};
class c
{
int a ;
public:
c(int b ):a(b){};
c(){};
Nodefault n(5) ;
};
int main()
{
c obj;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我无法在这里使用 Nodefault 类作为其成员创建类 c 的对象?
以下是编译器的错误:
错误:数字常量之前的预期标识符错误2.cpp:18:14:错误:数字常量之前的预期“,”或“...”