Const
Const

Reputation: 1356

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

I wrote a code as follows:

#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;
}

I can rewrite the above without the lambda function, something like follows:

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 );
}

Which looks pretty less code than the first one. Now the question is,

  1. Is there any efficiency differences between in these two ways, considering that, query could be up to the maximum integer numeric limit.
  2. If so, which one of above mentioned ways, would you suggest me to do?

Thanks for your time.

Upvotes: 1

Views: 59

Answers (1)

Jarod42
Jarod42

Reputation: 217245

The following does a copy:

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

It should be

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

then both code would be equivalent.

Note that you may even move the string to avoid string copies.

Upvotes: 2

Related Questions