将 Map 从第二个元素开始复制到另一个 Map

Copy Map from the second element onwards to another Map

我有一张地图:map<int , std::string> results,我想在第二张地图中复制这张地图的一部分 results2

例如我有:

results[0] = "A",
results[1] = "B",
results[2] = "C",
results[3] = "D"

然后 results2 将是 results2("B", "C", "D")。所以它从索引 1 开始是相同的。

I want to copy a part of this map in a second map

这很简单,使用迭代器并构造 'second map'

std::map<int, std::string> result2(results.find("B"), results.end());

将从"B"开始(包括"B")复制到最后。

您可以使用 insertstd::next 轻松完成此操作。 std::map 没有随机访问迭代器,只有双向迭代器,所以没有 + n 操作。所以 std::next 是必需的。

#include<iostream>
#include<map>
#include<algorithm>

int main()
{
    std::map<int, std::string> results, results2;
    results = {{1, "A"}, {2, "B"}, {3, "C"}, {4, "D"}};
    results2.insert(std::next(results.begin()), results.end()); //from second element onwards

    for(auto const& m: results)
      std::cout << m.first << ' ' << m.second << ' ';

    std::cout << '\n';

    for(auto const& m: results2)
      std::cout << m.first << ' ' << m.second << ' ';

}

See Demo