Using std::placeholder

closed account (Sw07fSEw)
I'm reading about std::bind, to bind arguments into a callable object which can be passed to a function. I felt like I've understood most of the concepts up to this point, but I have a question I wasn't able to find an answer too.

In the examples where I've used std::bind, I've been using it to pass callable objects into algorithms as predicates. All of the algorithms have been algorithms such as std::sort found within <algorithm> that take either unary of binary predicates. Since their predicates only take 1 or 2 parameters, when would I use placeholders greater than _2, greater than _3, all the way thru placeholder::_N?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <functional>
#include <algorithm>
#include <string>
#include <vector>

bool isShorter(const std::string& a, const std::string& b) {
	return a.size() < b.size();
}
bool check_size(const std::string s, std::string::size_type sz) {
	return s.size() < sz;
}

int main() {
	using namespace std::placeholders;
	std::vector<std::string> words = { "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "turtle" };

	const int max_length(5);

	auto count = std::count_if(words.begin(), words.end(), std::bind(check_size, _1, max_length)); 
	//counts all words whose length is less than a specified length. Unary predicate.

	std::sort(words.begin(), words.end(), isShorter); //std::sort takes a binary predicate
	std::sort(words.begin(), words.end(), std::bind(isShorter, _1, _2)); // same a previous call

	std::sort(words.begin(), words.end(), std::bind(isShorter, _2, _1)); 
	//second parameter of the binary predicate is passed in as the first argument. Inverted.

	return 0;
}
Last edited on
when would I use placeholders greater than _2, greater than _3, all the way thru placeholder::_N?
Isn't that obvious? If you need to provide 4 parameters you may use _4. The parameters correspond to the placeholders.
Topic archived. No new replies allowed.