3

我有一个稀疏向量类型std::vector<SparseElement<T,I>>,其中 SparseElement 是:

template<typename T, typename I = unsigned int>
struct SparseElement
{
    I index;
    T value;
    //............
    SparseElement &operator=(const std::pair<I,T> &pair);
 }

因为我用于填充std::map<I,T>作为元素的稀疏向量 a std::pair<I,T>,所以我想要一个解决方案而不更改 SparseElement 的“索引”和“值”成员:

std::pair<I,T> a;
SparseElement<T,I> b;
b = a; // This is OK!
a = b; // Is there a solution on this problem?
// on containers:
std::vector<SparseElement<T,I>> vec;
std::map<I,T> m(vec.begin(), vec.end()); // Not working.
vec.assign(m.begin(), m.end()); // Working.
4

1 回答 1

0

重写答案以帮助社区

template<typename T, typename I = unsigned int>
struct SparseElement
{
    //..........
    I index;                //!< Index of element in vector
    T value;                //!< Value of element
    //..........
    //! Template copy constructor from a different type of \p std::pair
    //! This is useful for conversion from MapVector to SparseVector
    template<typename T2, typename I2>
    SparseElement(const std::pair<I2,T2> &s) : index(s.first), value(s.second) {}
    //..........
    //! Template copy assign from a different type of \p std::pair
    //! This is useful for conversion from MapVector to SparseVector
    template<typename T2, typename I2>
    SparseElement &operator=(const std::pair<I2,T2> &s) { index = s.first; value = s.second; return *this; }

    //! Implicit conversion from SparseElement to a \p std::pair
    //! This is useful for conversion from SparseVector to MapVector
    operator std::pair<const I,T>() { return std::pair<const I,T>(index, value); }
};
于 2013-03-21T17:48:08.060 回答