While working in a project with some legacy code i found this function:
std::vector<std::string> Object::getTypes(){
static std::string types [] = {"type1","type2", "type3"};
return std::vector<std::string> (types , types +2);
}
I would probably have written this as:
std::vector<std::string> Object::getTypes(){
std::vector<std::string> types;
types.push_back("type1");
types.push_back("type2");
types.push_back("type3");
return types;
}
Is this merely a style choice or is there something I'm missing? Any help would be greatly appreciated. Sorry if this is too basic.
Update: Actually found different classes that override the same method do it one way or the other, so It's even more ambiguous. I would make them all the same but would prefer the better approach, if there is one.
Edit
Please note that the above legacy code is incorrect because it initializes the vector with only the first two elements of the array. However, this error has been discussed in the comments and thus should be preserved.
The correct initialization should have read as follows:
...
return std::vector<std::string> (types, types + 3);
...
return std::vector<std::string>{"type1","type2", "type3"};.return {"type1","type2", "type3"};.std::beginandstd::end(which you should, of course).