簡體   English   中英

C ++:要設置的通用類型的向量

[英]C++: vector of generic type to set

如何將存儲通用類型A的共享指針的向量復制到集合中?

#include <memory>
#include <vector>
#include <set>

template <typename T>
class A {
   public:
      T a;
      A(const T &a_) : a(a_) {}
};

template <typename Type>
class comp
{

   bool operator() (const Type & a1, const const Type &a2) const {
       return (a1->get().a < a2->get().a);
   }
};

不幸的是,這種構造不起作用

int main() {
   using v = std::vector <std::shared_ptr <A <double> >> ;
   using s = std::set <std::shared_ptr <A <double> >,comp <std::shared_ptr <A <double> > > >;

   s.insert(v.begin(), v.end()); //Trying to insert

   return 0;
}

並且發生以下錯誤(VS 2015):

error C2059: syntax error: '.'

謝謝你的幫助。

更新的解決方案:

感謝您對使用的評論,更新后的有效解決方案是:

template <typename T>
class A {
    public:
        T a;
        A(const T &a_) : a(a_) {}
};

template <typename Type>
class comp
{
    public:
    bool operator() (const Type & a1, const const Type &a2) const {
        return (a1.get()->a < a2.get()->a);
    }
};


int main() {
    std::vector <std::shared_ptr <A <double> >> v;
    std::set <std::shared_ptr <A <double> >, comp <std::shared_ptr <A <double> > > > s(v.begin(), v.end());

}

當您說類似:

using v = std::vector <std::shared_ptr <A <double> >> ;

然后創建一個名為v的新類型名稱,該名稱是任何東西的向量。

然后,您可以創建該類型的對象:

v av;      // av is an object of type v

並可能在它們上調用方法:

av.begin()

應該有意義。

這樣編譯:

#include <vector>
#include <set>
#include <memory>

template <typename T>
class A {
public:
    T a;
    A(const T &a_) : a(a_) {}
};

template <typename Type>
struct comp
{
    bool operator() (Type const &a1, Type const &a2) const
    {
        return (a1.get()->a < a2.get()->a);
    }
};

int main() {

    using v = std::vector <std::shared_ptr <A <double>>>;
    using s = std::set<std::shared_ptr <A <double>>, comp<std::shared_ptr <A <double>>>>;

    v vec;
    s set(vec.begin(), vec.end());

    return 0;
}

https://ideone.com/kOPGjt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM