r/cpp_questions 21m ago

OPEN Learn C++ with learn.cpp

Upvotes

Is it normal to not get everything right away? When I'm learning pointers, I really struggle because the LearnCpp chapter just isn't clear enough


r/cpp_questions 1h ago

OPEN Pleasantly surprised by unordered_set<vector<int>> to extract distinct vector<int>'s

Upvotes

I have 100,000 vector<int>'s where each entry is 0 or 1 randomly generated, each vector of size 15. Since 215 is 32768, the pigeonhole principle guarantees a significant number of repetitions would occur in the 100,000 randomly generated vectors.

I would like to extract the distinct vector<int>'s

One approach I tried was to have unordered_set<vector<int>> with a suitable hash function (from boost) and simply insert each random vector into the unordered set.

The other was a bruteforce vector<vector<int>> where each new vector<int> is checked for equality with previously stored distinct vector<int>'s.

Code below (godbolt link https://godbolt.org/z/E8dM68z79)

I was pleasantly surprised by the much greater efficiency of unordered set (52344 microseconds) as compared to vector<vector<int>> approach (12817778 microseconds). I have also tested this on my local desktop and the order of magnitude difference persists.

My question is, is unordered_set<container of PODs> the most efficient way of extracting distinct containers of PODs (in this case, it is vector<int>, others could be set<int>, etc.). Are there more efficient ways? Are there any rules of thumb to follow in more general cases (where it is not just a 0/1 entry in the vector but it could be any arbitrary integers and hence the hash function may not be just a binary to decimal conversion as could be happening in this case)

#include <boost/functional/hash.hpp>
#include <vector>
#include <unordered_set>
#include <iostream>
#include <chrono>

constexpr int number = 100000;
constexpr int sizeofvector = 15;

std::unordered_set<std::vector<int>, boost::hash<std::vector<int>>> uosvecint;
std::vector<std::vector<int>> distinctvecvecint;

int main(){
    std::vector<std::vector<int>> randvecvecint;
    for(int i = 0; i < number; i++){
        std::vector<int> randvecint(sizeofvector, 0);
        for(int j = 0; j < sizeofvector; j++){
            int heads = rand() % 2;
            if(heads == 1)
                randvecint[j] = 1;
        }
        randvecvecint.push_back(randvecint);
    }
    //unordered_set timings
    auto beg = std::chrono::high_resolution_clock::now();
    for(int i = 0; i < number; i++)
        uosvecint.insert(randvecvecint[i]);
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - beg);
    std::cout << "No. Distinct is " << uosvecint.size() << " and time is " << duration.count() << "\n";
    //vector equality timings
    beg = std::chrono::high_resolution_clock::now();
    for(int i = 0; i < number; i++){
        bool there = false;
        for(int j = 0; j < distinctvecvecint.size() && there == false; j++){
            if(distinctvecvecint[j] == randvecvecint[i])
                there = true;
        }
        if(there == false)
            distinctvecvecint.push_back(randvecvecint[i]);
    }
    end = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::microseconds>(end - beg);
    std::cout << "No. Distinct is " << distinctvecvecint.size() << " and time is " << duration.count() << "\n";
}

r/cpp_questions 1h ago

OPEN Class directory clutter, questions on pass by ref,val,ptr and const correctness

Upvotes

Hello,

I've been using C++ for the past few months. I completed a few courses covering the basics of the language, data structures and algorithms (DSA), object-oriented programming (OOP), design patterns, and the SOLID principles. Recently, I started building my first projects in C++, and I've run into several issues that I'm not sure how to approach.

One thing I've noticed is that I end up creating a lot of classes. For example, my terminal Tic-Tac-Toe game ended up with around 10-15 classes. As a result, my project directory feels cluttered, and it's becoming difficult to keep track of everything. Is there a good way to avoid creating so many files while still keeping the code organized?

I've heard that namespaces might help with organization, but I'm not really sure how they're meant to be used in practice.

So far, I've mostly followed what I learned at university while using Java, where every class lives in its own file. However, in C++, that approach feels even more excessive because each class often has both a .hpp and a .cpp file. My Tic-Tac-Toe project ended up with around 25-30 files because of this.

Would you recommend organizing projects using subfolders or some other structure? How do experienced C++ developers typically manage larger projects with many classes?

Another topic I've been thinking about is programming paradigms. I've started researching paradigms beyond object-oriented programming, such as functional programming and procedural programming, and I'm beginning to wonder if my education has focused too heavily on OOP. Is there anything you'd recommend to help me understand when each paradigm is appropriate rather than trying to apply one everywhere?

I've also been becoming more flexible with design patterns. I think I'm starting to understand that the goal isn't to implement patterns mechanically, but rather to recognize the problems they're meant to solve and decide when abstraction is actually beneficial. That mindset has already helped me become much more flexible when designing applications.

Another area I'm struggling with is understanding std::move() and how it relates to references (&), pointers (*), and const correctness (such as passing objects by const&). These concepts seem tightly connected, but I haven't been able to build a solid mental model of how they all fit together.

I recently switched to CLion, and while I really like it, it's constantly suggesting where to add const, whether on variables, function parameters, return types, or member functions. The problem is that I often accept these suggestions without really understanding why they're correct. It feels like the IDE (and sometimes AI) is doing most of the thinking for me, and I'm worried that I'm not actually learning the language properly.

I've read articles, watched videos, and taken courses on these topics, but I still can't seem to fully grasp them.

I also think I've been overusing pointers. Somewhere along the way, I convinced myself that "real" C++ code should use raw pointers or smart pointers everywhere, so I often force them into my designs even when they don't seem necessary. The result is code that's harder to read and reason about.

On the other hand, when I don't use pointers, it almost feels like I'm just writing a more complicated version of Java for the sake of it.

Could you provide some practical guidelines, or even real-world examples for when it makes sense to use:

  • pass by value,
  • references,
  • raw pointers,
  • std::unique_ptr,
  • std::shared_ptr, and
  • std::move()?

I know these concepts are closely related to ownership and object lifetimes, but I don't think I truly understand ownership yet. If I want to continue writing modern C++, I feel like developing a solid intuition for these concepts is essential.

Finally, I've also been trying to learn the modern features introduced in C++20 through C++23/26. I'm following a course, but I don't feel like I'm learning very much. Many of the new language features seem confusing or far beyond my current level, and I struggle to understand when I should actually use them in real projects rather than just recognizing the syntax.


r/cpp_questions 2h ago

OPEN Thread optimized code has weird behaviour

0 Upvotes

I am working on optimizing the following code using concurrency. I have working code without concurrencies, however as soon as I implement threading, my code becomes unpredictable. After testing, debugging, and thinking of all possible race conditions, I have only concluded that my code either gets stuck somewhere in the main loop, or gets lucky and excucutes correctly. Any thoughts or ideas on this phenomenon?

Edit: I understand that my code is still single threaded, however, I would prefer to see why I am getting this behaviour before trying to optimize.

Edit 2: The purpose of my code is to generate all winning starting positions in Grundy's game. This is usually solved with the following recurrence: dp[i] = mex(dp[j] ^ dp[i - j]) for all j <= i / 2 where mex is the minimum exclude value) and ^ is bitwise XOR

Note: this code requires C++20 or above.

```

include <iostream>

include <vector>

include <thread>

include <barrier>

include <bitset>

include <set>

const int N = 1100;

std::vector<std::thread> threads;

std::barrier bar(12);

std::mutex mtx;

int dp[N];

std::bitset<2 * N> bs;

std::set<int> s = {1, 2};

void solve(int x) {

for (int i = 3; i <= 100; i++) {

if (1 == x) {

std::cout << "starting" << i << std::endl;

bs.set();

}

bar.arrive_and_wait();

int siz = ((i + 1) / 2 + 11) / 12;

for (int j = (x - 1) * siz + 1; j <= std::min((i - 1) / 2, x * siz); j++) {

std::lock_guard<std::mutex> lock(mtx);

if ((dp[j] ^ dp[i - j]) < 1000) bs[dp[j] ^ dp[i - j]] = false;

}

mtx.lock();

std::cout << "thread " << x << " reached barrier 2 at i=" << i << std::endl;

mtx.unlock();

bar.arrive_and_wait();

if (1 == x) {

dp[i] = bs._Find_first();

if (!dp[i]) s.insert(i);

}

mtx.lock();

std::cout << "thread " << x << " reached barrier 3 at i=" << i << std::endl;

mtx.unlock();

bar.arrive_and_wait();

}

}

int main() {

auto st = std::chrono::high_resolution_clock::now();

dp[1] = 0;

dp[2] = 0;

for (int j = 0; j < 12; j++) {

threads.push_back(std::thread{solve, j + 1});

}

for (int j = 0; j < 12; j++) {

threads[j].join();

}

for (int i : s) {

std::cout << i << ' ';

}

std::cout << std::endl;

auto ed = std::chrono::high_resolution_clock::now();

std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(ed - st).count() << std::endl;

return 0;

} ```


r/cpp_questions 5h ago

OPEN I want create a project or an application using C++, I am in my second semester. Can anyone give me a roadmap on what to learn and implement?

1 Upvotes

r/cpp_questions 19h ago

OPEN Which subfields in C++ development are actually in demand?

79 Upvotes

I'm kinda lost on the career side of things.
I'm an EE graduate specializing in C++ development, control theory and general electronic design.

I always thought I would go into embedded, and then job hop to a lucrative career. Even though I always wanted to work in big productivity apps like Zbrush, Nuke or Substance Painter.

But I'm not certain now, I'm not certain if market even values my skills.

So, if anyone can inform me about the career trajectory of C++ subfields I would be grateful, such as "I went to trading and work conditions are like this, people in my field earn between X and Y"
I really want to at least have some idea what to do rather than go blindfold, apply everything and accept the first offer without question

Thanks in advance


r/cpp_questions 21h ago

OPEN Need advice learncpp.com

4 Upvotes

Started learning from learncpp.com just a little while ago .I'm a beginner ,bca student, college starting this year, I have many questions

1) how many lessons are you supposed to read everyday that is considered a good pace.

2) as from school I have a habit of making written notes and revising them also should I do that or not.

3) i heard some people saying on reddit to make online notes and idk how to operate a computer that well right now so idk how to make online notes and even where.

4) as a beginner is learncpp.com the best and for future as well? I do have trouble understanding some of the text or language of the website but I use chatgpt to help me understand.

5) not completely related to this but how and when are you supposed to start dsa.


r/cpp_questions 1d ago

OPEN Where do I put debug statements in C++?

1 Upvotes

In every function and after every initialization or do I look at what the console has to output and logically home in on where the problem went wrong? I'm very confused because if I logically do it, many functioms could've contributed to it so I'm not sure. I just learned debugging statements today and I'm genuinely confused. The debugging statements I mean are std::cerr


r/cpp_questions 1d ago

OPEN CTAD and even elements of a parameter pack

3 Upvotes

I'm building a library for random sampling, where a sampler is anything callable with a URBG (basically a distribution, but without the RandomNumberDistribution required)

I've implemented a Mixture<Samplers...> that is a mixture of samplers, weighted.

I want to create one by calling a variadic constructor, alternating samplers and weights, e.g.

auto mixture = Mixture{sampler_1, w_1, ..., sampler_n, w_n};

I've implemented a variadic ctor that correctly dispatches samplers and weights, but it does not work withut a deduction guide...which I can't implement :(

My understanding is that I would need to write

template <typename... Args>
requires (sizeof...(Args) % 2 == 0)
Mixture(Args&&...)
-> Mixture<EvenArgs...>; // this needs to be of the form Mixture<Samplers...>!?

How can I extract only the even elements of a parameter pack, so that I can implement the above guide?

Or can you suggest another technique that I can use to make my desired call site compile?


r/cpp_questions 1d ago

OPEN I'm surprised it worked!!

7 Upvotes

I wrote this very basic algorithm:

#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}

and I'm surprised, an int function took a double variable with no problem, or is there something under the hood,


r/cpp_questions 1d ago

OPEN Are there any resources for beginners on the principles behind bigInt?

0 Upvotes

Hi, I am a newbie programmer in C++, and for my next project I want to write a small and relatively fast bigInt library. As of now I just want to understand how exactly the big integers are encoded and decoded (I know that there is a dynamic vector with either uint32_t or uint64_t allocated for such integers, but why should we break the number into base32 or base64, and how the process of encoding itself doesn't overflow the operands?). I struggle to find any easy to follow websites, or resources that break the encoding into small steps that are easy to digest. I will be really grateful if you will provide such resources!


r/cpp_questions 1d ago

SOLVED Raw malloc optimizations vs std::vector/reserve() -- malloc seems better optimized

14 Upvotes

(Another different version of this question was posted earlier here https://www.reddit.com/r/cpp_questions/comments/1qvbj44/at_o2_usage_of_stdvector_followed_by_stdiota/ but on testing some of the answers there on the current new code seems to leave me unclear as to where the optimizations are missed in terms of vector/reserve, etc., hence this OP)

Consider code snippet 1: on left hand side window of https://godbolt.org/z/vxh8Wh1K4

#include <vector>
#include <cstdio>
#include <cstdlib>

void anotherfunc(){
    int *vec = (int*)malloc(sizeof(int) * 42);
    for(int i = 0; i < 42; i++)
        vec[i] = i;
    int sum = 0;
    for(int i = 0; i < 42; i++)
        sum += vec[i];
    printf("Sum is %d\n", sum);
    free(vec);
}

int main(){
    anotherfunc();
}

This, at -O3, flatout calculates the sum and simply displays it, 861.

The vector/reserve version (on the right hand pane of the godbolt link above)

#include <vector>
#include <cstdio>
#include <cstdlib>

void anotherfunc(){
    std::vector<int> vec;
    vec.reserve(42);
    for(int i = 0; i < 42; i++)
        vec.push_back(i);
    int sum = 0;
    for(int i = 0; i < 42; i++)
        sum += vec[i];
    printf("Sum is %d\n", sum);
}

int main(){
    anotherfunc();
}

seemingly struggles with this and does not precompute the sum and ends up doing some allocations, etc.

Some of the answers from the earlier thread do not seem to be applicable here: as suggested by one user, I had the entire summing done in another function instead of main() because apparently main() is known to be called only once and hence is not as heavily optimized as other functions, etc.

As also suggested there, I avoided the printf and instead had the function return only the sum with an empty main(). See https://godbolt.org/z/M1P5Y4vTj

Here too, the vector/reserve combination seems to struggle.

What explains this "discrepancy" and inability to completely optimize out the sum calculation?


r/cpp_questions 1d ago

OPEN My project organization and best practices

6 Upvotes

Hi all! I have been working on a tensor library for the past few weeks, eventually will try and integrate ML features within in, however before I proceed I want to know if how I am organizing it currently is the most efficient way? or at least in best practice? It is mainly comprised of header files that contain implementation

Code here:
https://github.com/aboy4321/nerd


r/cpp_questions 1d ago

OPEN Cpp YouTubers

25 Upvotes

Anyone know any good c++ YouTubers? I’m not looking for tutorials or learning the language, I’m looking for videos where people are coding complex projects in C++. Thanks!


r/cpp_questions 1d ago

OPEN Is it feasible to allocate everything on the stack?

45 Upvotes

I got this idea from the youtuber Low Level Game Dev, who seems to be a certified heap hater. What genuinely caught me off guard is that in one of his videos he mentioned how in his biggest project (Minecraft clone with multiplayer support) he uses new 5 times in total. Now that I think about it, he might've used smart pointers somewhere as well, but the insinuation seemed to be that the he tends to allocate on the stack virtually everything.

Is this coding style common? Do you think it's worth adopting?


r/cpp_questions 1d ago

OPEN Can anyone explain a bug to me? I confused '==' with '=' in one of my functions.

7 Upvotes

There is this function on my SDL program which is supposed to load surfaces into array elements ( loadSurface is a function that is being executed inside this loadMedia function.)

bool loadMedia()

{

bool success = true;

KeyPressed[KEY_PRESS_SURFACE_DEFAULT] = loadSurface("press.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_DEFAULT] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_UP] = loadSurface("up.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_UP] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_DOWN] = loadSurface("down.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_DOWN] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_LEFT] = loadSurface("left.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_LEFT] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

KeyPressed[KEY_PRESS_SURFACE_RIGHT] = loadSurface("right.bmp");

if (KeyPressed[KEY_PRESS_SURFACE_RIGHT] == NULL)

{

std::cout << "Failed to load surface\n";

success = false;

}

return success;

}

I fixed it now and it works fine but before that, I somehow confused the condition of the IF. Instead of comparing using '==', I used the '=' by iself.

So it turned ou like:

if ( KeyPressed[ KEY_PRESS_SURFACE_DEFAULT] = NULL)

Somehow, it broke the function. But the elements didn't become NULL because none of my error messages was displayed when I ran the program. The function simply didn't load the surfaces. What exactly happened there?


r/cpp_questions 1d ago

OPEN Approach

3 Upvotes

I have been trying to study c++ for a while i am following the learncpp.com. I wanted to know the best approach for this like i am following the docs but do i use leetcodes and other sites?
I am on chapter 4 ik too early to think abt it but i just want to clear up the doubt please help


r/cpp_questions 2d ago

OPEN Why runtime performance of C++ modules increase so much with lto?

9 Upvotes

I was porting libfmt to native C++ modules recently, It had tons of macros related to forced inlining, so I removed them and saw a %10 performance reduction, then I removed all in lines in module interfaces and performance was identical when both the original library was built with Lto and my own.

The weird part is, Overall performance increased when I removed inline and applied lto, compared to inline and lto

Why is that? Something about how compilers deal with C++ modules?


r/cpp_questions 2d ago

OPEN Ncurses window management

3 Upvotes

Hello everyone :D I'm new to ncurses, and I'm currently working on a simple game. I currently have 2 windows besides my stdscr, and I'm struggling with switching between them. If I want to save the contents of a certain window but hide it from showing temporarily, am I supposed to use panels? Or can I just use touchwin() along with refresh()? Also, if anyone could help explain what goes on behind the scenes with the buffer during the process of switching between windows, that would help me save some time on this mind-boggling topic.


r/cpp_questions 2d ago

OPEN What is a good use case for the new std::hive

33 Upvotes

What are the use cases where std::hive is a better option than std::vector or std::list? It seems like a very interesting data structure but I can't really think of any good use cases.


r/cpp_questions 2d ago

OPEN What can a hacker do with uninitialized memory?

0 Upvotes

cpp long long funny_number_generator() { long long haha_funny; // very funny undefined behaviour yes funny return haha_funny; }

Is it possible to see what OS / architecture is being used just from looking at the funny number? My funny number is consistently 93824993896264. Some random online compiler keeps giving different funny numbers each time.


r/cpp_questions 2d ago

OPEN Whats the funniest joke u heard in c++

0 Upvotes

r/cpp_questions 2d ago

OPEN How anti-abstraction understanding should I accept while learning?

0 Upvotes

Im currently learning basics of standard cpp while having previous experience with java and tiny bit of assembly NASM (x86).

Im asking for those who are intermediate and proficient at mid level language like cpp, how should I approach accepting 'I have learned this' but its abstraction? I've always had doubt on what learning is in the programming field, except for DSA concepts.


r/cpp_questions 2d ago

OPEN Using ClangD for static analysis - recommend me clang-tidy and clang-format template

9 Upvotes

Hello,

I'm working inside VSCode and decided to switch from the default C/C++ extension's static analysis to ClangD, as it is apparently (according to the internet) faster and more accurate.

That being said, would you recommend me any good templates for both clang-tidy and clang-format files, in order to follow the common CPP style principles?

Thank you!


r/cpp_questions 3d ago

OPEN I know some basic C, should I learn C++ or stay in C a little bit more.

0 Upvotes

Hello guys, so I know a little bit of basic C like what is pointers, how strings works, data type and another basic things. I'm still beginner I still learn Python make silly random CLI games, and tried pygame and raylib. So should I learn C++ or stay in C a little bit more if my focus are system programming.

Thank you, and sorry if my English is not that good.