通常情况下,您会有一个类似于
那么,您该如何编写符合规范的KeyIterator类,它包装了映射表并提供标准迭代器访问映射表中的键。
例如:
map<string,X>
的映射表,其中键是映射值的名称,您需要一个API,使消费者可以查看所有名称...例如,用于填充GUI列表框。您可以构建一个向量并将其作为API调用返回,但这样效率相对较低。您也可以返回对映射的引用,但这样值也是可访问的,而您可能不希望如此。那么,您该如何编写符合规范的KeyIterator类,它包装了映射表并提供标准迭代器访问映射表中的键。
例如:
map<string,X> m= ...
KeyIterator<string> ki(m);
for(KeyIterator<string>::iterator it=ki.begin();it!=ki.end();++it)
cout << *it;
KeyIterator应该是轻量级的,这样你就可以从一个几乎没有开销的方法中返回它。
编辑: 我不确定我解释得完美,让我给出一个更好的用例(半伪代码):
class PersonManager
{
private:
map<string,Person> people;
public:
//this version has to iterate the map, build a new structure and return a copy
vector<string> getNamesStandard();
//this version returns a lightweight container which can be iterated
//and directly wraps the map, allowing access to the keys
KeyIterator<string> getNames();
};
void PrintNames(PersonManager &pm)
{
KeyIterator<string> names = pm.getNames();
for(KeyIterator<string>::iterator it=names.begin();it!=names.end();++it)
cout << *it << endl;
}