使用std :: map时这些适当的做法是什么?

Nav*_*K N 9 c++ enums map standard-library

我有一些使用问题std::map:

  1. enumstd::map一个良好的实践中使用一个关键?请考虑以下代码:

    enum Shape{
        Circle,
        Rectangle
    };
    
    int main(int argc, char* argv[])
    {
         std::map<Shape,std::string> strMap;
         // strMap.insert(Shape::Circle,"Circle"); // This will not compile
         strMap[Shape::Circle] = "Circle";         // But this will work
         return 0;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在上面的示例中,为什么insert()在重载[]运算符正常工作时调用生成编译器错误?建议将哪些方法插入到std::map

  3. 我知道当在类find()上使用该方法时std::map,它不是在容器中进行顺序搜索,而是进行一些对数搜索,这将比顺序搜索快得多.这种理解是否正确?

gim*_*mpf 12

  1. 将枚举作为key_type本身并不坏.(编辑)但是如果你只使用顺序枚举值,那么std::vector使用O(1)访问会更好.
  2. insert必须像这样使用:mapVar.insert(make_pair(key, value)); 另见cppreference.com.
  3. 是的,std::map具有O(log(n))查找,由标准保证,如果n足够高,则比O(n)快.


Ala*_*lan 5

插入失败,因为value_type是std :: pair