【问题标题】:Insert more than one pair in c++在 C++ 中插入多于一对
【发布时间】:2014-10-10 17:04:58
【问题描述】:

我有一张这样的地图:

map<string, map<int, int>> collector;  

而且我不知道如何在我的地图中插入数据。如果我有

map<string, int> collector;

只有键值我会使用

collector.insert(pair<string, int>)(name,money));

但是当我们在地图中有地图时插入的方式是什么?我试着做:

typedef map<int, int> map_;
  for(iteration = collector.begin(); iteration != collector.end(); iteration++) {
    iteration = collector.find(word);
    if(iteration == collector.end()) {
        iteration = collector.insert(map_::value_type(num,num).first;
    }
}

这种方式不适合我。

【问题讨论】:

  • 你能使用 C++11 的特性吗?
  • 首先,你的代码有语法错误。你得到什么错误?
  • 我刚刚发布了一些代码,我正在尝试了解如何将数据插入到我的地图中。
  • colector[a_string][a_int] = b_int;

标签: c++ map stl


【解决方案1】:

以下是一些插入数据结构的方法:

#include <iostream>  // cout
#include <map>
#include <string>
#include <utility>  // make_pair

using namespace std;

int main()
{
    using Collector = map<string, map<int, int>>;

    Collector collector;

    collector["USD"] = Collector::mapped_type{ { 1, 3 }, { 0, 8 } };

    collector["EUR"].insert(make_pair(4, 5));
    collector["EUR"].insert(make_pair(6, 7));

    collector["CHF"][2] = 4;

    const Collector::mapped_type jpyIntegers { { 10, 20 }, { 100, 200 } };

    collector.insert(make_pair("JPY", jpyIntegers));

    collector["MMK"];

    for (const auto& a: collector) {
        cout << a.first << ": ";
        for (const auto& i: a.second) {
            cout << "(" << i.first << "|" << i.second << ")";
        }
        cout << "\n";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多