C++ 按排序顺序遍历集合而不修改集合的算法?
假设我们有这样一个集合:C++ 按排序顺序遍历集合而不修改集合的算法?,c++,algorithm,C++,Algorithm,假设我们有这样一个集合:{12,10,4,5,7} 我希望保留集合的顺序,这样索引将保持一致,但以排序顺序遍历集合,如so{12,10,7,5,4} 我想到的是创建另一个指向元素的指针集合,然后对指针进行排序 你的想法是什么?像这样的算法已经在C++中实现了吗? 编辑:在我的例子中,我有一个向量,我希望根据内部向量的总和以非递增的顺序遍历外部向量集合。方法之一(对于链接列表)是添加两级指针:一级用于原始顺序,另一级用于降序,如 typedef struct node{ int key;
{12,10,4,5,7}
我希望保留集合的顺序,这样索引将保持一致,但以排序顺序遍历集合,如so{12,10,7,5,4}
我想到的是创建另一个指向元素的指针集合,然后对指针进行排序
你的想法是什么?像这样的算法已经在C++中实现了吗?
编辑:在我的例子中,我有一个向量
,我希望根据内部向量的总和以非递增的顺序遍历外部向量集合。方法之一(对于链接列表)是添加两级指针:一级用于原始顺序,另一级用于降序,如
typedef struct node{
int key;
struct node* next;
struct node* next_descending;
};
您可以将索引值存储在一个数组中,然后编写/调整排序算法,根据索引值在原始数组中的索引内容对索引值进行排序。如果您希望在添加和删除元素的同时保持这两个顺序,则可以使用boost multi-index: 除了按相反顺序排序外,该页面中的示例与您想要的基本相同:
multi_index_container<
int,
indexed_by<
sequenced<>, // sequenced type
ordered_unique<identity<int> > // another index
>
> s;
然后可以在pairvec上迭代。如果需要,将
设置为非常量迭代器。不确定运行时/内存约束是什么,但最简单实用的解决方案是将std::vector
中的所有项插入std::multiset
中,然后从头到尾遍历multiset
。整个运行时将是O(n*log(n)),并且需要O(n)个额外内存用于multiset
#include <set>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> data;
data.push_back(12);
data.push_back(10);
data.push_back(4);
data.push_back(5);
data.push_back(7);
multiset<int> sorted(data.begin(), data.end());
for (multiset<int>::iterator it=sorted.begin();it!=sorted.end();it++)
cout<<*it<<" ";
cout<<endl;
for(vector<int>::iterator it=data.begin();it!=data.end();it++)
cout<<*it<<" ";
cout<<endl;
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
矢量数据;
数据。推回(12);
数据。推回(10);
数据。推回(4);
数据。推回(5);
数据。推回(7);
多集排序(data.begin(),data.end());
for(multiset::iterator it=sorted.begin();it!=sorted.end();it++)
我想这就是我当时的想法,但可能比我的解释好一点。谢谢:)专利说受让人是“LSI公司”不是微软。我在这里遗漏了什么吗?@Chris:是的,尽管你的律师准备打架,但该专利似乎涵盖了双重链接列表,以及其他公然的现有技术案例,当时在科技媒体上广受嘲笑。不知道所有者是否试图强制执行该专利,或者是否有人试图在cou中嘲笑该专利rt.怪异,我想你是对的。不管怎样,google.com/patents/about?id=Szh4AAAAEBAJ&dq=7028023是双链接列表的专利。即使它是假的,在法庭上打官司也会非常昂贵…@Chris:我认为这项专利不适用于欧洲,特别是在法国,我认为你不能为一个想法申请专利,但是你可以拥有一个imp它的实现。谢谢你的回答。我以前不知道boost multi index。但对于我正在做的事情来说,它似乎有点太复杂了,这只是一个一次性的操作。
#include <set>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> data;
data.push_back(12);
data.push_back(10);
data.push_back(4);
data.push_back(5);
data.push_back(7);
multiset<int> sorted(data.begin(), data.end());
for (multiset<int>::iterator it=sorted.begin();it!=sorted.end();it++)
cout<<*it<<" ";
cout<<endl;
for(vector<int>::iterator it=data.begin();it!=data.end();it++)
cout<<*it<<" ";
cout<<endl;
return 0;
}