【问题标题】:Why is my implementation of C++ map not storing values?为什么我的 C++ 映射实现不存储值?
【发布时间】:2009-03-27 19:33:08
【问题描述】:

我有一个名为 ImageMatrix 的类,它以递归方式实现 C++ 映射;最终结果是我有一个 3 维数组。

typedef uint32_t VUInt32;
typedef int32_t VInt32;

class ImageMatrix
{
public:
    ImageMatrixRow operator[](VInt32 rowIndex)
private:
    ImageMatrixRowMap rows;
};

typedef std::map <VUInt32, VInt32> ImageMatrixChannelMap;

class ImageMatrixColumn
{
public:
    VInt32 &operator[](VUInt32 channelIndex);
private:
    ImageMatrixChannelMap channels;
};

typedef std::map<VUInt32, ImageMatrixColumn> ImageMatrixColumnMap;

class ImageMatrixRow
{
public:
    ImageMatrixColumn operator[](VUInt32 columnIndex);
private:
    ImageMatrixColumnMap columns;
};

typedef std::map<VUInt32, ImageMatrixRow> ImageMatrixRowMap;

每个运算符只返回一个映射包装类,如下所示:

ImageMatrixRow ImageMatrix::operator[](VInt32 rowIndex)
{
    return rows[rowIndex];
}

ImageMatrixColumn ImageMatrixRow::operator[](VUInt32 columnIndex)
{
    return columns[columnIndex];
}

VInt32 &ImageMatrixColumn::operator[](VUInt32 channelIndex)
{
    return channels[channelIndex];
}

基本上,当我将值设置为 100 并将值测试到 cout 时,它显示为 0,而不是我设置的数字。

for (VUInt32 a = 0; a < GetRowCount(); a++)
{
    for (VUInt32 b = 0; b < GetColumnCount(); b++)
    {
        for (VUInt32 c = 0; c < GetChannelCount(); c++)
        {
            VInt32 value = 100;
            matrix[a][b][c] = value;

            VInt32 test = matrix[a][b][c];

                            // pixel = 100, test = 0 - why?
            cout << pixel << "/" << test << endl;
        }
    }
}

注意:我已经对这个例子的原始代码进行了修改,以便占用更少的空间,因此可能会出现一些语法错误(请不要指出)。

【问题讨论】:

    标签: c++ map


    【解决方案1】:

    以下运算符按值返回,不写入修改实际数据。

    ImageMatrixRow ImageMatrix::operator[](VInt32 rowIndex);
    
    ImageMatrixColumn ImageMatrixRow::operator[](VUInt32 columnIndex);
    

    用途:

    ImageMatrixRow& ImageMatrix::operator[](VInt32 rowIndex)
    
    
    ImageMatrixColumn& ImageMatrixRow::operator[](VUInt32 columnIndex)
    

    【讨论】:

    • 是的,他的代码只是偶然编译,因为他记得从 ImageMatrixColumn::operator[] 返回一个引用
    • 谢谢,太尴尬了!老实说,我认为我正在返回参考资料......应该在大学里更加关注:p
    【解决方案2】:

    除了一个返回值之外,你所有的 operator[] 函数都应该返回引用。

    【讨论】:

      【解决方案3】:

      您的 ImageMatrixRowImageMatrixColumn operator[]() 方法返回副本,而不是引用。

      【讨论】:

        【解决方案4】:

        “每个都返回一个引用” - 你确定吗?

        它们看起来像是返回了存储地图的副本,而不是对它们的引用。

        试一试,例如:

        ImageMatrixRow & ImageMatrix::operator[](VInt32 rowIndex)
        

        注意&amp; 符号。

        【讨论】:

          猜你喜欢
          • 2012-02-14
          • 2011-01-11
          • 1970-01-01
          • 2012-10-11
          • 1970-01-01
          • 1970-01-01
          • 2021-12-30
          • 1970-01-01
          • 2020-12-12
          相关资源
          最近更新 更多