[英]map<Key,pair<A,B>> to map<Key,A>
我有一个 class 出于某种原因需要为每个键存储一对(比如 int,double),但其接口只公开这对(int)的两个值之一。 一种实现可能是
using namespace std;
class Foo {
public:
map<string,int> const & get() const {return external;}
void doStuff(string const & str) {
external.at(str);
internal.at(str);
}
private:
map<string,int> external;
map<string,double> internal;
};
缺点是 doStuff 有双重查找。
另一种方法是存储map<string,pair<int,double>> allin
但是返回整个 map 的访问器需要一个副本。
当然,最后一种方法是通过使用return allin.at(key).first;
访问单个键来使访问器更具原子性。 ,这似乎是最好的方法,但它破坏了我想提供的界面。
我想知道,有没有办法避免“外部/内部”版本中的双重查找?
另一种方法是定义具有私有和公共值的 map 条目。 通过朋友声明,私有值可以对 Foo class 可见。
#include <iostream>
#include <string>
#include <map>
class Foo;
template<typename T1, typename T2>
struct my_map_entry
{
public:
my_map_entry()=default;
my_map_entry(T1 v, T2 pv)
{
value = v;
private_value = pv;
}
T1 value;
private:
T2 private_value;
friend class Foo;
};
class Foo {
public:
Foo(){
map["test"]=my_map_entry<int, double>(1, 2.0);
}
void doStuff(const std::string& str
{
auto entry = map.at(str);
std::cout<<"private_value: "<<entry.private_value<<std::endl;
}
std::map<std::string,my_map_entry<int, double>> map;
};
int main()
{
Foo test;
test.doStuff("test");
}
鉴于您只希望用户能够检索项目,您的 get() 方法可以在考虑到该要求的情况下重写。
using namespace std;
class Foo {
public:
int *const get(string const &str) const {
auto it = map_.find(str)
return it == map_.end() ? nullptr : &it->first;
}
void doStuff(string const & str) {
map_.at(str);
}
private:
map<string,pair<int, double>> map_;
};
这个想法是如果没有找到键,则返回 nullptr,如果找到键,则返回指向值的指针。
相反,如果您还希望能够枚举所有可用的整数,那么您只有三个选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.