相关疑难解决方法(0)

什么是透明比较器?

在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<>> …

c++ c++-faq c++14

101
推荐指数
4
解决办法
2万
查看次数

如何创建一个C++映射容器,其中键是值的一部分?

我想存储一堆键值对象,但值对象本身(及其对它的引用)知道它的键.我还想在只给出密钥的情况下有效地查找这些对象.

class SomeObject
{
private:
    //String or integer. int seem cheap enough to duplicate with std::map, but
    //strings seem pretty expensive when there may be thousands of objects in existence.
    //Reference/Pointer to key is fine
    const SomeOtherObject key;
    ...other stuff...
public:
    ...methods, some of which use the key in some way...
};
Run Code Online (Sandbox Code Playgroud)
  • 的std ::地图
    • 似乎要求存储是std :: pair,这样值就无法访问密钥.如果值包含密钥,则需要重复该密钥.
    • 实际上并不强制执行值内部的键不会以某种方式更改
  • 的std ::设为
    • 看起来是一个非常好的解决方案,使用自定义比较方法按键提供唯一性,直到您意识到它使您的整个值成为常量,而不仅仅是关键字段.
  • std :: vector(或其他数组/列表之类的解决方案)
    • 可以使用线性搜索,或者如果项目保持排序二进制搜索.但是我怀疑这在性能方面并不是最优的,并且需要额外的某种层才能真正实现所需的行为.

c++ containers dictionary stl

13
推荐指数
2
解决办法
3309
查看次数

如何编写一个替换链式方法调用的可变方法?

我正在研究一个名为group_bySQL同名模型的递归映射类.

例如,GB是一个group_by将存储指向对象foo分组通过std::string,int以及char密钥类型,在这个顺序.

group_by<foo,std::string,int,char>  gb;
Run Code Online (Sandbox Code Playgroud)

group_by提供了一种at( I const& key )存取方法,可用于查看当前的水平图.链接at()调用以检索更深层的地图工作正常.

auto& v = gb.at( k1 ).at( k2 ).at( k3 ).get_vec();
Run Code Online (Sandbox Code Playgroud)

问题

我想创建一个at()被调用的替代方法,at_variadic( Args const& ...args )它可以在一次调用中检索更深层的地图,而无需链接.

auto& w = gb.at_variadic( k1, k2 );
auto& x = gb.at_variadic( k1, k2, k3 );
Run Code Online (Sandbox Code Playgroud)

但是,我遇到了一些问题.首先,我不知道如何指定返回类型,因为它取决于可变参数.也许用decltype(),不知何故?

工作答案

Ecatmur在下面的回答概述了一个很好的方法.

我不得不玩终端案例group_by<>以使编译器满意,但下面的代码,很大程度上基于Ecatmur的答案,似乎与gcc 4.7.2一起正常工作.

#include <cassert>
#include <map>
#include <vector>
#include <iostream>

template< …
Run Code Online (Sandbox Code Playgroud)

c++ templates variadic-functions c++11

7
推荐指数
1
解决办法
371
查看次数