开发者

Creating a set<char> in C++

I a开发者_C百科m coding this thing and it would be helpful to have a static const set<char> containing some elements that won't change.

class MyClass {
     private:
         static const set<char> mySet = ??  
}

How can I do this? It would be nice if you could create them from a string, like mySet("ABC"), but I can't get the syntax to work.


Something like this will work just fine:

// my_class.h
class MyClass
{
  static const std::set<char> mySet;
};

// my_class.cpp
const char *tmp = "ABCDEFGHI";
const std::set<char> MyClass::mySet(tmp,tmp+strlen(tmp));


Something like the following ought to work..

#include <iostream>
#include <set>

struct foo
{
  static std::set<char> init_chars();

  static const std::set<char> myChars;
};

const std::set<char> foo::myChars = foo::init_chars();

std::set<char> foo::init_chars()
{
  std::string sl("ABDCEDFG");
  return std::set<char>(sl.begin(), sl.end());
}

int main()
{
  std::cout << foo::myChars.size() << std::endl;
  return 0;
}


You can't initialize the variable inside the class, because it technically hasn't been defined yet (only declared).

In the class, keep static const set<char> mySet;.

In the implementation (i.e. .cpp file):

const char[] _MyClassSetChars = "ABC";

// Define and initialize the set, using
// the constructor that takes a start and end iterator
const set<char> MyClass::mySet(
    _MyClassSetChars,
    _MyClassSetChars + sizeof(_MyClassSetChars) / sizeof(_MyClassSetChars[0])
);

This also includes the terminating null character (\0) in the set, which is probably not what you want -- instead, use this:

const set<char> MyClass::mySet(
    _MyClassSetChars,
    _MyClassSetChars + (sizeof(_MyClassSetChars) / sizeof(_MyClassSetChars[0]) - 1)
);

Note that here you can use <cstring>'s strlen() (as per Let_Me_Be's answer) in place of the more general form above:

const set<char> MyClass::mySet(
    _MyClassSetChars,
    _MyClassSetChars + strlen(_MyClassSetChars)
);

Also see this question.


Have you tried static set <const char> mySet; ? Of course you need to initialize it first otherwise if you try to insert after you declare your set, it will fail.


header file:
#include<set>
class MyClass {
private:
    static const std::set<char> mySet;
}

source file:
#include<boost/assign.hpp>
const MyClass::mySet = boost::assign::list_of('A')('B')('C');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜