[英]Time complexity of copying a string
這會調用復制構造函數嗎?這段代碼的時間復雜度是多少? 我在某處的書中讀到,它使用了復制構造函數,並且時間復雜度非常差。
string tmp = "thisisanexample";
string current = "";
for(int i = 0; i < tmp.size(); ++i){
current = current + tmp[i]; //does this require the copy constructor to copy the stuff in tmp?
}
它是原始字符串長度的二次方,因為current + tmp[i];
每次按值返回一個新字符串,但必須在current
中保留舊值的副本,因為此時是否仍需要current
的值是未知的。 當然,盡管如此,這是由足夠聰明的編譯器進行的優化。
為了使原始字符串長度的線性復雜度有效,添加std::move
以告訴編譯器您不需要保留current
的原始值,以便可以重用其 memory :
current = std::move(current) + tmp[i];
甚至更好,只需使用std::string
的復制分配,這可能更快,因為它確切知道要預先分配多少 memory 並且不需要執行上述行中涉及的幾個移動操作中的任何一個。
current = tmp;
但是,顯示的代碼中沒有直接的復制構造函數調用。 current = std::move(current) + tmp[i];
有或沒有std::move
只使用operator+
(但不同的重載)和std::string
as operator+
的移動賦值運算符以任何方式返回值。
然而, operator+
的左值重載被指定為就像復制原始字符串一樣,它使用復制構造函數,將新字符添加到它的末尾,然后返回它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.