Skip to content

Instantly share code, notes, and snippets.

@jtbandes
Last active August 29, 2015 14:27
Show Gist options
  • Save jtbandes/683d2dbc7c7f048fca90 to your computer and use it in GitHub Desktop.
Save jtbandes/683d2dbc7c7f048fca90 to your computer and use it in GitHub Desktop.
fun things made possible by C++
// Suppose we want to convert argv/argc to a std::vector<std::string> for easier use.
// There are surprisingly many (and surprisingly concise) options:
// First pass:
vector<string> args;
for (int i = 1; i < argc; i++) {
args.push_back(string(argv[i]));
}
// Minor improvement using emplace, which forwards the char* param directly to a string constructor:
vector<string> args;
for (int i = 1; i < argc; i++) {
args.emplace_back(argv[i]);
}
// Make the for loop into a one-liner using stuff from <algorithm>/<iterator>,
// which uses string::string(char*) and calls push_back under the (templated) hood:
vector<string> args;
copy(argv+1, argv+argc, back_inserter(args));
// That works because copy()'s first 2 arguments (begin/end) can be any "iterator" type,
// which requires the ability to dereference (*it), compare (it1==it2), and increment (++it).
// We're using char** itself as an iterator. When dereferenced it becomes char*,
// so we do *[the_back_insert_iterator] = *[the char**], which implicitly converts
// the resulting char* up to a string and then push_back()s it onto the vector.
// But it so happens that vector also has a constructor which takes 2 iterators (begin/end),
// so we don't even have to bother with a loop or copy()!
// So in one fell swoop:
const vector<string> args(argv+1, argv+argc); // since it's a one-liner, can even be const!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment