65
\$\begingroup\$

What general tips do you have for golfing in C++?

I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C++ (e.g. "remove comments" is not an answer). Please post one tip per answer.

(Tips that apply to C as well can be found in Tips for golfing in C - but note that some C tips don't work in C++. For example, C++ does require function prototypes and return values.)

\$\endgroup\$
3
  • 7
    \$\begingroup\$ Many of the tips for golfing in C are also applicable to C++, so please assume that readers are familiar with that question; only post here if you have something that isn't also a valid C golfing tip. \$\endgroup\$ Commented Apr 21, 2016 at 16:47
  • \$\begingroup\$ @TobySpeight Probably because they have the same url besides the question ID. \$\endgroup\$ Commented Jan 5, 2017 at 19:22
  • \$\begingroup\$ C and C++, even if not 'golfing' type, are right and easy (if one consider the right subset of C++) \$\endgroup\$ Commented Aug 12, 2019 at 21:37

32 Answers 32

1
2
1
\$\begingroup\$

From C++11, a std::string is always zero-terminated. Thus, of all the characters, exactly the last one is falsy. So, these loops are equivalent:

#include<string> std::string s; // indexed loop, yielding an index // ungolfed for(int i = 0; i < s.size(); i++) { std::cout << s[i]; } // golfed C++98 for(int i=0;i++<s.size();)std::cout<<s[i]; // golfed C++11 for(int i=0;s[i++];)std::cout<<s[i]; 

Note, that depending on the surrounding code, the following alternative looping techniques may be more efficient:

// C++11 iterator loop, yielding an iterator for(auto i=s.begin();i++<s.end();)std::cout<<*i; // C++11 ranged-for loop, yielding a character for(auto c:s)std::cout<<c; 

The latter work likewise for std::vector.

\$\endgroup\$
2
  • \$\begingroup\$ Instead of for(auto i=s.begin();i<s.end();i++) consider for(auto i=begin(s);i<end(s);i++) or for(auto i=&s[0];i<&*end(s);i++) if your container supports them. \$\endgroup\$ Commented Apr 2 at 7:15
  • \$\begingroup\$ ... and if it's worth to spend the 20 characters for using namespace std;. \$\endgroup\$ Commented Apr 3 at 21:12
0
\$\begingroup\$

Don't use string(""), use "". It saves 8 bytes.

\$\endgroup\$
3
  • 4
    \$\begingroup\$ It's not exactly equivalent. For example "" + 'a' is char* + char, which is pointer addition, while std::string("") + 'a' is std::string + char - string concatenation. string() would work. \$\endgroup\$ Commented Dec 8, 2017 at 9:49
  • \$\begingroup\$ I would suggest using ""s. This saves 7 bytes and still is a std::string. \$\endgroup\$ Commented Apr 20, 2022 at 0:55
  • \$\begingroup\$ you need using namespace std::literals to use ""s \$\endgroup\$ Commented Jun 16, 2023 at 18:17
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.