8

私は次のshared_ptrものを持っていますmap

std::shared_ptr<std::map<double, std::string>>

そして、ブレース初期化を使用して初期化したいと思います。出来ますか?

私はもう試した:

std::string s1("temp");
std::shared_ptr<std::map<double, std::string>> foo = std::make_shared<std::map<double, std::string>>(1000.0, s1);

ただし、Xcode 6.3 を使用してコンパイルすると、次のエラーが発生します。

/usr/include/c++/v1/map:853:14: Candidate constructor not viable: no known conversion from 'double' to 'const key_compare' (aka 'const std::__1::less<double>') for 1st argument

最初のパラメーター (1000.0) の他のバリエーションを試しましたが、成功しませんでした。

誰でも助けることができますか?

4

5 に答える 5

8

std::map初期化子リストのコンストラクターがあります。

map (initializer_list<value_type> il,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());

このコンストラクターを使用して非常に簡単にマップを作成できます。

std::map<double,std::string> m1{{1000.0, s1}};

で使用するには、提供するmake_sharedのインスタンス化を指定する必要があります。initializer_list

auto foo = std::make_shared<std::map<double,std::string>>
           (std::initializer_list<std::map<double,std::string>::value_type>{{1000.0, s1}});

それは本当にぎこちなく見えます。ただし、これが定期的に必要な場合は、エイリアスを使用して整理できます。

#include <string>
#include <map>
#include <memory>

std::string s1{"temp"};

using map_ds = std::map<double,std::string>;
using il_ds = std::initializer_list<map_ds::value_type>;

auto foo = std::make_shared<map_ds>(il_ds{{1000.0, s1}});

代わりに、呼び出しをラップするテンプレート関数を定義することをお勧めします。

#include <string>
#include <map>
#include <memory>

template<class Key, class T>
std::shared_ptr<std::map<Key,T>>
make_shared_map(std::initializer_list<typename std::map<Key,T>::value_type> il)
{
    return std::make_shared<std::map<Key,T>>(il);
}

std::string s1{"temp"};
auto foo = make_shared_map<double,std::string>({{1000, s1}});
于 2016-04-06T08:55:48.233 に答える
1

あなたの問題は、実際には初期化子に中括弧を入れていないことです。それを機能させるには、次のものが必要でした。

auto foo = std::make_shared<std::map<double, std::string> >(
                         std::map<double, std::string>({{1000.0, s1}})
           );

ダブルはstd::map<double, std::string>私を悩ませます。それは本当にそれらのうちの1つを他のものから解決できるはずです...しかし、gcc 5.3.0はボールをプレーしません。

必ず二重ブレースが必要になります。(1 回はマップを初期化していると言い、1 回は各エントリを区切るためです。)

于 2016-04-06T08:55:46.853 に答える
-2

これに似た何かがそれを行うはずです...

 std::string s1("temp");  

 std::map<double, std::string> *m = new std::map<double, std::string>{{100., s1}};

 auto foo = std::shared_ptr<std::map<double, std::string>>(m);

またはワンライナーとして

auto foo2 = std::shared_ptr<std::map<double, std::string>>(new std::map<double, std::string>{{100., s1}});

(申し訳ありませんが、最初にイニシャライザリストの要件を逃しました)

于 2016-04-06T08:43:30.547 に答える