A handy C++ one-liner

It’s often interesting to see just how much can be accomplished with just one line of code; this mini-article has been written to demonstrate a solution to an age-old problem: How to convert *argv[] into something usable in (Modern) C++.

Any seasoned C programmer will be quick to tell you there are two forms to the main() function, the empty parentheses variant and the one specifying argc (number of arguments) and argv (a pointer to an array of pointer to char).

If your head hurts if you try to determine whether there’s any difference to declaring argv as const char **argv or const char *argv[] you’re probably not alone. (No, there isn’t a difference, is the answer.) In Modern C++ we hardly want to be messing around with a single const char * if we can help it, never mind an array of them. So, how to construct and populate a vector of string views in one line? Here is the code (line 12 is the one-line magic):

// one_liner.cpp : store command line arguments in a C++ container

#include <string_view>
#include <vector>
#include <iostream>

using std::string_view;
using std::vector;
using std::cout;

int main(const int argc, const char *argv[]) {
    vector<string_view> args{ argv, argv + argc };

    for (auto& arg : args) {
        cout << "-- " << arg << '\n';

So, no loop (other than to print out the already populated args). No push_back(). Just the single vector constructor which would normally be the version accepting begin() and end() of another container, except we use the start of array and array plus length (in other words pointer arithmetic). (If this makes your head hurt too, I’m sorry. You don’t need to understand it fully in order to use it, however.)

I’ve chosen to use a vector of string views because this generates a smaller per-object overhead compared to using a vector of strings. Despite their small object size (typically a pointer and length) string views have available many of the useful member functions that string objects have. String views are particularly appropriate here as they are of course read-only, like the variable argv is, too.

Resources: Download or browse the source code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s