我尝试使用lambda函数sort,但是出现了"Segmentation fault"错误.我设法将代码简化为以下内容:
#include <iostream>
#include <algorithm>
int main()
{
const int len = 18;
int intArr[len];
for (int i=0;i<len;i++) intArr[i]=1000+i;
// The following is expected to sort all but the last element of the array
std::sort(intArr, intArr + len -1, [](int a, int b)
{
std::cout<<"("<<a<<", "<<b<<")\n";
return (a<b?-1:(a>b?1:0));
});
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我使用在Ubuntu 11.04(x64)中编译并运行此代码
g++ -std=gnu++0x test2.cpp && ./a.out.
它会打印很多对形式(large_integer,1008),一对(0,1008)和退出"Segmentation fault".
我知道有一个用于序列化的Boost模块boost::shared_ptr,但我找不到任何东西std::shared_ptr.
另外,我不知道如何轻松实现它.我怕以下代码
namespace boost{namespace serialization{
template<class Archive, class T>
inline void serialize(Archive & ar, std::shared_ptr<T> &t, const unsigned int version)
{
if(Archive::is_loading::value) {T*r;ar>>r;t=r;}
else {ar<<t.get();}
}
}}//namespaces
Run Code Online (Sandbox Code Playgroud)
不起作用.实际上,如果某个对象被多次引用,它将被第一次运行加载ar>>r,之后只会复制一个指针.但是,我们会创建shared_ptr指向它的多个对象,因此会多次破坏它.
有什么想法吗?
关于我正在使用的系统的一些技术细节:
sudo apt-get install libboost-dev)我要做的是定义一个等于2 ^ 30的常量(我可能会将它改为2 ^ 34,所以我更喜欢有一个大于32位的空间).
为什么下面的最小(?)示例不能编译?
#include <stdint.h>
// test.cpp:4:33: error: expected primary-expression before numeric constant
// test.cpp:4:33: error: expected ')' before numeric constant
const uint64_t test = (uint64_t 1) << 30;
//const uint64_t test1 = (uint64_t(1)) << 30;// this one magically compiles! why?
int main() { return 0; }
Run Code Online (Sandbox Code Playgroud) 想象一下,我们有一个SortBinTree类型构造函数,例如,
data SortBinTree a = EmptyNode | Node a (SortBinTree a) (SortBinTree a);
Run Code Online (Sandbox Code Playgroud)
它只有在类型类a的实例时才有意义Ord,因此大多数函数:: (Ord a) =>在其声明的开头都有,特别是从列表中创建这样一个树的函数.但是要教Haskell,这SortBinTree是Functor类型类的一个实例,我们必须编写类似的东西
instance Functor SortBinTree where
fmap g tree = ...
Run Code Online (Sandbox Code Playgroud)
这里的问题是我们必须处理g :: a->b,其中b不一定是Ord类类的实例.这使得编写这样的函数成为问题,因为在创建类型的元素时我们不能使用不等式SortBinTree b.
这里有标准的解决方法吗?任何fmap只为案例定义的方法b是在Ord类型类中?
我写了以下功能
bool random_bool(double probability)
{
double p_scaled = probability * (RAND_MAX+1) - rand();
if ( p_scaled >= 1 ) return true;
if ( p_scaled <= 0 ) return false;
return random_bool( p_scaled );
}
Run Code Online (Sandbox Code Playgroud)
给定,rand()从均匀分布生成一个{0,1,...,RAND_MAX-1,RAND_MAX}数字,后续调用中的数字可以被视为独立于除加密之外的所有实际目的,这应该true以概率返回p:两个if语句true以略低于概率的方式返回p,并且false概率略高于1-p,而递归调用处理其他所有事情.
但是,以下测试失败:
long long N = 10000000000; //1e10
double p = 10000.0 / N;
int counter = 0;
for (long long i=0;i<N;i++) if (random_bool(p)) counter++;
assert(9672 < counter …Run Code Online (Sandbox Code Playgroud)