C++ copy_if lambda capturing std::string

C++ copy_if lambda capturing std::string

本文关键字:std string capturing lambda copy if C++      更新时间:2023-10-16

这是下面的一个问题:C++-开发自己版本的std::count_if?

我有以下功能:

// vector for storing the file names that contains sound 
std::vector<std::string> FilesContainingSound; 
void ContainsSound(const std::unique_ptr<Signal>& s)
{
    // Open the Wav file 
    Wav waveFile = Wav("Samples/" + s->filename_); 
    // Copy the signal that contains the sufficient energy 
    std::copy_if(waveFile.Signal().begin(), waveFile.Signal().end(), 
                 FilesContainingSound.begin(), [] (const Signal& s) {
                     // If the energy bin > threshold then store the 
                     // file name inside FilesContaining
                 }
}

但对我来说,我只需要在lambda表达式中捕获字符串"filename",因为我只会处理它。我只需要访问waveFile.Signal()就可以进行分析。

有人有什么建议吗?

编辑:

std::vector<std::string> FilesContainingSound;
std::copy_if(w.Signal().begin(), w.Signal().end(), 
             FilesContainingSound.begin(), [&] (const std::unique_ptr<Signal>& file) {
                 // If the energy bin > threshold then store the 
                 // file name inside FilesContaining
             });

您似乎混淆了不同级别的抽象。如果你要使用文件名,那么你基本上想要这个订单上的东西:

std::vector<std::string> input_files;
std::vector<std::string> files_that_contain_sound;
bool file_contains_sound(std::string const &filename) { 
     Wav waveFile = Wav("Samples/" + filename);
     return binned_energy_greater(waveFile, threshold);
}
std::copy_if(input_files.begin(), input_files.end(),
             std::back_inserter(files_that_contain_sound),
             file_contains_sound);

目前,我将file_contains_sound放在一个单独的函数中,只是为了明确其类型——因为您处理的是文件名,所以它必须将文件名作为字符串,并返回一个bool,指示该文件名是否是您想要在结果集中的组之一。

事实上,你几乎从来没有真正想把它实现为一个实际的函数——你通常希望它是某个重载operator()的类的对象(lambda是生成这样一个类的简单方法)。不过,所涉及的类型必须保持不变:它仍然需要将文件名(字符串)作为参数,并返回一个bool来指示该文件名是否是您想要的结果集中的文件名。处理文件内部内容的一切都将发生在该函数(或它调用的东西)内部。