Writing

Software, technology, sysadmin war stories, and more. Feed
Thursday, April 26, 2018

What's the size of that vector, anyway?

Following last Thursday's post about C++ maps and types, I got a neat little bit of feedback showing me even more fun stuff that you can do with vectors of things. Here's a short example program. Try to predict the output before you compile and run it. (If you're on a Mac, you'll need to add '--std=c++1z' to compile this.)

#include <stdio.h>
#include <string>
#include <vector>

int main() { { std::vector<int> v{3}; printf("vector<int> v{3} size() %zd\n", v.size()); } { std::vector<std::string> v{3}; printf("vector<string> v{3} size() %zd\n", v.size()); } { std::vector<int> v{0}; printf("vector<int> v{0} size() %zd\n", v.size()); } { // for extra goodness std::vector<std::string> v{0}; printf("vector<string> v{0} size() %zd\n", v.size()); } }

Thanks to Hyman Rosen for sending in the original, which I have adjusted a bit to fit on the page here.