【问题标题】:Creating 2-D Associative Array Using Template Operator使用模板运算符创建二维关联数组
【发布时间】:2014-09-19 03:15:59
【问题描述】:

为了定义二维关联数组,我在类中编写了模板运算符以使其更接近原始数组。这是我的算子函数。

template <class T, class U, class V>
T& TwoAssocDArray<T,U,V>::operator [](U input1)[](V input2) {
    for(int i=0; i<size(); i++)
        if(stack[i].key1 == input1 && stack[i].key2 == input2) 
                return stack[i].d;
    DataPack pack;
    pack.key1 = input1;
    pack.key2 = input2;
    stack.push_back(pack);
    return stack[size].d;
}

类接口,

#ifndef _DATASTRUCTURE_H_
#define _DATASTRUCTURE_H_

#include <vector>

using namespace std;

template <class T, class U, class V>
class TwoDAssocArray {

private:
    typedef struct _DataPack {
        T d;
        U key1;
        V key2;
    } DataPack;
    vector<DataPack> stack;

public:
    int size();
    bool isIn(U input1, V input2);
    bool add(T data, U input1, V input2);
    T get(U input1, V input2);
    T& operator [](U input1)[](V input2);
};

#endif

然后我在 main() 中对其进行了测试。

int main(int argc, char *argv[]) {

    TwoDAssocArray<int, char*, char*> assocArr;

    assocArr["in1"]["in2"] = 2246001;
    cout << assocArr["in1"]["in2"] << endl;

    return 0;
}

构建并运行后,我发现它不起作用,出现十几个错误。 我认为主要原因是我不熟悉的模板语法。 我相信大量的错误总是来自一些语法错误。

如果有人愿意帮助我,我将不胜感激。

【问题讨论】:

  • 你应该检查你的设计:像arr[x][y] 这样的东西需要一个支持[] 访问的arr 对象,并返回另一个适合第二个[] 访问的对象。

标签: c++ arrays templates


【解决方案1】:

T&amp; operator [](U input1)[](V input2);

您不能像这样链接运算符。你可能已经看到operator[] 也只能接受一个参数,所以你对T&amp; operator [](U input1, V input2); 不走运

从这篇文章的标题看来,您确实希望能够做到:

assocArr["in1"]["in2"] = 2246001;

有一种方法可以获得这个功能,那就是在一维上实现它:

template <class T, class U >
class MyArray {

private:
    struct DataPack {
        T d;
        U key1;
    };

    std::vector<DataPack> stack;

public:
    T& operator[]( U key );
};

int main( void )
{
  MyArray< int, char > one_dimension;
  one_dimension[ 'a' ]; // returns an int reference

  // Now the trick
  MyArray< MyArray< int, char >, char > two_dimensions;
  two_dimensions['a']; // returns a MyArray< int, char > reference
  two_dimensions['a']['b']; // returns an int reference
}

另外,请注意我声明结构的方式,这是我的朋友 C++。要添加,不要使用char *,使用const char *。其实不要用const char *,用std::string

const char * 可以测试是否相等,但您不会比较 c 字符串中的内容,而是比较指针的地址。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2015-11-15
    相关资源
    最近更新 更多