gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:39:57 26 4
gpt4 key购买 nike

我正在尝试理解 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com