C ++:要设置的泛型类型的向量

问题描述 投票:-1回答:2

如何将存储泛型类型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());

}
c++ generics vector copy set
2个回答
2
投票

当你说的话:

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

然后你创建一个名为v的新类型名称,这是一个任意的向量。

然后,您可以创建该类型的对象:

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

并可能调用它们的方法:

av.begin()

应该有意义吗?


1
投票

这编译:

#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

© www.soinside.com 2019 - 2024. All rights reserved.