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);
}
}
解决方案
我实际上不确定您要实现什么,所以我不知道遍历地图的顺序: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());
}
推荐阅读
- ios - 在类型化数组中存储符合泛型协议的对象
- angular - 在根级别为离子选项卡配置选项卡
- rotation - 处理 3.5.3 围绕中心点旋转点 图像缩小消失
- visual-studio - 如何在 Visual Studio 2017 中远程调试到以前部署的以调试模式构建的应用程序?
- sql - How can I create a selection that can show my total of objects by owners?
- schema.org - 为什么 Google 说一个项目需要 schema.org 中的 url 属性?
- docusignapi - JWT OAuth 身份验证流程中的“错误请求”消息
- android - 使用 Espresso 同时测试两项活动
- azure - Azure SQL Server 中的批量插入权限问题
- python - Django Tags 保存相关对象