【发布时间】:2021-10-11 21:47:14
【问题描述】:
我正在尝试在 c++ 中创建一个 std::set 的 std::pair 。我希望集合显示的行为是使用对的第一个元素对对进行排序,并使用对的第二个元素定义不规则性。例如,如果输入对如下:
1 5
5 2
3 3
2 4
4 3
该集合应如下所示:
1 5
2 4
4 3
5 2
【问题讨论】:
-
std::set做不到。
我正在尝试在 c++ 中创建一个 std::set 的 std::pair 。我希望集合显示的行为是使用对的第一个元素对对进行排序,并使用对的第二个元素定义不规则性。例如,如果输入对如下:
1 5
5 2
3 3
2 4
4 3
该集合应如下所示:
1 5
2 4
4 3
5 2
【问题讨论】:
std::set 做不到。
使用std::set 无法做到这一点。 std::set 使用与订单相同的相等关系,没有任何技巧可以改变它。
【讨论】:
boost::multi_index_container 可以。
您可以使用地图来制作唯一性。
#include <iostream>
#include <set>
#include <map>
using p = std::pair<int, int>;
int main(){
std::set<p> s {
{1, 5},
{5, 2},
{3, 3},
{2, 4},
{4, 3}
};
// copy to a map
std::map<int, int> m;
for(p e: s){
m[e.second] = e.first;
}
// put back in the set
s.clear();
for(p e: m){
s.emplace(e.second, e.first);
}
// print out
for(p e: s){
std::cout << e.first << ' ' << e.second <<'\n';
}
}
【讨论】:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/key.hpp>
#include <utility>
using namespace boost::multi_index;
using int_pair=std::pair<int,int>;
using container=multi_index_container<
int_pair,
indexed_by<
ordered_non_unique<key<&int_pair::first>>,
ordered_unique<key<&int_pair::second>>
>
>;
#include <iostream>
int main()
{
container c={{1,5},{5,2},{3,3},{2,4},{4,3}};
for(const auto& p:c)std::cout<<p.first<<" "<<p.second<<"\n";
}
输出
1 5
2 4
3 3
5 2
【讨论】: