我想在运行时选择许多可用对象中的一个,而不会产生复制对象的开销。在下面的代码中,我将说明我在寻找什么。我有2个map
个对象,我想在运行时根据type
的值操作其中一个。{1}}。我可以想到两种可能的解决方案:
=
使用赋值运算符 - 这会将地图复制到另一个地图,我想避免这种情况point
到正确的地图。我可以在不使用指针的情况下实现这一目标吗?
#include <iostream>
#include <map>
void print_map(map<string, bool> const &M, string header)
{
map<string, bool>::const_iterator itr;
cout << header << endl;
for (itr=M.begin(); itr!=M.end(); itr++) {
cout << itr->first << " -> " << itr->second << endl;
}
cout << " --- " << endl;
return;
}
int main()
{
map<string, bool> fruits;
map<string, bool> veggies;
fruits.insert(pair<string, bool>("apple", true));
fruits.insert(pair<string, bool>("banana", true));
print_map(fruits, "fruits before");
veggies.insert(pair<string, bool>("celery", true));
veggies.insert(pair<string, bool>("potato", true));
veggies.insert(pair<string, bool>("radish", true));
print_map(veggies, "veggies before");
string type = "f";
// obj_handle <---- Need help on implementing this handle
if (type == "f") {
// obj_handle = ?
}
else if (type == "v") {
// obj_handle = ?
}
// Manipulate object
// print_map(obj_handle, "Printing from handle");
return 0;
}
在SO上找到了另一个相关的答案:https://stackoverflow.com/a/7002278/3586654
答案 0 :(得分:1)
有几种方法可以获得对两个地图之一的引用。这是一个使用单独的功能。但是,正如@CaptainObvlious评论的那样,你也可以使用一个丑陋巨大的三元表达来实现同样的目标。
#include <iostream>
#include <map>
#include <stdexcept>
#if __cplusplus >= 201103L
using ItemFlags = std::map<std::string, bool> ;
#else
typedef std::map<std::string, bool> ItemFlags ;
#endif
void print_map(const ItemFlags& M,
const std::string& header)
{
using namespace std ;
ItemFlags::const_iterator itr;
cout << header << endl;
for (itr=M.begin(); itr!=M.end(); itr++) {
cout << itr->first << " -> " << itr->second << endl;
}
cout << " --- " << endl;
return;
}
const ItemFlags& select_map( const ItemFlags& fruitMap,
const ItemFlags& veggieMap,
const std::string& typeSelector )
{
if (typeSelector == "f") {
return fruitMap ;
}
if (typeSelector == "v") {
return veggieMap ;
}
throw std::runtime_error("Invalid type selector.") ;
}
int main()
{
using namespace std ;
ItemFlags fruits;
ItemFlags veggies;
fruits.insert(pair<string, bool>("apple", true));
fruits.insert(pair<string, bool>("banana", true));
print_map(fruits, "fruits before");
veggies.insert(pair<string, bool>("celery", true));
veggies.insert(pair<string, bool>("potato", true));
veggies.insert(pair<string, bool>("radish", true));
print_map(veggies, "veggies before");
string type = "f";
const ItemFlags& selected_map = select_map(fruits, veggies, type) ;
// Manipulate object
print_map(selected_map, "Printing from handle");
return 0;
}