创建 1 个元素的集合的最佳\最简单\最快方法是什么?(C++)

pav*_*nko 6 c++ boost stl set c++11

有时我需要用户类型的 1 个元素的集合(或任何其他容器)并以这种方式创建它们:

boost::assign::list_of(typeVariable).convert_to_container<std::unordered_set<UserType> >()
Run Code Online (Sandbox Code Playgroud)

有谁知道更漂亮的方法吗?

PS: 例如,我们有任何业务逻辑 API,它搜索元素,并且它采用类型集(或另一个容器)进行选择。不同的用户可以访问不同的类型。我们也可以选择任何一种类型进行过滤,在这种情况下,我们将从过滤选项中采用这种类型。

所以我只是想要一种用 1 行编写代码的简单方法。我当前的版本是:

getElements(filter.type != UNDEFINED
            ? boost::assign::list_of(filter.type).convert_to_container<std::set<UserType> >()
            : std::set<UserType>(allowedTypes.begin(), allowedTypes.end()))
Run Code Online (Sandbox Code Playgroud)

coy*_*508 5

std::unordered_set<UsertType> set = {typeVariable}
Run Code Online (Sandbox Code Playgroud)

或者对于包含临时生成的集合的完整工作代码:

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
    /* First (unused in the rest of the code) set */
    std::unordered_set<int> set = {1};

    /* Set generated on the fly, if you don't even want to create
       a variable for it */
    cout << *std::unordered_set<int>({2}).begin() << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Wal*_*ter 5

不幸的是,在 C++ 中你不能简单地使用auto set={2.3};,因为这创建的不是一个集合,而是一个std::initializer_list。然而,在

template<typename Tp>
inline std::unordered_set<Tp> make_set(Tp const&x)
{ return {x}; }
Run Code Online (Sandbox Code Playgroud)

您可以使用

auto set = make_set(2.3);
Run Code Online (Sandbox Code Playgroud)

无需set明确指定类型(如另一个答案)。

您可以扩展make_set()以获取任意数量的相同类型的参数(我将其作为练习留给您),但添加采用初始值设定项列表的重载会更容易

template<typename Tp>
std::unordered_set<Tp> make_set(std::initializer_list<Tp> const&x)
{ return {x}; }
Run Code Online (Sandbox Code Playgroud)

什么时候

auto set = make_set({2.3,3.1});
Run Code Online (Sandbox Code Playgroud)

创建一个std::unordered_set<double>具有两个元素的 。

编辑在我看来,没有纯粹的std解决方案可以避免显式命名集合的类型(std::unordered_set<possibly_templated_user_type>)。因此, (或类似)是唯一这样的解决方案,并且可以说,应该由(类似于和)make_set()提供。stdstd::make_unique()std::make_shared()