我有一些代码使用lambda表达式:
#include <vector>
#include <algorithm>
int main(){
std::vector<int> vi={3,1};
std::sort(vi.begin(),vi.end(),[](int x,int y){
return x<y;
});
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这不需要 #include< functional>编译,但如果我使用变量来存储lambda函数:
#include <vector>
#include <algorithm>
#include <functional>
int main(){
std::vector<int> vi={3,1};
std::function<void()> compf=[](int x,int y){
return x<y;
};
std::sort(vi.begin(),vi.end(),compf);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后我需要包括<functional>编译,为什么?为什么sort()不包括<functional>呢?
我知道double不应该直接用==运算符进行比较,但如果我将初始值定义为0.0怎么样?例如:
double a=0.0;
double b=
.
.
.
Run Code Online (Sandbox Code Playgroud)
如果a未被修改,a*b == 0总是如此吗?
我很惊讶为什么下面的代码会编译:
#include <stdio.h>
int main(){
printf("%lu",sizeof(int(123)));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是4,这里的(123)是什么意思?
我发现这行代码可以用g ++编译,但不是gcc,这是什么原因?
我有一个变量i:
int i;
if(b){
i=1;
}
else{
i=-1;
}
Run Code Online (Sandbox Code Playgroud)
是i因为未定义行为的int i;存在?或者我们应该int i=0先行吗?
我编写了一个简单的程序,当定义了一个新类(例如:One,Two)时,它会将值添加到全局集合容器中:
GlobalSet.h
#include <set>
struct GlobalSet{
public:
static void* addValue(int val);
private:
static std::set<int> s;
};
Run Code Online (Sandbox Code Playgroud)
GlobalSet.cpp
#include "GlobalSet.cpp"
std::set<int> GlobalSet::s;
void* GlobalSet::addValue(int val){
s.insert(val);
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
One.h
struct One{};
Run Code Online (Sandbox Code Playgroud)
One.cpp
#include "One.h"
#include "GlobalSet.h"
void* globalset =GlobalSet::addValue(1);
Run Code Online (Sandbox Code Playgroud)
Two.h
struct Two{};
Run Code Online (Sandbox Code Playgroud)
Two.cpp
#include "Two.h"
#include "GlobalSet.h"
void* globalset2 =GlobalSet::addValue(2);
Run Code Online (Sandbox Code Playgroud)
TEST.CPP
int main(){
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是这个程序会导致段错误依赖于gcc编译命令中的cpp序列:
g++ GlobalSet.cpp One.cpp Two.cpp test.cpp -o test.exe //normal
g++ One.cpp Two.cpp GlobalSet.cpp test.cpp -o test.exe //segment fault!!
Run Code Online (Sandbox Code Playgroud)
为什么会这样?如何解决问题,使其无需关心gcc编译中的cpp序列?
我将创建一些具有虚拟副本功能的父类和子类,它返回self的副本:
class A{
public:
int ID;
virtual A* copy(){
return new A();
}
}
class B : public A{
public:
int subID;
virtual A* copy(){
B* b=new B();
memcpy(b,this,sizeof(B));
return b;
}
};
Run Code Online (Sandbox Code Playgroud)
编译时,会显示以下警告:
destination for this 'memcpy' call is a pointer to dynamic class 'B' ; vtable pointer will be overwritten
explicitly cast the pointer to silence this warning
Run Code Online (Sandbox Code Playgroud)
这个警告意味着什么,它会带来什么潜在的问题?
我发现我在源代码中添加了一些URL,但忘了评论它,但仍然可以编译,我单独测试它:
int main(){
http://localhost
return 0;
}
gcc hello.c -o hello.exe
Run Code Online (Sandbox Code Playgroud)
哪个仍然可以编译没有错误,我检查c关键字,'http'似乎不是关键字,是什么原因?