将元组传递给函数并让它返回数字列表的最佳方法

Best way to pass tuples to a function and have it return a list of number?

本文关键字:数字 返回 列表 方法 最佳 元组 函数      更新时间:2023-10-16

例如,假设我想将值(1,2),(2,3),(3,4)等传递到函数中,并让它返回一个数字列表,无论它们是什么,即经过一些操作后的1,3,5,3,6。 在C++实现这一结果的最佳方法是什么? 从 python 迁移后,在这里做起来似乎要困难得多,有什么帮助吗?

通常,您将使用 std::vector 容器及其方法 push_back .然后你可以返回向量(按值返回它,不要费心动态分配它,因为你的编译器可能支持移动语义)。

std::vector<int> func(
    const std::tuple<int, int>& a, const std::tuple <int, int>& b)
{
     std::vector<int> ret;
     ret.push_back(...);
     ret.push_back(...);
     return ret;
}

我并不是说这是最好的方法,但我认为它非常好,也来自内存复制前景,请注意我避免返回vector(昂贵,因为它隐式调用operator=):

#include <vector>
using namespace std;
/**
 * Meaningful example: takes a vector of tuples (pairs) values_in and returns in
 * values_out the second elements of the tuple whose first element is less than 5
 */
void less_than_5(const vector<pair<int, int> >& values_in, vector<int>& values_out) {
    // clean up the values_out
    values_out.clear();
    // do something with values_in
    for (vector<pair<int, int> >::iterator iter = values_in.begin(); iter != values_in.end(); ++iter) {
        if (iter->first < 5) {
            values_out.push_back(iter->second);
        }
    }
    // clean up the values_out (again just to be consistent :))
    values_out.clear();
    // do something with values_in (equivalent loop)
    for (int i = 0; i < values_in.size(); ++i) {           
        if (values_in[i].first < 5) {
            values_out.push_back(values_in[i].second);
        }
    }        
    // at this point values_out contains all second elements from values_in tuples whose 
    // first is less than 5
}
void function(const std::vector<std::pair<int,int>> &pairs, 
    std::vector<int> &output) {
  /* ... */
}