簡體   English   中英

遵循以下哪種方法更有效?

[英]Which will be more efficient to em-place in following?

我編寫了如下代碼:

#include <iostream>
#include <vector>
using type = std::vector<std::string>;

int main()
{
    int query = 5;

    std::vector< type > answer;  
    answer.reserve(query);

    auto vecReturn = [](const std::string& x, const std::string& y) -> decltype(auto)
    {
        std::vector<std::string> tempVec = {x, y};
        return tempVec;     // removed std::move() from here
    };

    while(query--)
    {
        std::string xName, yName;
        std::cin >> xName >> yName;
        answer.emplace_back( vecReturn(xName, yName) );
    }

    return 0;
}

我可以不用lambda函數來重寫上面的內容,如下所示:

using type = std::vector<std::string>;
int query = 5;
std::vector< type > answer;  // group set
answer.reserve(query);

while(query--)
{
    std::string xName, yName;
    std::cin >> xName >> yName;

    type tempVec = { xName, yName };
    answer.emplace_back( tempVec );
}

看起來比第一個要少的代碼。 現在的問題是

  1. 在這兩種方式之間是否存在效率差異 ,請考慮到query可能達到最大整數數值限制。
  2. 如果是這樣,您會建議我采取上述哪種方式?

謝謝你的時間。

下面是一個副本:

type tempVec = { xName, yName };
answer.emplace_back( tempVec );

它應該是

type tempVec = { xName, yName };
answer.emplace_back( std::move(tempVec) );

那么這兩個代碼將是等效的。

請注意,您甚至可以移動字符串以避免字符串復制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM