3

So I know that I can set each value of an array to a "magic number" (in this case a magic string) at the time of construction like;

string * myArray[] = {"foo", "bar", "baz"};

What would be useful is if I could declare my array;

string * myArray[100];

Then later (in an if statement) set its values;

myArray = {"foo", "bar", "baz"};

(the actual array will contain ~30 magic strings, so I don't want to assign them all one at a time)

I understand that magic numbers (or magic strings) are not good. However the system I am working in is CERN's root, which is full of interesting eccentricities, and I would rather not to lose any more time searching for a neater approach. So in the interest of not letting perfect become the enemy of the good I am going to use magic numbers.

What's the quickest option here?

Edit; The accepted answer works great for c++11. If, like me, you don't have that option, here is a very-nasty-but-functional solution. (Programmers with sensibilities please shield your eyes.)

int numElements;
vector<char *> myArray;
if(someCondition){
  numElements = 3;
  string * tempArray[] = {"foo", "bar", "baz"}]
  for(int n = 0; n < numElements; n++){
    const char * element = (tempArray[n]);
    myArray.push_back(element);
  }
}else if(anoutherCondition){
//More stuff
}
Jekowl
  • 317
  • 2
  • 12

2 Answers2

3

Although built-in arrays do not allow aggregate assignments, std::vector lets you do this:

vector<string> data;
if (someCondition) {
    data = {"quick", "brown", "fox"};
} else {
    data = {"jumps", "over", "the", "lazy", "dog"};
}

Demo.

This approach has several advantages:

  • The syntax is compact and intuitive
  • Assigned aggregates are allowed to have different length
  • Resources allocated to std::vector are freed automatically.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

I think you probably mean an array of std::string rather than an array of std::string* like this:

std::string myArray[] = {"foo", "bar", "baz"};

The way I would do this is to allow a std::vector to manage the array for me. That allows me to easily copy, move or swap new values in later:

std::vector<std::string> myVector = {"foo", "bar", "baz"};

myVector = {"wdd", "ghh", "yhh"};
Galik
  • 47,303
  • 4
  • 80
  • 117