0

我正在尝试使用 blitz++ 数组,因为我知道它们通常比其他形式的数组提供更高的性能。是否可以使用 blitz++ 数组作为地图中的键?试

#include <map>
#include <blitz/array.h>
using namespace std;
map<blitz::Array<int,1>,int> testmap;
blitz::Array<int,1> B(3);
B = 1,2,3;
testmap.insert(make_pair(B,2));

不编译。这是错误:

在 /usr/include/c++/4.6/string:50:0 包含的文件中,

/usr/include/c++/4.6/bits/stl_function.h: 在成员函数'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = blitz::Array]' :

/usr/include/c++/4.6/bits/stl_function.h:236:22: 错误: 无法转换 'blitz::BzBinaryExprResult, blitz::Array >::T_result {aka blitz::_bz_ArrayExpr, blitz::FastArrayIterator, blitz ::Less > >}' 到 'bool' 作为回报

这是需要定义<运算符的问题吗?如果是,我可以/应该自己定义它吗?

回答

正如 Jimmy Thompson 所建议的,一个可能的解决方案是定义:

struct MyComparison 
{
bool operator() (const blitz::Array<int, 1> &lhs, const blitz::Array<int, 1> &rhs) const 
    {
        if (lhs.size() < rhs.size()) {return true;}
        else if (lhs.size() > rhs.size()) {return false;}
    else
        {
        for (int i=0; i<lhs.size(); i++)
            {
            if (lhs(i)<rhs(i)) {return true;}
            else if(lhs(i)>rhs(i)) {return false;}
            }
        }
    }
};

然后

map<blitz::Array<int,1>,int, MyComparison> testmap;
4

1 回答 1

3

The std::map documentation states that keys are compared using std::less by default. This just calls < and expects a return of true or false.

In order for you to use Blitz arrays as a key, you need to do one of the following:

  1. Create your own comparison function, like std::less, which returns a boolean value stating whether one Blitz array is 'less' than the other (how you choose to determine this is up to you). Assuming you made this function and called it MyComparison, you would then create your map as follows map<blitz::Array<int,1>, int, MyComparison> testmap;.

    struct MyComparison
    {
        bool operator() (const blitz::Array<int, 1> &lhs, const blitz::Array<int, 1> &rhs) const
        {
            // Blitz array comparison
        }
    };
    
  2. Wrap your Blitz array type (blitz::Array<int,1>) in another object, overloading the < operator for that given object and then performing your comparison in there. For example:

    class MyArrayWrapper
    {
        blitz::Array<int, 1> contents;
    
    public:
        // Constructor, etc.
    
        bool operator<(const MyArrayWrapper &rhs) const
        {
            // Blitz array comparison
        }
    };
    

Then in your current file.

    std::map<MyArrayWrapper,int> testmap;
于 2013-11-28T12:49:30.960 回答