将元组传递给函数并让它返回数字列表的最佳方法
Best way to pass tuples to a function and have it return a list of number?
例如,假设我想将值(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) {
/* ... */
}
相关文章:
- 函数如何使用引用返回所需的数字?
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 返回 int 中可被 2 c++ 整除的所有数字的总和
- C++ python 中的函数返回数字而不是字符串
- 使用非托管导出将字符串从 C# 返回到C++将返回数字
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 将 MPFR 数字转换为字符串并返回
- C++ 递归:返回数字的最小偶数
- typeid.name 返回派生类类型之前的数字
- Fibbonaci 递归代码返回错误值,始终返回下一个数字
- 为什么我的阶乘数查找器返回以C++输入的数字?(已编辑)
- 尝试编写函数尝试从字符串中提取数字,但它返回不相关的数字
- 随机函数在循环中调用时返回相同的数字!C++
- 将字符转换为ASCII返回数字太大
- 为什么此范围基于语句返回一个数字太低的范围
- 根据另一个数字的可整除性返回子数组中的索引
- 如果数组中有重复的数字,如何返回'false'?
- 递归计算满足条件的值数并返回该数字
- C++余数以较高的数字返回 7