3

I have a sparse vector of type std::vector<SparseElement<T,I>> where SparseElement is:

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

Because I am using for filling the sparse vector a std::map<I,T> which has as elements std::pair<I,T>, I want a solution on this without changing the 'index' and 'value' members of 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.
Chameleon
  • 1,804
  • 2
  • 15
  • 21

1 Answers1

0

Rewriting the answer to help the community

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); }
};
Chameleon
  • 1,804
  • 2
  • 15
  • 21