如何有效地将 std::string 复制到向量中 [英] How to efficiently copy a std::string into a vector
问题描述
我有一个字符串
I have a string
std::string s = "Stack Overflow";
我需要复制到一个向量中.这就是我的做法
That I need to copy into a vector.
This is how I am doing it
std::vector<char> v;
v.reserve(s.length()+1);
for(std::string::const_iterator it = s.begin(); it != s.end(); ++it)
{
v.push_back( *it );
}
v.push_back( '\0' );
但我听说范围操作更有效.所以我在想这样的事情
But I hear range operation are more efficient. So I am thinking something like this
std::vector<char> v( s.begin(), s.end());
v.push_back('\0');
但是在这种情况下这样更好吗?插入 '\0' 时潜在的重新分配怎么样?
我正在考虑的另一种方法是
But is this better in this case? What about the potential re-allocation when inserting '\0'?
Another approach I am thinking is this
std::vector<char> v(s.length()+1);
std::strcpy(&v[0],s.c_str());
也许很快但可能不安全?
编辑
必须是可以在 C 函数中使用(读/写)的空终止字符串
Perhaps fast but potentially unsafe?
EDIT
Has to be a null terminated string that can be used ( read/write ) inside a C function
推荐答案
如果您确实需要一个向量(例如,因为您的 C 函数修改了字符串内容),那么以下内容应该为您提供想要,在一行中:
If you really need a vector (e.g. because your C function modifies the string content), then the following should give you what you want, in one line:
std::vector<char> v(s.c_str(), s.c_str() + s.length() + 1);
由于 c_str()
返回一个以空字符结尾的字符串,您可以将它整个复制到向量中.
Since c_str()
returns a null-terminated string, you can just copy it whole into the vector.
然而,我实际上不确定这个构造函数的优化程度.我确实知道 std::copy
已尽可能优化,所以也许(测量!)以下更快:
However, I’m not actually sure how optimised this constructor is. I do know that std::copy
is as optimised as it gets, so perhaps (measure!) the following is faster:
std::vector<char> v(s.length() + 1);
std::copy(s.c_str(), s.c_str() + s.length() + 1, v.begin());
如果C函数不修改字符串,直接传递c_str()
,去掉const-ness.这是安全的,只要 C 函数只读取字符串.
If the C function doesn’t modify the string, just pass c_str()
directly, and cast away const-ness. This is safe, as long as the C function only reads from the string.
这篇关于如何有效地将 std::string 复制到向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!