使用 for_each ,使用字符串复制

Using for_each , copy with string

本文关键字:字符串 复制 for each 使用      更新时间:2023-10-16

我对程序有一些问题,也许有人可以帮助我。所以:

int main() {
    std::string col = "maly tekst"
    for_each(/* FILL IN #2*/ f());
    copy(/*FILL IN #3*/);
    std::cout << col; }

输出应为:TSKET YLAM
我知道我需要使用函子,所以我做了这样的东西:

#include <iostream>
#include <string>
#include <algorithm>
class f{
public:
void operator() (char &k)const
{
   k = toupper(k);
}
};
int main(){
std::string col = "maly tekst";
for_each(col.begin(),col.end(),f());
copy(col.rbegin(),col.rend(),back_inserter(col));
std::cout << col << std::endl;
}

但是现在当我运行它时,它返回:

MALY TEKSTTSKET YLAM

有人可以指出我正确的方法,或者帮助我使用此示例程序吗?

谢谢

E:忘了补充一下我只能在main中使用这个功能,我不能添加任何新内容

std::for_each(col.begin(),col.end(),f()); // as before
std::reverse(col.begin(), col.end());

如果您不能使用 std::copy 来替换原始容器,则不能使用 std::reverse 。要打印带有reverse order的 col,另一种解决方法是直接将col复制到stream iterator

for_each(col.begin(),col.end(),f());
std::copy(col.rbegin(), col.rend(), std::ostream_iterator<char>(std::cout, ""));