因此,我试图从任意数目的整数中生成一个唯一的键,以便以后可以使用映射中的唯一键查找值。在生成唯一键时,数字的排序不重要。
我研究了各种选项,包括使用Tuple、散列和串联int来生成键,但无法找到最优的解决方案。
期望的函数或逻辑应该包含一个int数组,作为回报,它应该给出一个唯一的键(int)。
例如
样本输入可以是1,5,6,134,1,1,5,6键应该与6,5,1
发布于 2019-06-13 18:45:47
正如我所理解的,您的问题(主要是从注释中推断),您希望将一些数据结构放在一个映射中,并使用一个整数数组作为键,其中整数的不同顺序实际上应该被视为相同的键。
为了这个例子,让我们说“一些数据结构”是一个std::string,那么最简单的就是使用一个std::set作为键,因为无论您使用什么顺序来构造set、1 5 6、1 6 5或6 5 1,您都会得到相同的set。
#include <string>
#include <map>
#include <iostream>
int main() {
std::map< std::set<int>, std::string> x;
x[ { 1,5,6} ] = "Hallo";
std::cout << x[ { 6 , 5, 1} ] << "\n";
}只使用set对元素进行排序有点浪费,因此可以使用排序向量。要防止地图的用户需要对向量排序,可以使用助手类型,如下所示:
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <initializer_list>
struct sorted_vector {
std::vector<int> x;
sorted_vector(std::initializer_list<int> l) : x(l) {
std::sort(x.begin(),x.end());
}
bool operator<(const sorted_vector& other) const {
return x < other.x;
}
};
int main() {
std::map< sorted_vector, std::string> x;
x[ { 1,5,6} ] = "Hallo";
std::cout << x[ { 6 , 5, 1} ] << "\n";
}我知道你担心效率,特别是当向量包含很多元素的时候。但是,除非您真的达到了限制或剖析您的代码,并意识到您需要改进的东西,我不会费心重新发明车轮。
https://stackoverflow.com/questions/56581454
复制相似问题