c++ - 在 C++ (STL) 的结构中声明的方法

标签 c++ stl

我正在尝试理解 STL 中用于某个类的语法。我们的老师向我们指出了这个网站 ( http://www.sgi.com/tech/stl/Map.html ),我在其中复制了以下代码:

struct ltstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    return strcmp(s1, s2) < 0;
  }
};

int main()
{
  map<const char*, int, ltstr> months;

  months["january"] = 31;
  months["february"] = 28;
  months["march"] = 31;
  months["april"] = 30;
  months["may"] = 31;
  months["june"] = 30;
  months["july"] = 31;
  months["august"] = 31;
  months["september"] = 30;
  months["october"] = 31;
  months["november"] = 30;
  months["december"] = 31;

  cout << "june -> " << months["june"] << endl;
  map<const char*, int, ltstr>::iterator cur  = months.find("june");
  map<const char*, int, ltstr>::iterator prev = cur;
  map<const char*, int, ltstr>::iterator next = cur;    
  ++next;
  --prev;
  cout << "Previous (in alphabetical order) is " << (*prev).first << endl;
  cout << "Next (in alphabetical order) is " << (*next).first << endl;
}

我不知道您可以在结构中声明方法。这是如何运作的?

我假设,当您声明名为 months 的 map 时,使用 map 的比较字段中的光泽会按字母顺序排列 map 。但仍然不确定它如何与 struct 语法一起使用。谢谢。

最佳答案

在 C++ 中,struct 实际上只是一个类,其默认访问说明符为 public 并且默认情况下公开继承。

换句话说,

struct ltstr
{
    // ...
};

相当于

class ltstr
{
public:
    // ...
};

如果您愿意,您也可以将结构的一部分设为 protectedprivate

struct 仍在 C++ 中的原因是向后兼容,尽管它是多余的。

关于c++ - 在 C++ (STL) 的结构中声明的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3255971/

相关文章:

c++ - C++: vector 分配器行为,内存分配和智能指针

c++ - 流出扩展 ASCII

c++ - 'delete' 的数组形式是什么?

c++ - 从 double 组的未排序 vector 中删除重复项

c++ - 如何在 std::map 中使用结构作为键

c++ - 在迭代 vector 时附加到 vector ?

c++ - 摆脱 _WIN32_WINNT 未定义。

c++ - 由于模板函数,我如何避免#includ-ing <sstream>?

c++ - 迭代 std::map<X,std::vector<Y>> 并对 vector 进行排序

c++ - 在 vector 引用上调用 vector::reserve()