C ++优雅的解决方案分区问题 [英] C++ Elegant solution to partition problem

查看:191
本文介绍了C ++优雅的解决方案分区问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在
STL中看到最优雅的STL像分区算法的扩展:

 给定一个ints的向量,分割向量使得正整数出现
到负整数的前面
AND
返回一个映射< int,int>其中map [i] = j意味着索引i的整数现在为j。

显然,第一部分(没有第二个要求)是

  partititon(vec.begin(),vec.end(),IsEven)

我没有看到这样做的方法,没有实际重新实现分区和构建
映射。

解决方案

将int的向量复制到如下的向量中:

  struct ValIdx 
{
int val;
size_t idx;
};

使用适当的函子进行分区,然后迭代结果,将ints复制回来并构建映射。


I would like to see the most elegant STL like extension to the partition algorithm in the STL:

given a vector of ints, partition the vector so that the positive integers appear
to the front of the negative integers
AND
return a map<int, int> where map[i]=j means that integer at index i is now at j.

Obviously the first part (without the second requirement) is something like

partititon(vec.begin(), vec.end(), IsEven)

I can't see a way to do this without actually reimplementing partition and building the map along the way.

解决方案

Copy your vector of ints into a vector of something like:

struct ValIdx
{
    int val;
    size_t idx;
};

Partition with an appropriate functor, then iterate over the result copying the ints back out and building your map.

这篇关于C ++优雅的解决方案分区问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆