tags:

views:

97

answers:

3

I'm trying to understand the syntax used in STL for a class. Our teacher pointed us to this website (http://www.sgi.com/tech/stl/Map.html) where I copied the code below:

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;
}

I did not know you could declare methods in structs. How does that work?

I'm assuming that with it, when you declare the map named months, using the luster in the Compare field of a map alphabetizes the map. But still unsure about how it works with the struct syntax. Thanks.

+1  A: 

in C++ structs are classes with public members by default

onof
You mean, with public members by default
glowcoder
And inherit as public by default.
Steven Jackson
@glowcoder: you're right, sorry
onof
-1 This wrong. The comments have it right, and I will remove my downvote if you edit your answer.
Space_C0wb0y
i have edited the answer
onof
+15  A: 

In C++, a struct is really just a class whose default access specifier is public and which inherits publicly by default.

In other words,

struct ltstr
{
    // ...
};

is equivalent to

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

If you want to, you can make parts of your struct protected or private, too.

The reason that struct is still in C++, even though it's redundant, is backwards compatibility.

Martin B
inheritance is public by default too, that's why I use so many structs...
Alexandre C.
@Alexandre: Good point -- I've incorporated this into the answer.
Martin B
@Alexandre: Oooops... should have checked. This means the two code snippets are not just almost equivalent but exactly equivalent...
Martin B
A: 

The struct does not add any functionality compared to a class except defaulting on public members. As such, none of that functionality is struct specific.

Nubsis