按特定顺序排列矢量元素
Arranging vector elements in a specific order
我正在开始编程,很抱歉我缺乏知识。如何按特定顺序设置矢量中的元素?我想以不会有相同元素彼此相邻的方式交换元素。例如,矢量包含:
{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
- 计算每个值的出现次数。
- 从最频繁的值开始,用不太频繁的值交替使用。
为了实现(1),可以简单地使用std::map<V, unsigned>
。然而,对于第二个,需要一组有序的std::pair<V, unsigned int>
,按第二个值排序。由于我们要跟踪需要使用给定值的次数,因此第二个值不能是恒定的。此外,如果我们碰巧将给定值的计数减少很多,我们不想更改顺序。总而言之,我们得到了
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
// In the pair, first is the original value, while
// second is the number occurrences of that value.
typedef std::pair<int, unsigned> value_counter;
int main(){
std::vector<int> sequence = { 0, 1, 3, 3, 4, 1, 2, 2, 2, 2 , 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4 };
std::map<int, unsigned> count;
for( auto i : sequence){
count[i]++;
}
std::vector<value_counter> store( count.size() );
std::copy(count.begin(), count.end(), store.begin());
// Sort by the second value
std::sort(store.begin(), store.end(),
[](const value_counter& a, const value_counter& b){
return a.second > b.second;
});
std::vector<int> result;
// We need two indices, one for the current value
// and the other one for the alternative
for(unsigned i = 0, j = 1; i < store.size(); ++i){
while(store[i].second > 0){
result.push_back(store[i].first);
store[i].second--;
if(store[i].second == 0)
continue;
if( j <= i)
j = i + 1;
while(j < store.size() && store[j].second == 0)
++j;
if(j >= store.size()){
std::cerr << "Not enough elements for filling!" << std::endl;
return 1;
}
else {
result.push_back(store[j].first);
store[j].second--;
}
}
}
for( auto r : result){
std::cout << r << " ";
}
}
与其使用typedef
,不如创建一个替代计数器,该计数器的名称比first
和second
更好,但这使得从地图复制更加冗长。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 为什么不;名字在地图上是按顺序排列的吗
- 使用 stl 排列 std::vector 元素的最短解决方案
- 给定一个包含 n 个整数和一个整数 x 的未排序数组 A,重新排列 A 中的元素
- 排列 2D 数组中的元素
- 使用特定位置重新排列数组的元素
- 为什么"std::unordered_map""speak like the Yoda" - 重新排列元素?
- 重新排列数组的元素
- 跳过C++中的排列元素
- 按特定顺序排列矢量元素
- 按升序排列的矢量元素
- 使用多个元素计算排列
- 重新排列链表元素
- 按状态排列向量中的元素
- 数组元素的所有排列在C++中一次获取一定数量的元素