我有一个类型为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>
,其中包含std::pair<I,T>
元素,所以我想要一个解决方案而不改变SparseElement的'index'和'value'成员:
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 :(得分: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); }
};