r/cpp • u/shadedtriangle • Nov 01 '21
C++ By Example - A new website for learning C++
https://cppbyexample.com10
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
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
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
Nov 02 '21
[deleted]
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.
1
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.
1
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++11flag).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};1
2
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
2
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
2
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.
2
5
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
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
1
2
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 usestd::ssize()instead of.size()andstd::size(), which returns a signed integer.std::ptrdiff_tis considered to be the signed counterpart ofstd::size_t[4] and therefore I usestd::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.
[3] https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-why-to-avoid-them/
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
Nov 02 '21
[deleted]
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
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.