相关疑难解决方法(0)

如何从std :: map中检索所有键(或值)并将它们放入向量中?

这是我出来的可能方式之一:

struct RetrieveKey
{
    template <typename T>
    typename T::first_type operator()(T keyValuePair) const
    {
        return keyValuePair.first;
    }
};

map<int, int> m;
vector<int> keys;

// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());

// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));
Run Code Online (Sandbox Code Playgroud)

当然,我们也可以通过定义另一个仿函数RetrieveValues从地图中检索所有值.

有没有其他方法可以轻松实现这一目标?(我总是想知道为什么std :: map不包含我们这样做的成员函数.)

c++ dictionary stl stdmap

222
推荐指数
16
解决办法
30万
查看次数

迭代C++映射中的键

有没有办法迭代键,而不是C++映射对?

c++ stl

109
推荐指数
12
解决办法
14万
查看次数

迭代器适配器只迭代映射中的值?

经过几年的C#和最近的Objective C,我刚刚回到C++.

我之前做过的一件事就是为std :: map滚动我自己的迭代器适配器,它将仅仅反映值部分,而不是键值对.这是一个非常普遍和自然的事情.C#为此工具提供了其Dictionary类的Keys和Values属性.类似地,Objective-C的NSDictionary具有allKeys和allValues.

自从我"离开"以来,Boost已经收购了Range和ForEach库,我现在正在广泛使用它们.我想知道两者之间是否有一些设施可以做同样的事情,但我找不到任何东西.

我正在考虑使用Boost的迭代器适配器来解决问题,但在我沿着这条路走下去之前,我想我会问这里是否有人知道Boost中的这样一个设施,还是其他现成的设施?

c++ maps iterator adapter

17
推荐指数
4
解决办法
1万
查看次数

创建STL映射键迭代器

通常,您有一个映射map<string,X>,其中键是映射值的名称,您需要一个API,让消费者可以看到所有名称...例如填充GUI列表框.您可以构建一个向量并将其作为API调用返回,但这样效率很低.您可以只返回对地图的引用,但随后也可以访问这些值,您可能不希望这样.

那么你怎么能编写一个兼容的类KeyIterator,它包装map并提供对该map中键的标准迭代器访问.

例如:

map<string,X> m= ...
KeyIterator<string> ki(m);
for(KeyIterator<string>::iterator it=ki.begin();it!=ki.end();++it)
 cout << *it;
Run Code Online (Sandbox Code Playgroud)

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; …
Run Code Online (Sandbox Code Playgroud)

c++ stl

7
推荐指数
1
解决办法
3068
查看次数

标签 统计

c++ ×4

stl ×3

adapter ×1

dictionary ×1

iterator ×1

maps ×1

stdmap ×1