C++ 如何在C++;?

C++ 如何在C++;?,c++,string,algorithm,vector,filter,C++,String,Algorithm,Vector,Filter,我有一个10000个字符串的大向量: std::vector<std::string> v; for (int i = 0; i < 10000; i++) { v.push_back(generateRandomString(10)); } std::vector v; 对于(inti=0;i

我有一个10000个字符串的大向量:

std::vector<std::string> v;
for (int i = 0; i < 10000; i++) { v.push_back(generateRandomString(10)); }
std::vector v;
对于(inti=0;i<10000;i++){v.push_-back(generateRandomString(10));}
我想将包含“AB”的字符串显示为子字符串。我试过:

std::vector<std::string> res;
res = std::copy_if(v, [](auto s) { return s.find("AB") != std::string::npos; });

cout << res;
std::vector res;
res=std::copy_如果(v,[](自动s){返回s.find(“AB”)!=std::string::npos;});

不能沿着这些路线(未经测试):

std::copy_if(v.begin(),v.end(),
std::ostream_迭代器(std::cout,“\n”),
[](const std::string&s){返回s.find(“AB”)!=std::string::npos;});

如果您正在寻找一种只打印您感兴趣的字符串的有效解决方案,则应避免创建中间数据结构,也就是说,如果
,则不应使用
std::copy\u。由于您可以将中的范围适配器
std::views::filter
与一起使用,如下所示:

auto ab = [](const auto& s) { return s.find("AB") != std::string::npos; };
for (auto const& s : v | std::views::filter(ab))
    std::cout << s << std::endl;
auto ab = [](const auto& s) { return s.contains("AB"); };
for (auto const& s : v | std::views::filter(ab))
    std::cout << s << std::endl;
std::vector<std::string> res;
std::ranges::copy(v | std::views::filter(ab), std::back_inserter(res));
for (auto const& s : res)
    std::cout << s << std::endl;

但是,如果还希望存储过滤结果以供进一步使用,则可以将上述解决方案与中的组合,如下所示:

auto ab = [](const auto& s) { return s.find("AB") != std::string::npos; };
for (auto const& s : v | std::views::filter(ab))
    std::cout << s << std::endl;
auto ab = [](const auto& s) { return s.contains("AB"); };
for (auto const& s : v | std::views::filter(ab))
    std::cout << s << std::endl;
std::vector<std::string> res;
std::ranges::copy(v | std::views::filter(ab), std::back_inserter(res));
for (auto const& s : res)
    std::cout << s << std::endl;
std::vector res;
std::ranges::copy(v | std::views::filter(ab)、std::back|u inserter(res));
用于(自动常数和s:res)

谢谢你的回答。我发现
错误:“ostream_迭代器”不是“std”的成员。
。您可能想使用
std::back_inserter
而不是
std::ostream_迭代器
,如果您想复制到另一个向量,在使用
std::ostream_迭代器
之前是否包含了建议应包含的标题?@vu1p3n0x quoh OP:“我想显示那些…”强调我的。@IgorTandetnik,为了进一步使用,我确实想把它复制到
res
然后显示
res
。它可能值得一读。