为稀疏矢量重载operator [] [英] Overloading operator [] for a sparse vector

查看:176
本文介绍了为稀疏矢量重载operator []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C ++中创建一个稀疏的向量类,如下:

I'm trying to create a "sparse" vector class in C++, like so:

template<typename V, V Default>
class SparseVector {
    ...
}

它将由 std :: map (其中 V 是存储的值的类型)。如果地图中没有元素,我们将假设它等于来自模板参数的值 Default

Internally, it will be represented by an std::map<int, V> (where V is the type of value stored). If an element is not present in the map, we will pretend that it is equal to the value Default from the template argument.

但是,我无法重载下标运算符 [] 。我必须重载 [] 运算符,因为我将这个类中的对象传递到Boost函数,期望 []

However, I'm having trouble overloading the subscript operator, []. I must overload the [] operator, because I'm passing objects from this class into a Boost function that expects [] to work correctly.

const 版本很简单:检查索引是否在地图中,return它的值如果是这样,或默认否则。

The const version is simple enough: check whether the index is in the map, return its value if so, or Default otherwise.

然而,非const版本要求我返回一个引用,这就是我遇到麻烦。如果值只是读取,我不需要(也不想)添加任何东西到地图;但如果正在写入 ,我可能需要在地图中添加一个新条目。问题是重载的 [] 不知道值是读取还是写入。它只是返回一个引用。

However, the non-const version requires me to return a reference, and that's where I run into trouble. If the value is only being read, I do not need (nor want) to add anything to the map; but if it's being written, I possibly need to put a new entry into the map. The problem is that the overloaded [] does not know whether a value is being read or written. It merely returns a reference.

有没有办法解决这个问题?

Is there any way to solve this problem? Or perhaps to work around it?

推荐答案

可能有一些非常简单的技巧,但是否则我认为 operator [] 只需要返回可以从V(并转换为V)赋值的东西,不一定是V&。所以我认为你需要返回一个对象与重载的 operator =(const V&),它创建了您的稀疏容器中的条目。

There may be some very simple trick, but otherwise I think operator[] only has to return something which can be assigned from V (and converted to V), not necessarily a V&. So I think you need to return some object with an overloaded operator=(const V&), which creates the entry in your sparse container.

您必须使用模板参数来检查Boost函数的作用,但是 - 用户定义的V转换会影响可能的转换链,例如通过阻止更多的用户定义转换在同一个链中。

You will have to check what the Boost function does with its template parameter, though - a user-defined conversion to V affects what conversion chains are possible, for example by preventing there being any more user-defined conversions in the same chain.

这篇关于为稀疏矢量重载operator []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆