我想将一个函数应用于std::vector的某些元素。我使用std::includes来检查“较大”的 vector 中是否存在“较小”的 vector ,如果存在,我想将函数应用于“较大” vector 的这些元素等于“较小” vector 的元素。有什么建议么?
编辑:
OP错误地张贴了以下内容作为答案
std::search有问题!它找到 vector 中包含的序列的首次出现,而在我的 vector 中这些元素位于多个位置。此外,我还有一个 vector 对象!
最佳答案
不确定您遇到什么问题,但是这是一个简单的示例,显示了较大的vector
中包含的元素范围,该范围与较小的std::search
的内容乘以2相同。我使用 std::includes
而不是vector
来确定是否较大的includes
包含较小元素中的元素范围,因为search
与vector
不同,它返回 bool(boolean) 值结果,而boost::find_nth
将迭代器返回至较大ojit_code中所包含范围的开头。
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
void times_two(int& t)
{
t *= 2;
}
int main()
{
std::vector<int> v1{1,2,3,4,5,6,7,8,9};
std::vector<int> v2{4,5,6};
// find if the larger vector contains the smaller one
auto first = std::search(v1.begin(), v1.end(), v2.begin(), v2.end());
if(first != v1.end()) {
// get the last element in the sub-range
auto last = std::next(first, v2.size());
// apply function to each sub-range element
std::for_each(first, last, times_two);
}
for(auto const& v : v1) {
std::cout << v << ' ';
}
std::cout << '\n';
}
输出:
1 2 3 8 10 12 7 8 9
编辑:
使用Here's an example执行搜索的 ojit_code 。