Mik*_*580 3 c++ stdstring stdvector c++03
首先,如果这是一个令人眼花缭乱的简单而明显的问题,我想道歉.我知道对于拥有专业知识的人来说,这是一件相当容易的事情.C++ 11允许以列表形式初始化向量:
std::vector<std::string> v = {
"this is a",
"list of strings",
"which are going",
"to be stored",
"in a vector"};
Run Code Online (Sandbox Code Playgroud)
但这在旧版本中不可用.我一直在努力想出填充字符串向量的最佳方法,到目前为止我唯一能想到的就是:
std::string s1("this is a");
std::string s2("list of strings");
std::string s3("which are going");
std::string s4("to be stored");
std::string s5("in a vector");
std::vector<std::string> v;
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
v.push_back(s5);
Run Code Online (Sandbox Code Playgroud)
它有效,但写作有点苦差事,我相信有更好的方法.
规范的方法是在合适的头文件中定义begin()和end()运行,并使用以下内容:
char const* array[] = {
"this is a",
"list of strings",
"which are going",
"to be stored",
"in a vector"
};
std::vector<std::string> vec(begin(array), end(array));
Run Code Online (Sandbox Code Playgroud)
函数begin()和end()定义如下:
template <typename T, int Size>
T* begin(T (&array)[Size]) {
return array;
}
template <typename T, int Size>
T* end(T (&array)[Size]) {
return array + Size;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1168 次 |
| 最近记录: |