首先,我是C++/OOP的新手.
我想在我的课程中包含一个std :: map,并且想知道如何为我的班级用户提供地图typedef和功能.我是否需要像下面的简单示例那样做?(我只展示了一个子集来表明我正在尝试做什么)
对于我已经包含容器的任何类(即使是映射方法的子集),我不得不这样做.它似乎也是一个类维护问题(例如,今天可能不需要一些map方法,但将来需要它)
ps除了回答这个问题之外,对以下示例的任何其他更正/反馈都表示赞赏.
#include <map>
#include <string>
class Inventory {
public:
typedef std::string key_type;
typedef std::string mapped_type;
typedef std::map<key_type, mapped_type>::value_type value_type;
Inventory() { }
Inventory(int lotNum) : lotNum_(lotNum) { }
void insert(const value_type& el) { cars_.insert(el); }
//
// TODO: iterators, erase, etc
//
private:
int lotNum_;
std::map<key_type, mapped_type> cars_;
};
int main() {
Inventory ourCars(1);
ourCars.insert( Inventory::value_type( "BMW","ABC123" ) );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下是我如何思考这个问题.分别考虑您的类接口和实现.用户不需要知道你在幕后做什么 - 你正在使用什么容器等.你的类本身应该具有你通过其界面提供的一些功能.我不确定你的类应该做什么,但如果你想要一个函数来插入两个字符串你应该只提供该函数.那是你的出发点.然后你决定将字符串存储在地图或其他任何地方.总之,进入地图的类型将由您的类接口决定.你正在做的是相反的 - 决定你如何实现它,然后在界面中暴露你的地图类型.