Set all values ββof an existing array to "magic numbers"
So I know I can set each array value to a "magic number" (in this case, a magic string) during construction, for example:
string * myArray[] = {"foo", "bar", "baz"};
Which would be helpful 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 lines, so I don't want to assign them one at a time)
I understand that magic numbers (or magic strings) are not good. However, the system I work on is the root of CERN, which is filled with interesting eccentricities, and I would rather not waste any more time looking for a neater approach. Therefore, it is in the interest not to allow yourself to be improved by the enemy of the good . I'm going to use magic numbers.
What's the fastest option here?
Edit; The accepted answer works great for C ++ 11. If, like me, you don't have such an option, here's a very frustrating but functional solution. (Programmers with sensitivity, please protect 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
}
source to share
Although built-in arrays do not allow for aggregate assignments, std::vector
it does:
vector<string> data;
if (someCondition) {
data = {"quick", "brown", "fox"};
} else {
data = {"jumps", "over", "the", "lazy", "dog"};
}
This approach has several advantages:
- The syntax is compact and intuitive
- Assigned units have different lengths
- The resources allocated for
std::vector
are automatically released.
source to share
I think you probably mean an array std::string
and not an array std::string*
like this:
std::string myArray[] = {"foo", "bar", "baz"};
How can I do this, allow the std::vector
array to be manipulated for me. This allows me to easily copy, move, or change new values ββlater:
std::vector<std::string> myVector = {"foo", "bar", "baz"};
myVector = {"wdd", "ghh", "yhh"};
source to share