【问题标题】:Blitz++ arrays as keys for mapsBlitz++ 数组作为地图的键
【发布时间】:2013-11-28 12:29:18
【问题描述】:

我正在尝试使用 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 = 闪电战::数组]':

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

这是否需要定义 &lt; 运算符,如果需要,我可以/应该自己定义吗?

回答

正如 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;

【问题讨论】:

  • 当你说它“不起作用”时,说明它如何不起作用是非常重要的。
  • 我在编译器错误中编辑。不过我真的不知道这是什么意思。
  • 你是对的。我编辑了命名空间std in。

标签: c++ stl blitz++


【解决方案1】:

std::map 文档指出,默认情况下使用 std::less 比较密钥。这只是调用&lt; 并期望返回truefalse

为了让您使用 Blitz 数组作为键,您需要执行以下操作之一:

  1. 创建您自己的比较函数,例如std::less,它返回一个布尔值,说明一个 Blitz 数组是否“小于”另一个(如何选择取决于您)。假设您创建了这个函数并将其命名为MyComparison,那么您将创建您的地图,如下所示map&lt;blitz::Array&lt;int,1&gt;, int, MyComparison&gt; testmap;

    struct MyComparison
    {
        bool operator() (const blitz::Array<int, 1> &lhs, const blitz::Array<int, 1> &rhs) const
        {
            // Blitz array comparison
        }
    };
    
  2. 将您的 Blitz 数组类型 (blitz::Array&lt;int,1&gt;) 包装在另一个对象中,为该给定对象重载 &lt; 运算符,然后在其中执行比较。例如:

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

然后在你当前的文件中。

    std::map<MyArrayWrapper,int> testmap;

【讨论】:

  • 感谢您的详尽回答。我选择了版本 1,因为它似乎是最轻量级的解决方案。我会将我的解决方案编辑到问题中。我没有看到如何在 Blitz++ 文档中使用 stl 样式迭代器,因此我的解决方案可能不是最有效的。实现是字典式的。如果您发现任何提高效率的方法,我很想知道。
猜你喜欢
  • 1970-01-01
  • 2017-12-02
  • 2016-11-16
  • 2013-12-04
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
相关资源
最近更新 更多