使用容器中的第n个元素,但使用另一个键
use n_th element in a container, but with another key
我有两个向量。一个实际保存数据(比如浮点数),另一个保存索引。我想在nth_element
传递下标向量,但是我想让比较是由实际保存数据的向量来完成的。我在考虑一个函子,但我猜它只提供()运算符。我通过使数据向量成为一个全局向量来实现这一点,但当然这不是我想要的。
std::vector<float> v; // data vector (global)
bool myfunction (int i,int j) { return (v[i]<v[j]); }
int find_median(std::vector<int> &v_i)
{
size_t n = v_i.size() / 2;
nth_element(v_i.begin(), v_i.begin()+n, v_i.end(), myfunction);
return v_i[n];
}
可以使用以下函子:
class comp_with_indirection
{
public:
explicit comp_with_indirection(const std::vector<float>& floats) :
floats(floats)
{}
bool operator() (int lhs, int rhs) const { return floats[lhs] < floats[rhs]; }
private:
const std::vector<float>& floats;
};
然后你可以这样使用:
int find_median(const std::vector<float>& v_f, std::vector<int> &v_i)
{
assert(!v_i.empty());
assert(v_i.size() <= v_f.size());
const size_t n = v_i.size() / 2;
std::nth_element(v_i.begin(), v_i.begin() + n, v_i.end(), comp_with_indirection(v_f));
return v_i[n];
}
注意:在c++ 11中,你可以使用lambda来代替命名函数类。
int find_median(const std::vector<float>& v_f, std::vector<int> &v_i)
{
assert(!v_i.empty());
assert(v_i.size() <= v_f.size());
const size_t n = v_i.size() / 2;
std::nth_element(
v_i.begin(), v_i.begin() + n, v_i.end(),
[&v_f](int lhs, int rhs) {
return v_f[lhs] < v_f[rhs];
});
return v_i[n];
}
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 如何从一个容器中获取某些元素并将其转换插入到另一个容器中?
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 保留从一个多集复制到另一个多集的元素的顺序
- 如何从一个向量中删除最小元素并添加到另一个向量,而第一个变为空?
- C++:检查向量中的元素是否大于另一个具有相同索引的元素的有效方法?
- 从另一个向量中搜索和找到元素的有效方法
- 如果在C 中已经回荡了另一个相同值的阵列元素,请防止循环回荡
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 如何将元素添加到从另一个线程绑定到 XAML 的 IVector
- 使用对另一个元组不同类型的元素的非常量引用来初始化元组的元素
- 并行算法将向量的元素分配到另一个元素的元素
- C 初始化矢量每个元素,带有另一个向量的参数
- 模板函数,它使用 n_copy 复制前 n 个元素形成一个向量,另一个向量导致编译错误
- 递增迭代器以指向另一个迭代器的下一个元素
- 如何转换一个类方法以修改另一个类的私有元素?
- 将映射从第二个元素复制到另一个地图
- 使用擦除-删除范例将元素从一个向量移动到另一个向量