0

I am doing a bit from Stroustrup's "Principles and practice" chapter 10, where he offers to create a table for converting numbers of months to their names and vice versa. That table is in a form of a string vector, which is then used by several functions declared in the header file of the program. I tried to go an easy way and declare + init the vector in the same header, so that all the functions could see it:

std::vector<std::string> monthNames(12);
monthNames[0] = "jan";
monthNames[1] = "feb";
monthNames[2] = "mar";
monthNames[3] = "apr";
monthNames[4] = "may";
monthNames[5] = "jun";
monthNames[6] = "jul";
monthNames[7] = "aug";
monthNames[8] = "sep";
monthNames[9] = "oct";
monthNames[10] = "nov";
monthNames[11] = "dec";

Now G++ does not seem to understand what I'm trying to do:

In file included from temperature.cpp:1:
./Temperature.h:48:1: error: C++ requires a type specifier for all declarations
monthNames[0] = "jan";
^~~~~~~~~~
./Temperature.h:49:1: error: C++ requires a type specifier for all declarations
monthNames[1] = "feb";

...

I understand in general, that declaring a global vector in a header is a poor practice, but in this example it seems to be a reasonable substitute for 12 {if...elses} in the functions that convert nums to month names and vice versa:

    const std::string& intToMonth(int num) {
    if ( num < 1 || num > 12 )
        throw BadMonthException();

    return monthNames[num-1];
    }

So I have two questions:

1) Why would compiler not let me initialize the vector?

2) Is there a sexier way to make it all work (without a global vector)?

Denys Triasunov
  • 539
  • 1
  • 4
  • 24

2 Answers2

1

Providing the include file isn't included more than once, you can use an anonymous namespace and an initialisation list, something like:

 namespace {
    std::vector<std::string> monthNames{ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"};
}
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
1

You can try something like this (works for cpp standards older than c++11):

const std::string _monthNames[] = { "jan", "feb", ... };
std::vector<std::string> monthNames(_monthNames,
                                    _monthNames+sizeof(_monthNames)/sizeof(std::string));

Regarding your questions:

  1. The statements cannot be used as declarations according to C++ grammar rules.
  2. Consider using static function variables -- the variables that are visible only in the scope of the function, but having the same lifetime as global variables.
tonso
  • 1,760
  • 1
  • 11
  • 19