在 c++ 中遍历映射(或 unordered_map)时,键和值通过 .first 和 .second 访问。但是有没有办法以更语义上有意义的方式访问键/值对?
例如,如果我将代数表达式存储在 map< set, int> 中:
x - 2yz + 3xyz --> expr = { {{'x'}, 1}, {{'y','z'}, -2}, {{'x','y','z'}, 3} }
Run Code Online (Sandbox Code Playgroud)
我想遍历地图,想要这样做似乎很自然:
for(auto & term : expr)
term.vars ...
term.coeff ...
Run Code Online (Sandbox Code Playgroud)
代替
for(auto & term : expr)
term.first ...
term.second ...
Run Code Online (Sandbox Code Playgroud)
有没有办法用 a 来实现这一点struct Term { set<char> vars; int coeff; };?我看不出有任何方法可以将这样的结构与 map 集成,但我也想不出任何根本原因为什么它应该是不可能的,因为例如它在 python 中是微不足道的:[(vars,coeff) for vars,coeff in expr.items()].
如果c++17您可以使用structured bindings,那么您可以用来分解这对
for (auto [vars, coeff] : expr) { ... }
Run Code Online (Sandbox Code Playgroud)
无需更改任何其他内容。
如果您不能使用,c++17那么您的Term结构可以在一个std::vector或另一个中使用,sequence container因为您已经取消了关联性并将其放在结构本身中。
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |