I have class with two static member objects, one of type int and one
of type vector<int>.
static int myStaticMemberInt
static vector<int> myStaticMemberVector;
I know how to initialize the int member:
MyClass::myStaticMemberInt = 99;
But what is the best way to initialzie myStaticMemberVector?
In particular, the initialization code I want to use is somewhat
complex, and involves processing a series of strings to come up with
each int value for the vector. I'd appreciate any ideas on how to
solve this problem.
Thanks,
cpp
How about making access to the vector be via a static member function,
rather than providing direct access to the vector? That way you can have
the function do initialization the first time it is called. In the
following example, I manipulate the vector through a pointer in main, so I
can re-use the pointer in multiple calls to the static function (which I've
named the same as you named your vector.). The syntax would be cleaner,
though, if I simply used a reference instead of the pointer. But the
implementation of the class and member function would remain the same.
Note also that this example provides no protection for the vector itself;
it may as well be public. To control client operations, you can provide
the usual interface functions (overloaded const and con-const subscript
operators, for example), make myStaticMemberVector() private, and have your
interface functions internally call the static function to get the
initialization behavior you want...
#include <iostream>
#include <vector>
class T
{
public:
static std::vector<int> &myStaticMemberVector();
private:
static int myStaticMemberInt; // = whatever;
static std::vector<int> vector_;
};
std::vector<int> T::vector_;
std::vector<int> &T::myStaticMemberVector()
{
static bool first_time = true;
if (first_time)
{
vector_.push_back(10);
vector_.push_back(20);
vector_.push_back(30);
vector_.push_back(40);
first_time = false;
}
return vector_;
}
int main()
{
using namespace std;
std::vector<int> *vi = &T::myStaticMemberVector();
for (int i = 0; i < vi->size(); i++)
cout << "vector[" << i << "] = " << (*vi)
<< endl;
cout << endl;
vi->push_back(50);
vi = &T::myStaticMemberVector(); // show no init this time
for (int i = 0; i < vi->size(); i++)
cout << "vector[" << i << "] = " << (*vi) << endl;
return 0;
}
Output:
vector[0] = 10
vector[1] = 20
vector[2] = 30
vector[3] = 40
vector[0] = 10
vector[1] = 20
vector[2] = 30
vector[3] = 40
vector[4] = 50
-leor