繁体   English   中英

C ++中向量的泛型向量

[英]Generic vector of vectors in C++

在C ++中,有没有一种很好的方法来实现(或伪造)矢量的通用矢量的类型?

忽略何时使用向量向量是个好主意(除非有等效的东西总是更好)。 假设它确实对问题进行了正确建模,并且矩阵没有对问题进行正确的建模。 还要假设以这些东西为参数的模板化函数确实需要操纵结构(例如,调用push_back),因此它们不能仅采用支持[][]的泛型类型。

我想做的是:

template<typename T>
typedef vector< vector<T> > vecvec;

vecvec<int> intSequences;
vecvec<string> stringSequences;

但这当然是不可能的,因为无法将typedef模板化。

#define vecvec(T) vector< vector<T> >

这是很接近的,可以避免在vecvecs上运行的每个模板化函数之间重复类型,但是在大多数C ++程序员中并不流行。

您想要有template-typedefs。 还不支持在当前的C ++。 解决方法是

template<typename T>
struct vecvec {
     typedef std::vector< std::vector<T> > type;
};

int main() {
    vecvec<int>::type intSequences;
    vecvec<std::string>::type stringSequences;
}

在下一个C ++(由于2010年称为c ++ 0x,c ++ 1x)中,这是可能的:

template<typename T>
using vecvec = std::vector< std::vector<T> >;

我使用在boost库中实现的Boost.MultiArray

高温超导

您可以简单地创建一个新模板:

#include <string>
#include <vector>

template<typename T>
struct vecvec : public std::vector< std::vector<T> > {};

int main() 
{
    vecvec<int> intSequences;
    vecvec<std::string> stringSequences;
}

如果这样做,您必须记住vector的析构函数不是虚拟的,并且不要执行以下操作:

void test()
{
    std::vector< std::vector<int> >* pvv = new vecvec<int>;
    delete pvv;
}

您可以使用std::vector作为基础来实现基本的vector-of-vector类型:

#include <iostream>
#include <ostream>
#include <vector>
using namespace std;

template <typename T>
struct vecvec
{
    typedef vector<T> value_type;
    typedef vector<value_type> type;
    typedef typename type::size_type size_type;
    typedef typename type::reference reference;
    typedef typename type::const_reference const_reference;

    vecvec(size_type first, size_type second)
        : v_(first, value_type(second, T()))
    {}

    reference operator[](size_type n)
    { return v_[n]; }

    const_reference operator[](size_type n) const
    { return v_[n]; }

    size_type first_size() const
    { return v_.size(); }

    size_type second_size() const
    { return v_.empty() ? 0 : v_[0].size(); }

    // TODO: replicate std::vector interface if needed, like
    //iterator begin();
    //iterator end();

private:
    type v_;

};

// for convenient printing only
template <typename T> 
ostream& operator<<(ostream& os, vecvec<T> const& v)
{
    typedef vecvec<T> v_t;
    typedef typename v_t::value_type vv_t;
    for (typename v_t::size_type i = 0; i < v.first_size(); ++i)
    {
        for (typename vv_t::size_type j = 0; j < v.second_size(); ++j)
        {
            os << v[i][j] << '\t';
        }
        os << endl;
    }
    return os;
}

int main()
{
    vecvec<int> v(2, 3);
    cout << v.first_size() << " x " << v.second_size() << endl;
    cout << v << endl;

    v[0][0] = 1; v[0][1] = 3; v[0][2] = 5;
    v[1][0] = 2; v[1][1] = 4; v[1][2] = 6;
    cout << v << endl;
}

它只是一个模拟矩阵的非常简单的容器(只要用户承诺,可以通过改进vecvec定义或通过适当使用矩形来实现)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM