我開始編程,所以對於我缺乏知識感到抱歉。 如何在特定順序中設置向量中的元素?我想以不會有相鄰元素相鄰的方式交換元素。 例如向量包含:C++ - 按特定順序排列矢量元素
{1, 2, 2, 2, 3, 3, 4, 4, 4}
,我想它是這樣的:
{1, 2, 4, 3, 4, 2, 3, 2, 4}
感謝您的幫助。
編輯: 你好,我發現不是最好的解決方案,也許你可以看看,並糾正它?現在
map<unsigned,unsigned> Map;
for(vector<unsigned>::iterator i=V.begin();i!=V.end();++i)
{
map<unsigned,unsigned>::iterator f=Map.find(*i);
if(f==Map.end()) Map[*i]=1;
else ++f->second;
}
for(bool more=true;more;)
{
more=false;
for(map<unsigned,unsigned>::iterator i=Map.begin();i!=Map.end();++i)
{
if(i->second)
{
--i->second;
cout<<i->first<<", ";
more=true;
}
}
}
,對於{1,2,2,2,3,3,4,4,4,4,4,4}它給我{1,2,3,4,2,3 ,4,2,4,4,4,4}而不是例如{4,1,4,2,4,3,4,2,4,3,4,2}。如何做呢?由於
學分:_13th_Dragon
如果這是不可能的?取決於你想要的,儘管'std :: unique'可能有幫助。 – chris
[算法來分離相同類型的項目]的可能重複(http://stackoverflow.com/questions/12375831/algorithm-to-separate-items-of-the-same-type) –
您必須開發一個算法怎麼做。那麼你應該關心它的實施。乍一看,這似乎不是一個這樣簡單的問題。 –