小编Sum*_*ndo的帖子

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

我有一些使用问题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,它不是在容器中进行顺序搜索,而是进行一些对数搜索,这将比顺序搜索快得多.这种理解是否正确?

c++ enums map standard-library

9
推荐指数
2
解决办法
6266
查看次数

模板类的模板友好功能

我与中描述的问题挣扎了这个问题(声明一个模板函数作为模板类的朋友),我相信第二个答案就是我想要做的(向前声明模板函数,然后将其命名一个专门为好友).我有一个问题,一个稍微不同的解决方案是否实际上是正确的,或者只是恰好在Visual C++ 2008中工作.

测试代码是:

#include <iostream>

// forward declarations
template <typename T>
class test;

template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t);

template <typename T>
class test {
  friend std::ostream& operator<< <T>(std::ostream &out, const test<T> &t);
  // alternative friend declaration
  // template <typename U>
  // friend std::ostream& operator<<(std::ostream &out, const test<T> &t);

  // rest of class
  };

template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t) {
  // output function defined here
  }
Run Code Online (Sandbox Code Playgroud)

首先,我发现一个奇怪的事情是,如果我更改前向声明operator<<以使其不匹配(例如std::ostream& …

c++ templates visual-c++ friend-function

9
推荐指数
1
解决办法
2万
查看次数