C++ copy_if lambda capturing std::string
C++ copy_if lambda capturing std::string
这是下面的一个问题: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来指示该文件名是否是您想要的结果集中的文件名。处理文件内部内容的一切都将发生在该函数(或它调用的东西)内部。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL