【C++STL】Algorithm库

  • ~2.63K 字
  1. 1. Algorithm库
    1. 1.1. copy_if()
    2. 1.2. partition()
    3. 1.3. 序列运算
    4. 1.4. 序列操作

Algorithm库

copy_if()

语法:copy_if(first, last, out, pred)

作用:按传入的对象pred条件复制容器内容

如实现查找string数组中指定单词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template<typename T, typename P>
std::vector<T> Filter(const std::vector<T>& vec, P pred){
std::vector<T> res;
std::copy_if(vec.begin(),vec.end(),std::back_inserter(res),pred);
return res;
}

int main(void){
std::string word="apple";
auto hasWord = [&word](const std::string& s) {return s. find(word) != s.npos;};
std::vector<std::string> words{"An apple","big apple","orange","green apple","grape"};
std::vector<std::string> res = Filter(words, hasWord);

for(auto s:res)
std::cout << s << " " << std::endl;

}

C++20中,在range库中进行了拓展

1
2
3
4
5
6
7
8
9
10
11
int main(void){
std::string word="apple";
auto hasWord = [&word](const std::string& s) {return s. find(word) != s.npos;};
std::vector<std::string> words{"An apple","big apple","orange","green apple","grape"};
std::vector<std::string> res ;
std::ranges::copy_if(words, std::back_inserter(res),hasWord);

for(auto s:res)
std::cout << s << " " << std::endl;

}

partition()

语法:copy_if(first, last, pred)

作用:将一个序列按条件分割

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(void)
{

std::vector<int> numbers{1,23,4,5,67,8,67,23,20,11,32,33,45,17};
auto bound1 = std::partition(numbers.begin(),numbers.end(), [](int v){return v%3 == 0;});
auto bound2 = std::partition(bound1, numbers. end(), [](int v){return v%3 == 1;});
std::cout << "\n{x=3k}:\n";
std::for_each(numbers.begin(),bound1, [](int v){std::cout << v << "";});
std::cout << "\n{x=3k+1}:\n";
std::for_each(bound1,bound2, [](int v){std::cout << v << "";});
std::cout << "\n{x=3k+2}:\n";
std::for_each(bound2,numbers.end(), [](int v){std::cout << v << "";});
}

序列运算

  • set_difference():将不是两个序列共有的元素拷贝到单独的元素中(差集)
  • set_symmetric_difference():上述加了绝对值(对称差集)
  • set_intersection()
  • set_union()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main(void){

std::vector<int> numbers1{1,1,2,3,4,4,5,6};
std::vector<int> numbers2{9,8,7,6,5,5,4};
std::vector<int> result;

std::sort(numbers1.begin(),numbers1.end());
std::sort(numbers2.begin(),numbers2.end());

std::set_symmetric_difference(numbers1.begin(),numbers1.end(),
numbers2.begin(),numbers2.end(),
std::back_insert_iterator(result));

for(auto v:result)
std::cout << v << " ";

}

序列操作

  • for_each()
  • transform()
  • remove_if()
  • reduce()
  • inner_product()
  • transform_reduce()
  • transform_exclusive_scan()
赞助喵
非常感谢您的喜欢!
赞助喵