【发布时间】:2020-10-02 00:22:48
【问题描述】:
当在 c++ 中遍历一个映射(或 unordered_map)时,键和值是通过 .first 和 .second 访问的。但是有没有办法以更具语义意义的方式访问键/值对?
例如,如果我将代数表达式存储在 map
x - 2yz + 3xyz --> expr = { {{'x'}, 1}, {{'y','z'}, -2}, {{'x','y','z'}, 3} }
而我想遍历地图,似乎很自然的想做:
for(auto & term : expr)
term.vars ...
term.coeff ...
而不是
for(auto & term : expr)
term.first ...
term.second ...
有没有什么方法可以通过struct Term { set<char> vars; int coeff; }; 实现这一点?我看不到任何将这种结构与 map 集成的方法,但我也想不出任何根本原因为什么它应该是不可能的,因为例如这在 python 中很简单:[(vars,coeff) for vars,coeff in expr.items()].
【问题讨论】:
-
如果 C++17 不是一个选项,总会有 std::tie。
标签: c++ dictionary