这个问题是本文的另一面如何有效地将std :: string复制到向量中
我通常以这种方式复制向量(null终止字符串)
std::string s((char*)&v[0]);
Run Code Online (Sandbox Code Playgroud)
或者(如果已经声明了字符串)就像这样
s = (char*)&v[0];
Run Code Online (Sandbox Code Playgroud)
它完成了工作,但也许有更好的方法.
编辑
C风格的演员是丑陋的,我被告知这是怎么回事
s = reinterpret_cast<char*>(&vo[0]);
Run Code Online (Sandbox Code Playgroud) 通常,我想确保自己一次处于函数主体的顶部。我执行此操作的不同方法是:
// I don't like this much as it stops the program when I may not want to
assert( idx < v.size() );
if( !(idx < v.size()) )
{
// take corrective action ...
}
if( v.size() <= idx )
{
// take corrective action ..
}
Run Code Online (Sandbox Code Playgroud)
在第二种和第三种方法之间(也许还有其他方法),哪种方法更有效?