c++ - 跟随哪个会更有效率?

标签 c++ performance c++11 stdvector

我写了一段代码如下:

#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. 这两种方式之间是否存在任何效率差异,考虑到查询可能达到最大整数数字限制。
  2. 如果是,您会建议我采用上述哪一种方式?

感谢您的宝贵时间。

最佳答案

下面做一个拷贝:

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

应该是

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

那么这两个代码将是等价的。

请注意,您甚至可以移动字符串以避免字符串复制。

关于c++ - 跟随哪个会更有效率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50544849/

相关文章:

c++ - 从套接字读取和转换字节 C++ 的最快方法

performance - LSTM评估指标MAE解释

boost - 在 C++11 中的 boost::asio 套接字对象上重复 std::move

c++ - 如何在 Boost::Statechart 中向一个状态添加超过 20 个转换?

c++ - 如何在Visual C++的代码中包含if if else问题

c++ - Qt Designer 生成 C++ 代码

c++ - 数据类型类与读取器/解析器之间的耦合

java - 有没有更好的替代 File.listFiles() 方法?

c++ - 计算编译时数组时编译器相关错误

c++ - 未找到 Xcode 4.5 和 C++11 header