在C++ 14中,关联容器似乎已从C++ 11改变 - [associative.reqmts]/13说:
成员函数模板
find,count,lower_bound,upper_bound,并且equal_range不得,除非类型参与重载决议Compare::is_transparent存在.
使比较器"透明"的目的是什么?
C++ 14还提供了这样的库模板:
template <class T = void> struct less {
constexpr bool operator()(const T& x, const T& y) const;
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
template <> struct less<void> {
template <class T, class U> auto operator()(T&& t, U&& u) const
-> decltype(std::forward<T>(t) < std::forward<U>(u));
typedef *unspecified* is_transparent;
};
Run Code Online (Sandbox Code Playgroud)
因此,例如,std::set<T, std::less<T>>将不会有一个透明的比较,而是std::set<T, std::less<>> …
Visual Studio 2013 Preview支持名为(根据此页面)"透明运算符函数" 的C++ 14功能.我不清楚这意味着什么.我找到的最接近的C++ 14提案就是这个,但我不确定它是否是同一个东西:http: //www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3421
我正在寻找一个更明确的解释,它是什么,为什么它是一个改进,也许是一个证明其使用的片段.
我最近发现了一件奇怪的事情.似乎计算Collatz序列长度完全没有缓存比使用缓存所有元素快 2倍.std::unordered_map
注意我确实从问题提示中是否gcc std :: unordered_map实现缓慢?如果是这样 - 为什么?我试着用这些知识来std::unordered_map表现我的能力(我使用g ++ 4.6,它确实比g ++的最新版本表现更好,我试着指定一个声音的初始桶数,我使它完全等于最大值地图必须持有的元素数量).
相比之下,使用std::vector缓存一些元素几乎比没有缓存快17倍,比使用缓慢快近40倍std::unordered_map.
我做错了什么,或者这个容器是慢的,为什么?可以让它表现得更快吗?或者,哈希映射本质上是无效的,应该尽可能避免在高性能代码中使用?
有问题的基准是:
#include <iostream>
#include <unordered_map>
#include <cstdint>
#include <ctime>
std::uint_fast16_t getCollatzLength(std::uint_fast64_t val) {
static std::unordered_map <std::uint_fast64_t, std::uint_fast16_t> cache ({{1,1}}, 2168611);
if(cache.count(val) == 0) {
if(val%2 == 0)
cache[val] = getCollatzLength(val/2) + 1;
else
cache[val] = getCollatzLength(3*val+1) + 1;
}
return cache[val];
}
int main()
{
std::clock_t tStart = std::clock();
std::uint_fast16_t largest …Run Code Online (Sandbox Code Playgroud)