I'm writing a program that accepts command line arguments and prints them out in alphanumerically sorted order with a custom comparator.
Along the way I got stuck with inserting the command-line arguments in the std::set container. Reviewed some similar code online and found something like:
std::set<char*, decltype(customComparator)> args (argv, argv argc, customComparator)
What does the argv argc argument mean/do?
When I tried inserting the cmd argument like:
std::set<char*, decltype(customComparator)> args (argv, customComparator)
There's a red squiggly line on the argv argument.
CodePudding user response:
The code you're showing uses the iterator based constructor, which receive a begin iterator, and a past the end iterator.
The thing is, a pointer can very much act like an iterator. The ptr operator works, as well as ptr != end_ptr and *ptr.
So if you want to construct an stl container from a C-style collection of objects, it's very well possible to do so. argv is the beginning of all the args value, and argv[argc - 1] is the end. To get a pointer past the end, simply do argv argc.
CodePudding user response:
- This overload of the
std::setconstructor accepts two iterators and a comparator. The two iterators should define a half-open range. The second iterator points to the end of the range, which for many kinds of ranges, is the one past the last element. - A pointer is an iterator.
- If
argvpoints to the first element of an array, andargcis an integer, thenargv argcpoints toargcth element of the same array (starting from zero). - Since there are exactly
argcmeaningful elements in theargvarray,argv argcpoints one past the last meaningful element of the array. (There happens to be another element there, bit it is a null pointer and we are not interested in it).
All in all, the range [argv, argv argc) is exactly the kind of half-open range standard library expects in lots of places.
