我想做什么:我想将2个,3个或N个向量锁定在一起,而不是将它们复制到元组中.也就是说,将冗长放在一边,例如:
vector<int> v1 = { 1, 2, 3, 4, 5};
vector<double> v2 = { 11, 22, 33, 44, 55};
vector<long> v3 = {111, 222, 333, 444, 555};
typedef tuple<int&,double&,long&> tup_t;
sort(zip(v1,v2,v3),[](tup_t t1, tup_t t2){ return t1.get<0>() > t2.get<0>(); });
for(auto& t : zip(v1,v2,v3))
cout << t.get<0>() << " " << t.get<1>() << " " << t.get<2>() << endl;
Run Code Online (Sandbox Code Playgroud)
这应输出:
5 55 555
4 44 444
...
1 11 111
Run Code Online (Sandbox Code Playgroud)
我现在是怎么做的:我已经实现了自己的快速排序,我传递的第一个数组用于比较,排列应用于所有其他数组.我只是无法弄清楚如何重用std :: sort来解决我的问题(例如提取排列).
我试过的: boost :: zip_iterator …
所有,
这个问题的延续这一个.我认为STL错过了这个功能,但它只是我的恕我直言.
现在,问题.
考虑以下代码:
class Foo
{
public:
Foo();
int paramA, paramB;
std::string name;
};
struct Sorter
{
bool operator()(const Foo &foo1, const Foo &foo2) const
{
switch( paramSorter )
{
case 1:
return foo1.paramA < foo2.paramA;
case 2:
return foo1.paramB < foo2.paramB;
default:
return foo1.name < foo2.name;
}
}
int paramSorter;
};
int main()
{
std::vector<Foo> foo;
Sorter sorter;
sorter.paramSorter = 0;
// fill the vector
std::sort( foo.begin(), foo.end(), sorter );
}
Run Code Online (Sandbox Code Playgroud)
在任何给定的时刻,矢量都可以重新排序.该类还具有在分类器结构中使用的getter方法.
在向量中插入新元素的最有效方法是什么?
我的情况是:
我有一个网格(电子表格),它使用类的排序向量.在任何给定时间,可以重新排序向量,并且网格将相应地显示排序的数据.
现在我需要在向量/网格中插入一个新元素.我可以插入,然后重新排序然后重新显示整个网格,但这对于大网格来说效率非常低. …
我们可以在C++中使用remove_if来基于对元素进行操作的谓词在线性时间中从向量中移除元素.
bool condition(double d) {...}
vector<double> data = ...
std::remove_if (data.begin(), data.end(), condition);
Run Code Online (Sandbox Code Playgroud)
如果我的条件不依赖于价值,而是依赖指数怎么办?换句话说,如果我想删除所有奇数索引元素,或某些任意索引集等?
bool condition(int index) {//returns whether this index should be removed}
vector<double> data = ...
std::remove_if (data.begin(), data.end(), ???);
Run Code Online (Sandbox Code Playgroud)