C ++:如何创建存储任何类型的向量的向量? [英] C++: How to create a vector storing vectors of any type?

查看:276
本文介绍了C ++:如何创建存储任何类型的向量的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将任何类型的向量存储在另一个向量中。所以,例如我有两个向量实例,std :: vector v1和std :: vector v2。我想把它们变成一个向量。我已经尝试这样:

I'd like to store vectors of any type in another vector. So, for example I have two vector instances, "std::vector v1" and "std::vector v2". And I would like to put them into a vector. I already tried like this:

std::vector<int> v1;
std::vector<std::string> v2;
std::vector< std::vector<boost::any> > vc;
vc.push_back(v1);

还有其他几种方法,但没有任何效果。您知道一个可能的解决方案吗?

And several other ways, but nothing works. Do you know a possible solution?

谢谢!

推荐答案

但是如果你坚持,这是可憎的开始:

But if you insist, here is the beginnings of such an abomination:

#include <vector>
#include <memory>
#include <functional>
#include <boost/any.hpp>


class any_vector
{
  using any = boost::any;
  struct concept
  {
    virtual any at(std::size_t) = 0;
    virtual any at(std::size_t) const = 0;
    virtual ~concept() = default; 
  };

  template<class T>
    struct model : concept
    {
      model(std::vector<T> v) : _data(std::move(v)) {}
      virtual any at(std::size_t i) override { return boost::any(std::ref(_data.at(i))); }
      virtual any at(std::size_t i) const override { return boost::any(std::cref(_data.at(i))); }
      std::vector<T> _data;
    };

  concept& deref() { return *vec_; }
  concept const& deref() const { return *vec_; }

  std::unique_ptr<concept> vec_;

  public:

  boost::any at(std::size_t i) const { return deref().at(i); }
  boost::any at(std::size_t i) { return deref().at(i); }

  template<class T>
  any_vector(std::vector<T> v)
  : vec_(std::make_unique<model<T>>(std::move(v)))
  {}
};

int main()
{
  any_vector a(std::vector<int> { 1, 2, 3 });
  any_vector b(std::vector<double> { 1.1, 2.2, 3.3 });

  std::vector<any_vector> va;
  va.push_back(std::move(a));
  va.push_back(std::move(b));


  auto anything = va.at(0).at(1);
  // how you deal with the resulting `any` is up to you!
}

注意,any_vector :: at(x)它将包含一个const-ref或一些对象的引用。

Note that any_vector::at(x) will return a boost::any which will either contain a const-ref or a ref to some object.

编写有用的代码,推断什么是东西,并使用它将是一个挑战。 。

Writing useful code that deduces what the thing is and uses it is going to be a challenge...

这篇关于C ++:如何创建存储任何类型的向量的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆