python - 将计数器附加到字符串
问题描述
我有一个生成组件的函数。这些组件的名称包含迭代器。
我知道如何在 Python 中做到这一点。我怎样才能在 C++ 中做同样的事情?
Python:
def _default_components(self):
return {"component{}".format(cnt) : block[cnt]
for cnt in range(number_of_components)}
这会产生一个字典,其中每个组件都有一个唯一的名称:
component1 : block1
component2 : block2
component3 : block3
component4 : block4
我现在要做的是将 传递iterator
给string
C++ 中的。
换句话说,这条线的 C++ 等价物是什么:
"component{}".format(cnt)
解决方案
新的 C++20 标准确实有一个format()
功能,但在撰写本文时,它仅在 Microsoft MSVC 编译器中实现。它的参考实现可作为来自fmt.dev的库获得。
它的工作方式与 Python 略有不同。格式字符串是相同的,但它不是字符串对象的方法。相反,它被用作独立函数,如下所示:
std::string s = std::format("hello {}\n", name);
或者,根据您的示例,
std::string s = std::format("component{}", cnt);
推荐阅读
- three.js - 围绕轴旋转立方体
- python - How do I save data from websocket?
- haskell - 如何实现基于谓词的列表拆分器
- javafx - JavaFX:将上下文菜单添加到 TableView 单元格
- c# - 当 UseShellExecute == false 时,如何在 C# 进程上强制标准输出?
- drupal - 在 Drupal 8 中获取节点 ID 的分类术语
- c# - C# WPF 图像不显示
- r - 如何在 RODBC 包 R 中使用 if_else 和 sql 查询
- javascript - 单击Angular 5停止执行其他功能
- javascript - Javascript倒数计时器无法正常工作