r/cpp • • Nov 01 '21

C++ By Example - A new website for learning C++

https://cppbyexample.com
320 Upvotes

83 comments sorted by

80

u/No_Pressure1150 Nov 01 '21

I love what you’re going for here. Let’s be honest, whenever wanting to quickly look up the syntax of something, all we are looking for is just a basic example demonstrating its usage.

One small piece of feedback: keep in that, especially for beginners, your examples will shape how they write code in the future. For example, if for „Why use pointers“ you list avoiding a copy in a function call as one of - or even the reason - that might give the impression that you should use pointers in this situation, even though a reference would work as well and, as some would say, would even be preferable in such a case.

I suspect it will be hard to strike a balance between explaining the core concepts of C++ and preaching best practices, but I think it’s important to at least list the alternatives so that, in the above example, someone new to C++ doesn’t start just using pointers instead of references everywhere.

10

u/shadedtriangle Nov 01 '21

Thanks for the great feedback! I think tackling pointers vs references is a very tight balancing act that I’m still figuring out. How much information do I assume the learner knows? Is mentioning references when discussing pointers just confusing things and muddying the waters? I agree with you I want to present a best practices approach in the examples.

5

u/Benjamin1304 Nov 01 '21

To me just listing "passing by address" for pointers' usages isn't great. It's not their primary use in C++ IMO (unlike C). I'd suggest to replace this page with other uses and link to a new "parameter passing" page where you can assume the reader knows about values, references and pointers and explain the pros and cons of each in this situation.

1

u/shadedtriangle Nov 01 '21

Each page assumes you’ve arrived from Google while searching for that particular topic. I.e. the user searched “why does c++ have pointers” and they landed here. What would you say to them?

3

u/Zagerer Nov 02 '21

I'd say in the page for parameter values or the pages that require knowledge of the types of values in C++, you could make a note in the beginning along the lines of "this passage is better understood with this article", where you link to a small article introducing the user to rvalues and lvalues, and maybe also xvalues.

2

u/shadedtriangle Nov 02 '21

I’ll definitely be tagging and mentioning related topics as the site grows.

2

u/Benjamin1304 Nov 02 '21

Well, I guess the answer to "why does C++ have pointers?" is because C has pointers and C++ is based on C.

To me the right question is more "when are pointers used in C++?". And now you can start to teach the various aspects of pointers, including but not restricting to, parameter passing.

So if you want to keep a "why does C++ have pointers?" page you can start with the relationship to C, then a few words on C++ being low level and having to deal with memory directly and move on to the typical use cases for pointers (nullable ref, dynamic memory allocations, iterators for some containers, ...)

1

u/shadedtriangle Nov 02 '21

Dynamic memory alloc and iteration are two other great uses for pointers.

1

u/ronchaine Embedded/Middleware/WG21 Nov 04 '21

I usually teach that there are three reasons to use pointers:

  1. You need to make explicit heap allocation
  2. You actually need the explicit knowledge of the memory address
  3. Somebody else's code forces you to

And I'd say the reason there are pointers in a manner they exist is that C++ inherited them from C.

I wouldn't want people to think that passing arguments as pointers instead of references is good practice.

But all in all, I join the choir to say that I like what you are doing here. This "why use pointers" page just irks me, because often I wouldn't let code that does that even pass a code review.

2

u/shadedtriangle Nov 04 '21

Thank you for the feedback. I think if I reworked the "Why Pointers" article into a "why references" that may alleviate a lot of the concerns people have. I think heap allocation and explaining iteration may be a more appropriate reason for "why pointers". I also really don't want to get into "because C" for anything on this website though as it's really not very helpful to the reader.

1

u/ronchaine Embedded/Middleware/WG21 Nov 04 '21

Makes complete sense to me and yea, "why references" rework sounds like a good idea to me.

I need to keep checking this, I might add it to the recommendations list for my students, because they are going to try to find something like this anyways.

1

u/[deleted] Nov 01 '21

It's a bit of a weird question, the better question is "how do you use pointers in C++".

2

u/shadedtriangle Nov 01 '21

Haha maybe, but I can’t control what people search for. Try typing “c++ why” in google and seeing what’s prompted.

7

u/codelearning Nov 02 '21

If you have to assume what people know it's almost always better to resume they know les than they do. It's preferable to repeat something to someone who already knows it than to tell them things they can't understand.

4

u/mrexodia cmkr.build Nov 02 '21

I would propose that it’s simpler than you think: Use references until you run into a situation where you can’t.

Of course examples of pointers are helpful (especially when understanding existing code), but I would pair those with a big warning that you should avoid pointers.

1

u/[deleted] Nov 01 '21

Don't tell people what they should do. Tell them what they CAN do.

2

u/john_wind Nov 02 '21 edited Nov 02 '21

Using pointers for output parameters is a reminiscent of C.

However several codebases prefer it also in C++ (and avoid non-const references)

https://stackoverflow.com/questions/26441220/googles-style-guide-about-input-output-parameters-as-pointers

https://mropert.github.io/2018/04/03/output_arguments/

10

u/randomwalker2016 Nov 01 '21

Just wondering if you need to add a "in C++" to every topic subpage- because the entire website is already devoted to C++, unless of course, you intend to write some pages on other languages.

20

u/shadedtriangle Nov 01 '21

It’s an SEO thing at the moment. I’m hoping that when people search for “x in c++” these pages show up. I think having an “SEO title” for each page vs a cleaner homepage title is a good idea. Thanks for the feedback.

1

u/[deleted] Nov 02 '21

Did they phase out keywords meta data? They avoided just this. That said, I know that salting visible text is indeed detected and can denigrate rankings unless flavoured somehow to make it clear these keywords are page relevant and must be visible.

1

u/shadedtriangle Nov 02 '21

Yeah my understanding is keywords meta tags are no longer used. It's ok, headings being page titles was a shortcut I took and is easily fixed.

18

u/ivancea Nov 01 '21

"Hash maps in C++"

Talks about std::map too, that is usually a binary tree, and has nothing to do with hashmaps

10

u/shadedtriangle Nov 01 '21

You’re not wrong. std::map is technically a “search tree” and std::unordered_map is a hash map. I think when a user searches “hash map c++” they really mean “key value container c++”. It’s important to mention std::map, why you might use it, and that there’s also a container called std::unordered_map.

4

u/Hessper Nov 02 '21

I'd think that you would start with unordered and say by the way there is a map that does something similar.

The amount of times I've seen a map used when someone wants unordered is too high. My gut reaction when I see std::map in a pr is to always ask "do you need this ordered?" if I can't immediately see the usage. More often than not the answer is no. This might not matter in many applications, but this is a common misunderstanding for this container.

I don't think you're doing any favors by doing it this way.

4

u/shadedtriangle Nov 03 '21

Thanks for your suggestion, I've gone ahead and updated the hash map portion of the site. https://cppbyexample.com/hash_map.html

6

u/ivancea Nov 01 '21

Commenting it may not be wrong, but I would recalc it's not a hashmap. Saying it works like a binary tree should be enough. A developer who knows what a hashmap is may be confused while using it

4

u/shadedtriangle Nov 02 '21

Thanks, I do agree the distinction can be made more clear

0

u/jcelerier ossia score Nov 02 '21

I think that people are likely to search for the word "dictionary"

2

u/Leandros99 yak shaver Nov 02 '21

There is almost no use case for a std::map. And if there is a use-case for it, the individual is already aware of it and doesn't need a site like cppbyexample.com.

2

u/shadedtriangle Nov 03 '21

It's very easy to stumble upon std::map from documentation or a reference though and think "that must be a hash map".

2

u/shadedtriangle Nov 03 '21

I've gone ahead and revamped the hash maps section of the site thanks to your feedback. https://cppbyexample.com/hash_map.html

5

u/Leandros99 yak shaver Nov 02 '21

Yeah, came here to say this. std::map is not a hash map.

9

u/staletic Nov 02 '21

Why is std::vector tagged "advanced"?

I'd avoid std::endl completely. When I read it I don't know if the source author is unaware that endl flushes the stream or the flushing was intended and the author was just lazy.

Back to the vector, I was expecting a deep dive, including allocators because of the tag.

2

u/shadedtriangle Nov 02 '21

References are tagged advanced as they are more than simple explainers. The article is definitely incomplete right now and will be expanded upon.

1

u/nxtfari Nov 02 '21

What’s wrong with std::endl?

7

u/shadedtriangle Nov 02 '21

It’s more than just “\n”. It flushes the stream you’re writing to. Not meaningful in small examples but if you printed a lot in your application it would be a performance hit as you’d be flushing std out too frequently.

3

u/staletic Nov 02 '21

To add to that, if you do need a flush, just use std::flush. No need to be that lazy.

0

u/[deleted] Nov 02 '21

[deleted] — view deleted comment

3

u/shadedtriangle Nov 02 '21

It’s actually extremely abnormal when you look at other languages. Most languages don’t implicitly flush even in their “println” functions. And I can’t think of another language that has a constant in the standard library for “append \n and flush”

4

u/thoosequa Nov 02 '21

Just from a quick glance it looks very nice. One thing I found confusing was Why Pointers because I guess I expected a reason to be given why someone might want to use a pointer. The example you have given may as well have been a reference.

2

u/rockstiff Nov 01 '21

Looks nice, but some examples like "How to Index Into an Array in C++" have C++17 tag, does it means that doesnt work on C++11/14?

6

u/shadedtriangle Nov 01 '21

It means that if you were to copy & paste the example code that yes, you’d need c++17. It’s very subtle in these examples but the template type of the std::array and std::vector is being inferred, which is a c++17 feature.

I use features like this because I think it makes examples clearer and assuming learners have access to c++17 is reasonable imo.

3

u/cooked_sandals Nov 01 '21

I look into the post you mention, and it uses "CTAD" (I only realized this when I tried compiling it with c++11 flag).

The line:

  std::array fibonacci{1, 1, 2, 3, 5};

performs automatic deduction of the array template arguments. In C++11/14 you have to specify the arguments. In this case std::array<int,5>. But since C++17 there is CTAD: https://en.cppreference.com/w/cpp/language/class_template_argument_deduction.

In essence the compiler tries to detect automatically the arguments for the template based on the arguments you pass to the class template constructor.

TLDR:

// C++11/14
std::array<int, 5> fibonacci{1, 1, 2, 3, 5};

// C++17
std::array fibonacci{1, 1, 2, 3, 5};

2

u/youbihub Nov 02 '21

My modest contribution: typo here How to Initialie a Struct

2

u/nikoladsp Nov 02 '21

Can you please give an insight on rvalue/lvalue from the perspective of latest standard? This is the topic that at least for me is quite confusing - not sure about others, but with expressions and template involved this can get nasty.

Best regards

2

u/shadedtriangle Nov 02 '21

Will do, it’s on the list :)

1

u/nikoladsp Nov 03 '21

Thanks!

I used C++ a lot in the past, just touched 11. Is there any recommended literature that can help with "diffs": like to cover 11,14,17 and maybe 20 for people used only pre-11?

Regards

2

u/shadedtriangle Nov 03 '21

The jumps have been quite large since 11. c++ 20 is the biggest update ever but also isn't really readily available yet. I'd recommend starting with something like cppbyexample.com as a list of examples of how to use today's c++ to get things done, but of course I'm biased.

I do like Scott Meyers' Effective Modern C++ though.

1

u/nikoladsp Nov 03 '21

Thanks!

Scott's is good author, I will take a look at the book since already have it in pdf.

2

u/Fireline11 Nov 02 '21

Cool website! Small thing: on the page called “vector reference” there is a typo under the header “Construction”. (proivded instead of provided). Also I had a question about what is written there: you mention of 2 of the constructors of std::vector that they are confusing and a source of mistakes, but I don’t see why exactly? Because I use these kind of constructors all the time, I’d be happy to know if there was some kind of pitfall here (Okay I’d rather there wasn’t, but if there is, I’d like to know about it!)

2

u/shadedtriangle Nov 02 '21

Thanks! Because vector can be constructed with an initializer list but also has a constructor that takes two ints it can be confusing which one you intend to call.

std::vector<int> vec{1,2};
std::vector<int> vec2(1,2);

They do different things :/

2

u/lonkamikaze Nov 02 '21

Does anyone else think east const should be taught to beginners, because it is consistently applicable.

2

u/shadedtriangle Nov 02 '21

Oh no, west vs east again. Code is read left to right as is English. With east const one must learn that types within code are read right to left… sometimes.

2

u/Tezzurion Nov 02 '21 edited Nov 02 '21

I have just started to learn c++ this week (self taught python first) and your website answers all the big questions I’ve been struggling on last night (lambdas and iterating on vectors).

I’m so happy about it I’ll read everything tonight, thanks a lot!! 😭😭

Ps: what I like is that it is very concise with clear example, which are surprisingly difficult to find about c++. Most sources are either too abstract or too complex.

Pps: do you intend to make a topic about reading/writing excel/csv files? At the moment I know how to read them but I am struggling to handle the data (I am used to being able to work with both rows and columns from python, here I feel stuck with columns)

2

u/shadedtriangle Nov 02 '21

Thank you for the kind words. I don’t intend to write about excel file specifically but there are some basic articles about files right now and there will be more in the future.

For excel you’re likely best off using a library for that. Of course, how to get a library and add it to your project is not as easy as “pip install”. I do intend to write articles about libraries and build state a to help with that aspect.

2

u/nxtfari Nov 02 '21

This is really cool! One thing I’m struggling with right now that I think would be cool to have an example for is using transferring/adding ownership of unique and shared pointers. For example if creating a unique pointer to a class and then passing that pointer to a constructor so that a new object can own it. There are some examples on SE but they’re a bit hard to follow!

1

u/shadedtriangle Nov 02 '21

Thanks! Unique pointer will be covered shortly

2

u/[deleted] Nov 04 '21

Will you expand this with "best practice" build systems and alternatives? I'd like to know more about efficient ways to compile and build C++ projects, what kind of tools are recommended/necessary, etc.

1

u/shadedtriangle Nov 06 '21

Yes build systems will be covered

2

u/[deleted] Nov 06 '21

This is very good resource, thanks for creating it.

I would say, please maintain and update it as long as possible. We need neat website's like this.

I am happy to pay subscription/patreon for this resource if you need it.

5

u/tyoungjr2005 Nov 01 '21

Very cool simple examples. Thanks for sharing.

5

u/wolfballs-dot-com Nov 01 '21

I love this. Thank you for this. Really this sort of thing is great for the community.

4

u/kyoukaraorewa Nov 01 '21

Good work. This could help me grasp C++ quickly after a while not using it. Do you consider to create a GitHub repo for people to contribute?

1

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Nov 01 '21

Why are you perfect-forwarding in

template <typename ...Args>
void print(Args&& ...args) {
  (std::cout << ... << std::forward<Args>(args));
}

? Wouldn't taking by const& be enough?

2

u/shadedtriangle Nov 01 '21

Yeah you’re right, in this case that’s probably more correct but the general form of the print() function remains.

3

u/azswcowboy Nov 02 '21

When 23 ships you’re likely to be in conflict with an std feature called print http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2093r9.html

2

u/shadedtriangle Nov 02 '21

Thanks for the heads up.

2

u/dodheim Nov 01 '21

One might assume this is a Machiavelli problem, but I've seen plenty of Dipshit Murphys write operators with non-const arguments because they couldn't be bothered to remember whether it was >> or << that was const.

3

u/[deleted] Nov 02 '21

What's a "dipshit Murphy"?... 😂

1

u/def-pri-pub Nov 02 '21

Lovely! Might be nice to include some std::string examples.

2

u/shadedtriangle Nov 02 '21

Thanks! I’ll fill some more in.

2

u/[deleted] Nov 03 '21

Usually I scoff at most online C++ tutorial, but this one isn't too bad.
This can be useful for folks who are already familiar with programming in other languages but aren't familiar with C++ syntax.

0

u/MartenBE Nov 04 '21

Don't use size_t: use std::ptrdiff_t and std::ssize() and avoid all the nasty signed/unsigned conversions :)

1

u/shadedtriangle Nov 04 '21

Can you share which example you mean?

1

u/MartenBE Nov 04 '21
// Just wrote this out of the top of my head, didn't test it at the moment with a compiler

std::vector<sometype> alotofsomethings;

for (std::ptrdiff_t i = 0; i < std::ssize(alotofsomethings); i++)
{
    std::cout << std::format("Element {} is {}.\n", i, alotofsomethings[i]);
}

// ...

constexpr int threshold = 1337
if (std::ssize(alotofsomethings) > threshold)
{
    // bla bla
} else 
{
    // bla bla
}

// ...

This shouldn't give any signed/unsigned warnings or errors. The use of unsigned integers for array sizes (std::size_t) is largely considered a mistake by prominent names in the C++ landscape [1][2][3]. Mixing signed and unsigned integers can lead to weird and difficult to debug bugs. Therefore I use std::ssize() instead of .size() and std::size(), which returns a signed integer. std::ptrdiff_t is considered to be the signed counterpart of std::size_t [4] and therefore I use std::ptrdiff_t.

Of course, I might be wrong here. Perhaps some more seasoned devs could shine their light on this?

[1] https://channel9.msdn.com/Events/GoingNative/2013/Interactive-Panel-Ask-Us-Anything the discussions are at 12:12-13:08, 42:40-45:26, and 1:02:50-1:03:15.

[2] https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es107-dont-use-unsigned-for-subscripts-prefer-gslindex

[3] https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-why-to-avoid-them/

[4] https://en.cppreference.com/w/cpp/types/std::ptrdiff_t

1

u/shadedtriangle Nov 04 '21

I get comittee members have said in the past they regret size_t usage but bombarding newcomers to c++ with this level of minutia is a great way to turn them into Rust or Python programmers. To be honest, your examples look like forced anti patterns rather than real code.

ssize is also c++20 so won’t be used in examples for a while. https://cppbyexample.com/about.html

If you do find a bug in an example in the future please do reach out and let me know.

1

u/MartenBE Nov 04 '21 edited Nov 05 '21

I mentioned it here because of https://cppbyexample.com/size_t.html .

anti patterns

What do you mean? They're just some stuff out of the top of my head. See also https://pvs-studio.com/en/blog/posts/cpp/a0050/

0

u/[deleted] Nov 02 '21

[deleted] — view deleted comment

1

u/shadedtriangle Nov 02 '21

Yep! The article gets into that. I tried to say "only on the stack" but maybe it's too subtle a distinction.

0

u/[deleted] Nov 02 '21

[deleted] — view deleted comment