2013-03-21 92 views
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::pair<I,T>一个std::map<I,T>,我想

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. 
+0

'A = B;''也许模板的std ::对运算符=(对 LHS,SparseElement 常量& SE);'作为游离功能。 – RedX 2013-03-21 12:52:39

+0

@RedX - 不,我也为此而堕落。 'operator ='必须是由标准定义的非静态成员函数。 – 2013-03-21 12:53:29

+0

@KirilKirov Dang,如果可能的话,本来会很好。 – RedX 2013-03-21 12:54:12

回答

0

重写的答案,帮助社区

:在不改变“索引”和SparseElement的“价值”的成员在一个解决方案
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); } 
};