gpt4 book ai didi

c++ - 转换字符串 vector : skip elements based on the previous value

转载 作者:行者123 更新时间:2023-11-30 01:02:20 25 4
gpt4 key购买 nike

我需要将字符串 vector 转换为小写,但我需要保留文件名的大小写。它们由前面的字符串标记“file”或“out”标识。

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

template <class T>
void print(const T& v) {
std::copy(v.begin(), v.end(),
std::ostream_iterator<typename T::value_type>(std::cout, "\n"));
}

std::string lowercase(const std::string& s)
{
std::string result(s);
std::transform(result.begin(), result.end(), result.begin(), ::tolower);
return result;
}

int main() {

std::vector<std::string> tokens {"Col1", "Col2", "File", "FileIn.dat", "Out", "FileOut.dat"};
std::transform(tokens.begin(), tokens.end(), tokens.begin(), lowercase);

// how to replace lowercase() with a lambda that will take the previous
// element into account while converting an element into lowercase
print(tokens);

return 0;
}

在上面的代码中结果应该是

{"col1", "col2", "file", "FileIn.dat", "out", "FileOut.dat"};

保留“file”和“out”之后字符串的大小写。

有没有办法使用 std::transformlambda 函数来做到这一点?

最佳答案

是的。您可以像这样使用捕获 lambda:

bool is_filename = false;
std::transform(tokens.begin(), tokens.end(), tokens.begin(),
[&is_filename] (auto &s) {
if (is_filename)
is_filename = false;
else
{
s = lowercase (s);
is_filename = s == "file" || s == "out";
}
return s;
});

输出:

col1
col2
file
FileIn.dat
out
FileOut.dat

Live demo

关于c++ - 转换字符串 vector : skip elements based on the previous value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56189855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com