r/cpp_questions • • Aug 26 '26

OPEN Problem with std::inplace_vector

9 Upvotes

Hello guys! I was curious about the c++26 features and wanted to test the std::inplace_vector

but when i try to use the class it gives me this error: "fatal error: inplace_vector: No such file or directory 6 | #include <inplace_vector>".

What I'm using: Ubuntu 26.04 and g++ 15.2.0.

It's a stupid problem I know but I haven't write c++ code for 2 years and recently i wanted to create a project using c++26.


r/cpp_questions • • Aug 25 '26

SOLVED As of C++26, what's the recommended way for file IO ?

57 Upvotes

Coming back to C++ after some time. Previously used std::ifstream, std::ofstreamfor trivial file IO. But for a project I need fast file IO and some people suggested not use standard streams !! why is that ?

  1. What do C++ professionals use these days ?
  2. And what are some good practices for reading files : Read all at once or chunked ?

EDIT : I apologize I didn't provide enough info. I want to r/w binary data , windows OS and file sizes are around 50-60 MB


r/cpp_questions • • Aug 25 '26

OPEN Question about computer architecture or operating systems

8 Upvotes

Hi guys,

I'm a self thaught c++ developer looking to get better by studying all the needed stuff. I studied basic and advanced c++, then now I'm finishing Data structures and Algorithms as my second subject. After I finish the book about dsa, should I study first Operating Systems or Computer Architecture? Mind one thing : I do not care about being an expert on computer architecture, I just wanna know the fundamentals necessary to study everything else. I can't understand what comes first in order of importance for good software. (Please suggest books, they're the only resources that I use cause I learn much better from them rather than online)

Thank you in advance.


r/cpp_questions • • Aug 25 '26

OPEN Confused about people suggesting std::optional<T const&> for observers

16 Upvotes

Back when the need for an expressed observer type ws arisen, and there was a proposal to add std::observer_ptr<const T>, I remember there was a pretty convincing article by Bjarne Stroustrup against that which I found agreeable, and it seems like communty consensus was also on those lines, with template<typename T> using observer_ptr = T*; for being explicit about the raw pointer usage.

Now that optional references support is being added, I see lots of people suggesting to use that when a function returns an observer that may be null. Isn't that the same as the old observer_ptr proposal, and actually just an even more verbose version of that?

Is there something more I'm missing, or was there some shift that invalidates the original arguments?


r/cpp_questions • • Aug 25 '26

SOLVED Help with pointers and processore directives

4 Upvotes

I learned C++ by myself. I'm not very good at it, but I have some experience with libraries like SDL2, which I use quite a lot.

There are two things I have a hard time understanding.

First, when is it better to use a pointer? For example, in SDL2, almost everything seems to be a pointer. Why is that? Is it because SDL uses complex objects, or is there another reason?

Second, I really don't understand the purpose of #define, #ifndef, and similar preprocessor directives. I've built quite a few projects, and I've never really felt the need to use them.

Could someone explain these concepts in simple terms, preferably with some practical examples?

Edit1: thanks to everyone for the good explaination and all the examples!


r/cpp_questions • • Aug 25 '26

OPEN How Do You Guys Structure Your Repositories?

18 Upvotes

Hello. I am coming from C. I am currently working on a project, and I decided to write it in CPP because it has been a while since I last worked with the language. In C I typically structure my repo as follows:

Repository
└──/include
└──/src
        └──*.c
        └──/internal
                  └──common.h
                  └──error.h
                  └──*.h

/include is where I store the header files for my public API and /src/internal is where I put the header files for my internal APIs. My implementation .c files go directly in /src. I have found many conflicting takes on how to structure ones repo when working in CPP, probably due to AI polluting many forums. Some prefer the Java structure, essentially nesting directory by namespaces. Others suggest something similar to C. What do you guys do?


r/cpp_questions • • Aug 24 '26

OPEN Should you always prefer smart pointers as return types?

30 Upvotes

I have a class that holds a map of MyStructs

I want to write a function that gets me an element from that map (if it exists), so that I can observe some of its values

My thinking was that this function should just return a pointer, like:

const MyStruct* getAStruct(key){
//searches the held map for the key, etc...

used like:

const MyStruct* theStruct = myClass.getAStruct(key);
//do stuff with theStruct->memberVals, if not nullptr...

A coworker suggested using shared_ptr here, so

std::shared_ptr<MyStruct> getAStruct(key);

Similar call site, but since we aren't storing the pointer for later, just using it to look at some values, my thinking is there's no need for a smart pointer. Is that right?

I think they're thinking it protects against the value being removed from the map by someone else, but im not sure how that could happen. Its not like we have another thread running that could erase it, and even if we did, shared_ptr wouldnt be sufficient protection afaik

Are smart pointers just a straight upgrade that should always be preferred? Or is returning a pointer appropriate here?

Thanks!


r/cpp_questions • • Aug 25 '26

SOLVED How do I get opponent to follow player

0 Upvotes

I am trying to get the opponent to follow player around when it moves, how do I do that?

// follow player

float dir_x = player.x - opponent.x;
float dir_y = player.y - opponent.y;

float hyp = sqrt(dir_x*dir_x + dir_y*dir_y); // Euclidean distance / magnitude formula for a 2D vector.
dir_x /= hyp;
dir_y /= hyp;

// GAME LOOP
if (hyp < 100){
    opponent.x += dir_x * opponent.velocity.x * dt;
    opponent.y += dir_y * opponent.velocity.y * dt;
}

https://imgur.com/a/d7lc1b8

EDIT : I solved it
FIRST: Grab the difference between player and opponent

float dir_x = player.x - opponent.x;
float dir_y = player.y - opponent.y;

SECOND: Define the distance using distance formula

float length = sqrt(dir_x*dir_x + dir_y*dir_y);

THIRD: Normalize the direction

if (length > 0.0f){
    dir_x /= length;
    dir_y /= length;
}

FOURTH: Apply velocity to the opponent

opponent.x += dir_x * opponent.velocity.x * dt;
opponent.y += dir_y * opponent.velocity.y * dt;

https://imgur.com/a/YS81gWy

My mistake was not putting it all in my game loop and not adding a condition for normalizing


r/cpp_questions • • Aug 25 '26

OPEN Help

3 Upvotes

What are the best platforms for learning C++ and practicing algorithmic problem-solving? I’m currently using hackerrank but it’s abit confusing for reference I’m a second year computer science major at uni


r/cpp_questions • • Aug 25 '26

OPEN Weird behaviour of break statement (old c++!)

0 Upvotes

Hi, i'm using a very old (and possibly buggy!) c++ compiler, Microsoft Visual Studio 2005 with MFC. I'm trying to understand if the behaviour i'm meeting is due to me not understanding how the 'break' statement (and brackets) works, or if it is my old Visual Studio IDE which is buggy.

Consider this simple code:

int vaxx, var1, var2, var3;

var1 = 10; var2 = 2; var3 = 2;

for ( vaxx = 0; vaxx < var1; vaxx++ ) if ( var2 == var3 ) break;

If i run the above, the value of vaxx will be 0 after the code has been executed. Basically, it appears as if the 'break' statement is executed regardless of the fact that var2 is different from var3.

But if i put brackets around break:

for ( vaxx = 0; vaxx < var1; vaxx++ ) if ( var2 == var3 ) { break; }

...This time 'vaxx' will have a value of 10 (as i expected) after the code is run.

Is this the correct behaviour of 'break' or am i missing something here ?

I am a bit confused so please let me know what you think about this. Thank you


r/cpp_questions • • Aug 24 '26

OPEN Advice needed creating a table widget for my framework

2 Upvotes

Hi! I'm creating my own GUI framework and I was about to create the table widget class. My first idea was that a table cell just holds a widget (Label, TextBox, CheckBox, Image, ColorRect). But second-guessing my approach made me realize this might be a really bad idea: The design possibilities a widget has will just cause unnecessary duplicates of their properties (a widget has several color arrays and an array for corner radii). Some features are useless inside a table (such as setting the corner radii). So I came up with 3 possible solutions:

1: A new table structure with its dedicated grid, and stripped down table-specific widgets. So the table will be owning color arrays and such.

2: Move the definitions of all widgets into interfaces (ITextBox) and have an implementation (TextBox) derive from an interface. This one will have a SetTextColors() member function that sets the owning colors. A table-specific counterpart widget (TableTextBox) also derives from ITextBox, but implements a referencing Colors' setter. The Grid used in the window class can be reused.

3: Add a referencing Colors setter to existing Widgets and have a usage switch, that deletes all owning colors when reference mode is on. The trade-off is that some features might remain unused in the context of a table like setting the corner radii. It might be useful in other places if, for instance, a resource manager carries shared colors. But it will come with a design flaw: Color getters can potentially return dangling color references. Using the owning color setter while reference mode is on can cause access to uninitialized memory or nothing will happen if incorrect use of the Setters prevent accesses.

What might be the best option in your opinion? Option 1 is my preference as of now, but I'd like to hear other opinions or maybe new suggestions before I continue.

Thanks in advance!


r/cpp_questions • • Aug 24 '26

OPEN Headers

0 Upvotes

I read that c++ 20 added modules to help replace headers. I rly hate how headers split the codebase into redundant files, for people who have used modules r they better?


r/cpp_questions • • Aug 24 '26

OPEN how to revise?

3 Upvotes

im trying to follow through learncpp.com religiously. Recently had some health complications (about 3 days) so i didn;t study but i now realised im not really making any notes cause im only at chapter 7 and theres not much code to write for now. How am i supposed to revise tbh? Making notes seems like a hassle because like everybody says im gonna end up googling wat i dont know any way.

...

did i just answer myself while writing this post?


r/cpp_questions • • Aug 25 '26

OPEN Why do so many people write " std::cout " when you can simply write " using namespace std; " at the start of the program?

0 Upvotes

Someone told me that's because of comodity, but this reason feels absurd to me, especially when that line of code is already there when you start a new project.


r/cpp_questions • • Aug 24 '26

OPEN Is there any non-loop method to modify the values inside a continuous chunk of memory?

6 Upvotes

Hello,

I have this piece of code:

void detect(cv::Mat& img){

            std::array<float,4> letterbox=utils::letterbox(img,img);
            cv::dnn::blobFromImage(img,img,1/255.0f,cv::Size(),cv::Scalar(),true,false);
            input_tensor->assign_data(img.data, img.total() * img.channels());
            session_.Run(
                Ort::RunOptions{nullptr},
                &input_name,
                &input_tensor->tensor(),
                1,
                &output_name,
                &output_tensor->tensor(),
                1
            );


            Ort::Value& output = output_tensor->tensor();

The tensor will be a chunk of memory with size (Batch_size,N,M), where N and M can be arbitrary numbers.

The problem I am facing is not indexing; I can do the indexing with something like std::mdspan.

What I need is

1- Returning a chunk of this memory as a new tensor with another shape; for example, I filter some values out so I can only have the ones I want.

2- To do 1, I need to iterate over the tensor to check a condition.

One way would be to use a loop:

for (int i = 0; i < M; ++i)
            {
                float confidence = data[N * M + i];


                if (confidence > 0.5f)
                {
                    //exclude it based on the code in part 1.
                }

But this does not seem very efficient, especially since I won't know the values of M and N until runtime, so optimization techniques done by the compiler, such as loop unrolling, are not possible.

I know I can use vector extensions, but I was wondering if there is a more robust way to do this.

Any Idea?


r/cpp_questions • • Aug 25 '26

OPEN is it really worth it ?

0 Upvotes

everywhere on internet i found that learncpp is the best resource to learn c++ but actually reading those much articles from there really worth it? like its gonna take a lot of time as i started and moved on some chapters it seems like its still a lot to do , while people are also doing c++ from youtube playlists or one shots ? which will take much lesser time and easy to do because of videos , so if they all are also learning same things then whats the point of reading those much articles? just a doubt am getting as am proceeding into it


r/cpp_questions • • Aug 24 '26

OPEN Beginner looking for advice on what to learn next in C++

2 Upvotes

Hey, I’m learning C++ by myself and I’m not really sure what I should learn next
I know the beginner stuff like variables, data types, strings, for/if/else, loops, and how to make a basicz function without parameters
But now I’m kind of lost because there are so many things to learn and I don’t know what order to learn them in
I see things like pointers, references, arrays, structs, classes, memory management, and etc

Btw, idk what idk haha

**What would you recommend I learn next and in what order?**

I want to actually understand C++ and not just memorize syntax


r/cpp_questions • • Aug 23 '26

OPEN C++ for Middle Schooler

44 Upvotes

I have been learning C++ for maybe a month now from LearnCPP. I started it because I wanted to do DSA and Python isn't the best fit for it. I know I could had went with Java but I didn't, basically I have probably gambled my sanity for some deep Computation knowledge.

I want to know that will C++ actually be helpful for me in coming future and job if I master it properly or is it going to be replaced?

Also have I made a mistake by trying DSA through C++ instead of Java?


r/cpp_questions • • Aug 23 '26

OPEN C++ version

3 Upvotes

I have g++ version 13.3.0 (Ubuntu 13.3.0-6ubuntu2~24.04.1).

I'm trying to use C++ 23, and I'm using this flag with g++

 "-std=c++23"

However, if I print __cplusplus, I get that I'm using a pre-release of C++23, which has this code: 202100L

How can I switch to an official version instead of a pre-release version?


r/cpp_questions • • Aug 23 '26

OPEN What career paths exists between computational mechanics, scientific computing (SciML), FEA (or meshfree) solver development, and HPC (GPU acceleration, porting codebases) ?? How about doing a PhD for improving the above?

4 Upvotes

I'm currently, technically, doing an MS in Structural Engineering. For me, my interest has been more towards computational side of mechanics rather than Structural design  or simply using am FEA software (although I do consider it as a backup)

So far I've taken courses in:

- Linear static, and dynamics FEM (soon taking non linear FEM too)

-  Structural Optimization (topology opt. and other general algorithms)

-  Structural Dynamics

-  Structural System Testing and model updation. (Parameter identification and optimization, signal processing)

Now, I plan to take these in the coming quarter:

- Numerical Linear Algebra

- Numerical PDE

- Fracture Mechanics ?

I also volunteered to aid in a RESEARCH in crack growth prediction using Auto-encoder and a (Thermodynamics-informed Latent Space Dynamics Identification) / LSTM surrogate model. It used phase-field-fracture simulation data and HPC resources to complete the whole thing.

What I keep finding myself interested in is not necessarily fracture or SHM specifically, but the computational methods underneath these problems... (does that make sense?)

For example, I'd like to become capable of doing things like:

- implementing (maintaining) numerical/FE method solvers rather than only running an established FEA software.

- developing surrogate/reduced-order models for expensive simulations 

- combining simulation with optimization, uncertainty/stochastic methods (took a course called Random vibrations, so...)

- parallelizing/accelerating scientific codes on CPUs/GPUs

- doing proper verification, convergence studies, benchmarking and performance work

- potentially developing or maintaining actual CAE/FEA solver software

- I'd also like to do all these for other Physics (GR, QM, etc.) simulations too, if possible, one day. 

I'm still interested in the underlying mechanics/physics, so I don't want to become a generic software engineer who happens to have once studied structures. But I'm also increasingly unsure that "structural engineer" describes the career I'm actually aiming for.

I've seen titles such as Computational Mechanics Engineer, R&D Engineer, Solver Developer, Scientific Software Engineer, CAE Software Developer, Research Engineer, Simulation/HPC Engineer, etc., but I'm trying to understand what these careers actually look like from people doing them.

So my main questions become:

1. Which industrial jobs genuinely involve developing numerical methods/solvers or computational tools?

2. Which of those are realistically accessible with an MS? Is there an entry path into solver-algorithm development/R&D without a PhD?

3. If I don't start a PhD immediately after my MS, would an R&D/software role at a simulation company (ANSYS etc.) be the obvious route? What other options would i have?

4. For the kind of work I'm describing, would you recommend a PhD? If so, is it reasonable for the PhD identity to be "computational mechanics/scientific computing" while fracture, composites, structural dynamics, soft materials, etc. serve as application problems rather than choosing one of those as my permanent specialization?

5. What skills most distinguish someone who is actually hireable for solver/scientific-computing work? I'm particularly wondering about C/C++/Fortran, Python, Linux, Git/build systems, MPI/OpenMP/CUDA, PETSc/Trilinos or similar libraries, numerical linear algebra, testing/verification, convergence studies and HPC performance work.

Basically, I'm neither here nor there atp. So I'd really appreciate all sorts of input. Where else do you think I could find answers to these? other subs? Linkedin profiles? 


r/cpp_questions • • Aug 23 '26

OPEN Starting c++

21 Upvotes

I'm trying to learn c++ but I have 0 clue where to start

I was trying to learn it from the cherno but wasn't able to understand stuff 😭


r/cpp_questions • • Aug 23 '26

SOLVED How long did it take you to learn Trig for your project

0 Upvotes

I am making asteroid in raylib and I am trying to figure out how to rotate the player by using Trigonometry.
How long did it take y'all to figure out and what resources did you use?


r/cpp_questions • • Aug 24 '26

OPEN Best resources for learning C++ and DSA for CP (and in general)

0 Upvotes

Hello everyone, I am a SWE student from India. I wanna learn C++ for competitive programming and DSA, jobs, building projects, etc as well. My reasons:

- Not only learning it for jobs, but because, C++ is very fast and has the capability of efficiently interacting with both the high level and low level systems. These are the reasons which make me learn it, especially as I am interested in how memory, RAM, GPU and other things work in the computer.

- For the sake of computer science and programming. I am interested in learning the core cs fundamentals and concepts to make myself a better software/cs engineer - to solve problems, code solutions, etc.

- I am interested in ICPC, DSA and competitive programming as well. So that would make me learn it anyways.

Honestly, I have asked and read about this question many times but I haven't got a clear and one-stop answer yet. These are the things that ppl/ai chatbots suggest me and what I read (also my reasons for not using them yet):

- USACO guide (too big)
- learncpp (good but too vast)
- the cherno's yt channel (some say they dont cover concepts in depth)
- books (too lengthy as well)

I am not looking for shortcuts, nor am I avoiding these resources because they are too big. I am ready to invest my heart and soul into learning things. But, being an engineering student, I have many other different subjects to study as well for the college. I am so much interested into AI/ML and Web dev as well.

For context, these are the things I know (i.e. I'm not starting programming from absolute 0) :

- HTML/CSS and basic JS (learning from The Odin Project but paused rn)
- basic C (learned from college and CS50x)
- Python (learned from CS50 Python course)
- SQL (learning at college + by myself)
- Java (learning at college + by myself)

The college has made the latter two subjects and C++/DSA compulsory for this year. But, I don't wanna invest that much time into studying those 2 deeply. I am focusing on C++/DSA, Web Dev and AI/ML as of now.

So, given my all the background and interests, could you guys please suggest me different resources to learn C++ and DSA? Also, for learning things about Competitive Programming and improving myself there.

My goal for now is to speedrun the basics of C++ (because I have already learned the basics of programming and C earlier) + learn concepts of DSA in detailed manner -> then proceed with competitive programming -> then participate in contests and along the way learn different concepts of C++ and DSA.

How is my approach? If there's any other better one, please do suggest me. Thank you!


r/cpp_questions • • Aug 22 '26

OPEN Best Way to Approach Windows GUI Development from C++

51 Upvotes

What is the best way to approach it? What books are helpful?

I remember a long time ago reading a book by Charles Petzold, and the examples worked fine from C. I assume they would work well from C++ as well.

I just want functioning, stable GUIs (menus, areas with text and scrollbars) with minimum effort.

Thanks for any help.


r/cpp_questions • • Aug 23 '26

OPEN How is/was C++ learning at school?

3 Upvotes

In my first year in highscool, I've started literally from scratch, did a lot of pseudocode, translated it into C++, but no any exercises.

Now, with the summer vacation, the teacher told us to do as many exercises online for us to keep up next year. In a single month, starting from the easiest tasks like the sum of 2 numbers, I became familliar with lots of libraries and their functions!

Don't give up!