我正在编写代码来查找素数,在我的工作中,我很好奇 C++ 中的 % 操作究竟是如何在低级别工作的。
首先,我编写了一些代码来比较 '%' 运算符和 '>>' 运算符的经过时间。
#include <iostream>
#include <chrono>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
bool remainder1(int x);
bool remainder2(int y);
void timeCompare(bool(*f)(int), bool(*g)(int));
// I want to check which one is faster, x % 2 Vs. (x >> 1) & 1
int main()
{
srand(time(NULL));
for (int i = 0; i < 10; i++) {
timeCompare(remainder1, remainder2);
}
return 0;
}
// % 2 operation
bool remainder1(int x) {
if (x …Run Code Online (Sandbox Code Playgroud) 我尝试使用模板类创建自定义 Vector 类。
我希望我可以将我的放入变量Vector<int>中Vector<Vector<int>>。至少那是我所希望的......但它在析构函数代码处不断崩溃。
这是我的代码。
#include <iostream>
#include <string>
template <typename T>
class Vector {
T* data;
int capacity;
int length;
public:
typedef T value_type;
Vector() {}
Vector(int n) : data(new T[n]), capacity(n), length(0) {}
void push_back(T input) {
data[length++] = input;
}
T operator[](int i) { return data[i]; }
virtual ~Vector() { if (data) delete[] data; }
};
int main() {
Vector<Vector<int>> v(3);
Vector<int> vv(4);
v.push_back(vv);
}
Run Code Online (Sandbox Code Playgroud)
所以我想,也许我应该使用复制构造函数,因为问题似乎是v之前被删除了vv。好吧,如果我只是注释掉析构函数代码,它就会起作用,但这对我来说似乎不对......
所以我做了一个自定义的复制构造函数,如下所示:
Vector(const T& …Run Code Online (Sandbox Code Playgroud) 在编写c代码时,我尝试编写strcpy自己的代码,并且遇到了这个问题.
#include <stdio.h>
#include <string.h>
void strcpy2(char *s, char *t);
int main() {
char a[10] = "asds";
char b[10] = "1234567890";
strcpy2(a, b);
printf("Copy completed! : %s", a);
return 0;
}
void strcpy2(char *s, char *t) {
while ((*s++ = *t++));
}
Run Code Online (Sandbox Code Playgroud)
错误代码:已完成退出代码-1073741819(0xC0000005)
感谢这个问题,我学会了字符串应该以'\ 0'结尾,但为什么上面的代码不起作用,即使它在声明时不会导致错误?(当char b [10] ="123456789"时效果很好)
那么,'\ 0'究竟如何影响这个过程并最终导致错误?(运行时?编译时间?等)(我只知道'\ 0'应该是字符串的结尾)
char* name;
const char* _name = "something";
name = _name; // conversion from const char * is not allowed
Run Code Online (Sandbox Code Playgroud)
我知道它在 C++ 中已被弃用,但我想知道为什么......
为什么C++禁止name指向某些文字_name指向?
c++ ×3
bit-shift ×1
c ×1
char ×1
constants ×1
containers ×1
destructor ×1
rule-of-five ×1
strcpy ×1
string ×1
time ×1
vector ×1