C ++ - 开发自己的std :: count_if版本 [英] C++ - Developing own version of std::count_if
问题描述
对于任务,我做一些简单的数据采样,以确定哪些样本包含音频计数总能量。我一直在研究 std :: count_if
函数,虽然这在某种程度上适合我的需要,例如:
For a task, I'm doing some simple data sampling to determine which samples contains audio counting the total number of energy. I've been looking into the std::count_if
function, and, although this suits my needs to a certain extent, for example:
int foo = std::count_if(
std::begin(samples),
std::end(samples),
containsSound);
这会计算包含声音的样本总数,但不会指示样本包含声音。我想出了这个解决方案:
This counts the total number of samples that contain sound, but does not give an indication to the samples that contain sound. I came up with this solution:
std::vector<std::string> sound_files = myLib::count_sample_if(
std::begin(samples),
std::end(samples),
samples.DirName,
containsSOund);
然后存储并推送 samples.DirName
到向量
,然后我可以使用它来存储我选择的样本集。
This would then store and push the samples.DirName
to a vector
which I can then use to only store the sample set of my choice.
是否容易实现?
推荐答案
如果你只是需要可读性/开发速度,关心性能,那么你可以很容易地使用 std :: copy_if
和 std :: transform
来获得你需要的: / p>
If you just need readability / speed of development and you don't care about performance then you can easily use std::copy_if
and std::transform
to obtain what you need:
std::vector<Song> songs;
std::vector<Song> filtered;
std::vector<std::string> transformed;
std::copy_if(songs.begin(), songs.end(), filtered.begin(), [](const Song &song) { return whatever you need; });
std::transform(filtered.begin(), filtered.end(), transformed.begin(), [](const Song &song) { return song.sample; });
或者您可以使用 std :: for_each
:
std::vector<Song> songs;
std::vector<std::string> transformed;
std::for_each(songs.begin(), songs.end(), [&](const Song &song) { if (song.containsSample()) transformed.push_back(song.sample); });
那么包含声音的样本量只是 transformed.size
。
Then the amount of samples that contains sound is just transformed.size()
.
这篇关于C ++ - 开发自己的std :: count_if版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!