Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a set<char> in C++

I am 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.

like image 632
Aillyn Avatar asked Apr 04 '11 20:04

Aillyn


People also ask

What is set char?

setChar() is an inbuilt method in Java and is used to change a specified char value to a specified index of a given object array. Syntax: Array.setChar(Object []array, int index, char value)

How do I create a new character?

You can create a Character object with the Character constructor: Character ch = new Character('a'); The Java compiler will also create a Character object for you under some circumstances.

How do you assign a character value?

To assign int value to a char variable in Java would consider the ASCII value and display the associated character/ digit. Here, we have a char. char val; Now assign int value to it.

What does %c mean in C?

%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.


2 Answers

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));
like image 152
Šimon Tóth Avatar answered Sep 30 '22 12:09

Šimon Tóth


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;
}
like image 22
Nim Avatar answered Sep 30 '22 12:09

Nim