首页 > 解决方案 > 将计数器附加到字符串

问题描述

我有一个生成组件的函数。这些组件的名称包含迭代器。

我知道如何在 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

我现在要做的是将 传递iteratorstringC++ 中的。

换句话说,这条线的 C++ 等价物是什么:

"component{}".format(cnt)

标签: pythonc++stringiterator

解决方案


新的 C++20 标准确实有一个format()功能,但在撰写本文时,它仅在 Microsoft MSVC 编译器中实现。它的参考实现可作为来自fmt.dev的库获得。

它的工作方式与 Python 略有不同。格式字符串是相同的,但它不是字符串对象的方法。相反,它被用作独立函数,如下所示:

std::string s = std::format("hello {}\n", name);

或者,根据您的示例,

std::string s = std::format("component{}", cnt);

推荐阅读