How can I initialize a (string) array or vector with a constructor's initializing list in C++?
Consider please this example where I want to initialize a string array with arguments given to the constructor:
#include <string>
#include <vector>
class Myclass{
private:
std::string commands[2];
// std::vector<std::string> commands(2); respectively
public:
MyClass( std::string command1, std::string command2) : commands( ??? )
{/* */}
}
int main(){
MyClass myclass("foo", "bar");
return 0;
}
Besides that, which of the two types (array vs vector) is recommended for saving two strings while creating an object, and why?
With C++11, you do it like this:
class MyClass{
private:
std::string commands[2];
//std::vector<std::string> commands;
public:
MyClass( std::string command1, std::string command2)
: commands{command1,command2}
{/* */}
};
For pre-C++11 compilers, you will need to initialize the array or vector in the body of the constructor:
class MyClass{
private:
std::string commands[2];
public:
MyClass( std::string command1, std::string command2)
{
commands[0] = command1;
commands[1] = command2;
}
};
or
class MyClass{
private:
std::vector<std::string> commands;
public:
MyClass( std::string command1, std::string command2)
{
commands.reserve(2);
commands.push_back(command1);
commands.push_back(command2);
}
};
In the initializer list you may call any constructor of the class of the member you want to initialize. Take a look at std::string
and std::vector
documentation and choose the constructor that works for you.
For storing two objects I would recommend using std::pair
. However if you expect that the number may grow std::vector
is the best option.
You could use
#include <utility>
...
std::pair<string, string> commands;
commands=std::make_pair("string1","string2");
...
//to access them use
std::cout<<commands.first<<" "<<commands.second;
class Myclass{
private:
Vector<string> *commands;
// std::vector<std::string> commands(2); respectively
public:
MyClass( std::string command1, std::string command2)
{
commands.append(command1); //Add your values here
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.