我知道如何用其他语言做到这一点,但不知道在 C++ 中,我不得不在这里使用它。
我有一组字符串( keywords
),我正在打印到 out
作为列表,这些字符串之间需要一个逗号,但不是尾随逗号。例如,在 Java 中,我会使用 StringBuilder
并在构建字符串后删除末尾的逗号。我怎样才能在 C++ 中做到这一点?
auto iter = keywords.begin();
for (iter; iter != keywords.end( ); iter++ )
{
out << *iter << ", ";
}
out << endl;
我最初尝试插入以下块来执行此操作(在此处移动逗号打印):
if (iter++ != keywords.end())
out << ", ";
iter--;
原文由 quandrum 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用中缀迭代器:
用法类似于: