STL 标准库算法测试

头文件为 algorithm , 算法由all_of, any_of, sort

#include <iostream>
#include <vector>
#include <algorithm>
//all_of
template <typename T>
class Test_std_algorithm {
public:
	void add_vector_para(const T& a) {
		vec.push_back(a);
	}
	void test_all_of() {
		//all_of return true if pred returns true for all the elements in the range [first, last) or if the range is empty, and false otherwise.
		std::cout << std::all_of(vec.begin(), vec.end(), [](T& i) {return i % 2; }) << std::endl;
	}
	void test_any_of() {
		//any_of return true if pred returns true for any of the element in the range [first, last) and false otherwise.
		std::cout << std::any_of(vec.begin(), vec.end(), [](T& i) {return i % 2; }) << std::endl;
	}
	void test_sort() {
		//sort sorts the elements in the range [first, last) into ascending order.
		for (T& i : vec) {
			std::cout << i << " ";
		}
		std::cout << std::endl;
		std::sort(vec.begin(), vec.end());
		for (T& i : vec) {
			std::cout << i << " ";
		}
		std::cout << std::endl;
	}

	void test_sort_gen_func() {
		vec.push_back(10);
		for (T& i : vec) {
			std::cout << i << " ";
		}
		std::cout << std::endl;
		std::sort(vec.begin(), vec.end(), ::myclass_sort());
		for (T& i : vec) {
			std::cout << i << " ";
		}
		std::cout << std::endl;
	}

	void test_sort_func() {
		//sort func
		vec.push_back(1);
		for (T& i : vec) {
			std::cout << i << " ";
		}
		std::cout << std::endl;
		std::sort(vec.begin(), vec.end(), ::myfunction_sort);
		for (T& i : vec) {
			std::cout << i << " ";
		}
		std::cout << std::endl;
	}
	void test_binary_search() {
		//sorted sequence
		//binary_search return true if any element in the range [first, last) is equivalent to val, and false otherwise
		std::cout << std::binary_search(vec.begin(), vec.end(), 2) << std::endl;
	}
private:
	std::vector<T> vec;
};
bool myfunction_sort(int& i, int& j) { return (i < j); }
//泛函数 重载()运算符实现
struct myclass_sort {
	bool operator() (int& i, int& j) { return (i < j); }
};

int main() {
	//由于匿名函数的原因,测试all_of, any_of时,请用重载过%运算符的数据类型
	Test_std_algorithm<int> test_std;
	for (int i = 1; i < 10; i++) {
		test_std.add_vector_para(i);
	}
	test_std.add_vector_para(5);
	//test_std.test_all_of();
	//test_std.test_any_of();
	//test_std.test_binary_search();
	//test_std.test_sort();
	//test_std.test_sort_func();
	test_std.test_sort_gen_func();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值