我有一行代码,占用了我应用程序运行时的25% - 30%.它是std :: set的小于比较器(该集合用红黑树实现).它在28秒内被称为大约1.8亿次.
struct Entry {
const float _cost;
const long _id;
// some other vars
Entry(float cost, float id) : _cost(cost), _id(id) {
}
};
template<class T>
struct lt_entry: public binary_function <T, T, bool>
{
bool operator()(const T &l, const T &r) const
{
// Most readable shape
if(l._cost != r._cost) {
return r._cost < l._cost;
} else {
return l._id < r._id;
}
}
};
Run Code Online (Sandbox Code Playgroud)
条目应按成本排序,如果成本与其ID相同.每次提取最小值时都会有很多插入.我想过使用Fibonacci-Heaps,但我被告知它们理论上很好,但是它们受到高常数的影响并且实现起来非常复杂.并且由于insert在O(log(n))中,运行时增加几乎是恒定的,大n.所以我认为可以坚持下去.
为了提高性能,我尝试用不同的形状表达它:
return l._cost < r._cost || r._cost > l._cost || …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个方法,该方法可以更改可以具有任意结构的对象中的字段值.当我有一个指向结构的指针时,字段的转换没有问题.但是,当我的接口没有包装指向结构的指针但结构本身时,我无法改变字段,简而言之:
// The following doesn't work
var x interface{} = A{Str: "Hello"}
// This panics: reflect: call of reflect.Value.Field on ptr Value
reflect.ValueOf(&x).Field(0).SetString("Bye")
// This panics: reflect: call of reflect.Value.Field on interface Value
reflect.ValueOf(&x).Elem().Field(0).SetString("Bye")
// This panics: reflect: reflect.Value.SetString using unaddressable value
reflect.ValueOf(&x).Elem().Elem().Field(0).SetString("Bye")
// This prints `false`. But I want this to be settable
fmt.Println(reflect.ValueOf(&x).Elem().Elem().Field(0).CanSet())
// This works
var z interface{} = &A{Str: "Hello"}
// This prints `true`
fmt.Println(reflect.ValueOf(z).Elem().Field(0).CanSet())
Run Code Online (Sandbox Code Playgroud)
长:http://play.golang.org/p/OsnCPvOx8F
我已经阅读了反射法则,所以我知道当我有一个指向结构的指针时,我可能只修改字段.所以现在我的问题是:如何获得指向结构数据的指针?
更新:
我基本上使用它,y …