我有一个unordered_map,它包含一个枚举和一个字符串作为第二个。第一个值可能会以不同的顺序出现多次。这是一个例子:
enum SomeType
{
TYPE1,
TYPE2,
};
static std::unordered_map<SomeType, std::string> value_map =
{
{ TYPE2, "Value that shouldn't be found" },
{ TYPE1, "Value that gets found first" },
{ TYPE2, "Value that also never gets found" },
{ TYPE1, "Value that gets found second" },
{ TYPE2, "Value that gets found last" },
};
我想按如下方式遍历地图:例如,首先我想找到TYPE1
的对,这将为我提供第一个TYPE1
值。之后再次搜索TYPE1
值不会使我获得第一个值,而是可以在其后找到的下一个值。在此之后搜索TYPE2
值只会净化最后一个值
基本上我想找到下一个匹配的值,但是没有找到最后找到的值。
我多次尝试实现这样做,但我不太确定如何实现这样的算法 如何实现这样的算法?
尝试演示我想要的完整代码示例:https://godbolt.org/g/CgNZnj
答案 0 :(得分:6)
您可能需要std :: unordered_multimap(multimap)并使用equal_range:
#include <algorithm>
#include <iostream>
#include <unordered_map>
enum SomeType
{
TYPE1,
TYPE2,
};
static std::unordered_multimap<unsigned, std::string> value_map =
{
{ TYPE2, "Value that shouldn't be found" },
{ TYPE1, "Value that gets found first" },
{ TYPE2, "Value that also never gets found" },
{ TYPE1, "Value that gets found second" },
{ TYPE2, "Value that gets found last" },
};
int main() {
auto range = value_map.equal_range(TYPE1);
for( auto i = range.first; i != range.second; ++i )
std::cout << i->second << '\n';
}
但是:
unordered_multimap
替换为multimap
。结论:
在关联容器上运行算法中实现搜索要求是不可能的。
答案 1 :(得分:1)
#include <iostream>
#include <string>
#include <vector>
#include <utility>
enum SomeType
{
TYPE1,
TYPE2,
TYPE3,
};
using value_map = std::vector<std::pair<SomeType, std::string>>;
class ValueMap
{
public:
ValueMap(value_map& map) : map(map), index(0) {}
value_map& map;
std::string find_next(SomeType type)
{
while ((index != map.size()) && (map[index].first != type))
{
++index;
}
if (index != map.size())
{
std::string result = map[index].second;
++index;
return result;
}
else
{
return "-";
}
}
private:
unsigned index;
};
static value_map some_value_map =
{
{ TYPE2, "Value that shouldn't be found" },
{ TYPE1, "Value that gets found first" },
{ TYPE2, "Value that also never gets found" },
{ TYPE1, "Value that gets found second" },
{ TYPE2, "Value that gets found last" },
};
static ValueMap value_mapper(some_value_map);
int main()
{
std::cout << value_mapper.find_next(TYPE1) << std::endl;
std::cout << value_mapper.find_next(TYPE1) << std::endl;
std::cout << value_mapper.find_next(TYPE2) << std::endl;
std::string some_string = value_mapper.find_next(TYPE1);
if (some_string == "-")
{
std::cout << "Didn't find a match" << std::endl;
}
value_mapper.map.push_back({ TYPE3, "Value that gets after the last as new" });
std::cout << value_mapper.find_next(TYPE3) << std::endl;
return 0;
}
产生
Value that gets found first
Value that gets found second
Value that gets found last
Didn't find a match
Value that gets after the last as new