获取地图的其余部分(C++),c++"/>

首页 > 解决方案 > 地图获取地图的其余部分(C++)

问题描述

我正在尝试以递归方式获取std::map<string, int>C++ 中 a 的所有值(和键)。

通过aMap.begin()->first,我得到第一个元素的键。

通过aMap.begin()->second,我得到第一个元素的值。

有没有办法获得一个排除地图中第一个值(已使用)的地图?这aMap.erase(aMap.begin())给了我错误:(地图的其余部分)

Invalid arguments '
Candidates are:
std::__cxx11::basic_string<char,std::char_traits<char>,std::allocator<char>> mapToCode(std::map<std::__cxx11::basic_string<char,std::char_traits<char>,std::allocator<char>>,int,std::less<std::__cxx11::basic_string<char,std::char_traits<char>,std::allocator<char>>>,std::allocator<std::pair<const std::__cxx11::basic_string<char,std::char_traits<char>,std::allocator<char>>,int>>>)
'

我不了解 C++ 标准映射的一些基本功能吗?

这是我正在使用的功能:

using std::map;
string mapToCode(map<string, int> aMap) {
    string returnString = "Dict(";
    if (aMap.empty()) {
        return returnString + ")";
    } else {
        string hold = mapToCode(aMap.erase(aMap.begin())) + "\"" + aMap.begin()->first + "\", " + std::to_string(aMap.begin()->second) + ")";
        return returnString + hold;
    }
}

这是使用它的类:

Dictionary::Dictionary() {
}

Dictionary::Dictionary(Dictionary dicObject, string key, int value) {
    std::map<string, int> newDict;
    newDict[key] = value;
    newDict.insert(dict.begin(), dict.end());

    dict = newDict;
}

string Dictionary::toCode() {
    if (empty()) {
        return "Dictionary()";
    } else {
        return mapToCode(dict);
    }
}

标签: c++

解决方案


我实际上不确定您要实现什么,所以我不知道遍历地图的顺序:P 但我想这有点接近您想要的:

std::string mapToCode(const std::map<std::string, int>& map, std::map<string, int>::iterator it) 
{
    std::string returnString = "Dict(";
    if (it == std::end(map))
    {
        // Not sure if you really wanted to return returnString + ")";
        return ""; // returnString;
    }

    std::string hold = mapToCode(map, std::next(it)) + "\"" + it->first + "\", " + std::to_string(it->second) + ")";
    return returnString + hold;
}

对此输入进行了测试:

int main()
{
    std::map<std::string, int> map;

    map.insert(std::make_pair("a", 1));
    map.insert(std::make_pair("b", 2));

    std::cout << mapToCode(map, map.begin()) << std::endl;

    return 0;
}

输出是:

Dict(Dict("b", 2)"a", 1)

注意:我们可以使用标准库的 std::next 将迭代器移动到容器中的下一个位置,而不是擦除,这可能很昂贵:)

在每次调用标准库之前优先使用 std 并避免使用命名空间 std。

注意 const& 而不是按值传递映射。它可以防止复制整个地图。

关于复制构造函数的第二部分:

Dictionary::Dictionary(const Dictionary& other)
{
    // I am assuming that dict is the class variable that you use to store the actual map in the class

    // Also this "appends" to the existing dictionary
    // If you want to first delete the old one's data, clear the dict
    // dict.clear()
    dict.insert(other.begin(), other.end());
}

推荐阅读