【问题标题】:Can I use vector as index in map structure in c++?我可以在 C++ 中使用向量作为映射结构中的索引吗?
【发布时间】:2011-02-16 16:21:23
【问题描述】:

我试图做这样的事情,但它没有编译:

class point
{
    public:
        int x;
        int y;
};



int main()
{

    vector<point> vp1;
    vector<point> vp2;
    vector<point> vp3;

    map < vector<point>, int > m;

    m[vp1] = 1;
    m[vp2] = 2;
    m[vp3] = 3;

    map < vector<point>, int >::iterator it;
    for (it=m.begin(); it!=m.end(); it++)
    {
        cout<<m[it->first]<<endl;
    }
    return 0;
}

【问题讨论】:

  • 确切的编译器错误是什么?

标签: c++ class stl vector map


【解决方案1】:

您可以将任何东西用作std::map 的索引类型,只要它支持operator&lt;(可以定义为独立函数——不必是成员函数,只要因为你可以写a &lt; b 为a 和b 是你感兴趣的类型的实例)具有通常的语义(反反身,传递,...)。或者,如果更适合您,您可以传递具有相同语义的二进制函数来代替 &lt;。

【讨论】:

  • 您不能为vector 或任何其他容器定义operator&lt;,因为它已经定义了。
  • @potatoswatter,好点子,所以您可以已经使用std::vector 作为您的std::map 的索引类型,不用多说。
【解决方案2】:

您可以,但是在映射中用作键的类型需要是可比较的,可以使用operator&lt;,或者使用您作为映射类型的第三个模板参数提供的比较函数/函子。

【讨论】:

    【解决方案3】:

    是的,你可以。与所有容器一样,向量具有可比性。生成的map 将按字典顺序对向量进行排序。

    问题是point 没有可比性。您必须为points 定义一个排序顺序,然后这将反过来定义vector&lt;point&gt; 的字典顺序。

    class point
    {
        public:
            int x;
            int y;
    };
    
    bool operator<( point const &l, point const &r ) {
        return l.x < r.x? true
             : r.x < l.x? false
             : l.y < r.y;
    }
    

    更简单的解决方案是使用std::pair,而不是定义自己的point。

    typedef pair< int, int > point; // point::first = x, point::second = y
       // pair is already comparable; order defined as in previous example
    typedef vector<point> pointvec; // OK
    

    【讨论】:

      【解决方案4】:

      您还没有定义一个函数来比较 vector&lt;point&gt; 映射要求键检查等效性和比较。

      【讨论】:

        【解决方案5】:

        您必须声明operator&lt;。它看起来像这样(请记住,您的示例代码中的三个向量实际上看起来相同):

        bool operator<(const vector<point>& left, const vector<point>& right)
        {
            return left.size() < right.size();
        }
        

        【讨论】:

        • 为了让map 行为合理,! (a&lt;b || b&lt;a) 应该暗示a 和b 是相等的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-11
        • 2020-10-26
        • 1970-01-01
        相关资源
        最近更新 更多