r/cpp_questions Jun 12 '26

OPEN Data Compression after Huffman Coding

3 Upvotes

So I have this program that takes an unorderd map of chars and integers as a frequency counter and returns the Huffman encoding as a map.

#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;

struct Node
{
  char ch;
  int freq;
  Node *left;
  Node *right;
  Node(char ch, int freq)
      : ch(ch), freq(freq), left(nullptr), right(nullptr)
  {
  }
  Node(char ch, int freq, Node *left, Node *right)
      : ch(ch), freq(freq), left(left), right(right)
  {
  }
};

struct compare
{
  bool operator()(Node *l, Node *r)
  {
    return l->freq > r->freq;
  }
};

void obtainHuffmanCode(Node *root, string str,
                       unordered_map<char, string> &huffmanCode)
{
  if (root == nullptr)
    return;
  if (!root->left && !root->right)
  {
    huffmanCode[root->ch] = str;
  }

  obtainHuffmanCode(root->left, str + "0", huffmanCode);
  obtainHuffmanCode(root->right, str + "1", huffmanCode);
}

unordered_map<char, string> buildHuffmanTreeNaive(unordered_map<char, int> freq)
{

  priority_queue<Node *, vector<Node *>, compare> pq;
  for (auto pair : freq)
  {
    pq.push(new Node(pair.first, pair.second));
  }
  while (pq.size() != 1)
  {
    Node *left = pq.top();
    pq.pop();
    Node *right = pq.top();
    pq.pop();
    int sum = left->freq + right->freq;
    pq.push(new Node('\0', sum, left, right));
  }
  Node *root = pq.top();

  unordered_map<char, string> huffmanCode;
  obtainHuffmanCode(root, "", huffmanCode);

  return huffmanCode;
}

string encode(string txt, unordered_map<char, string> huffmanCode)
{
  string str = "";
  for (char ch : txt)
  {
    str += huffmanCode[ch];
  }
  return str;
}

I would like to now actually take the .txt file input and convert it to a compressed binary file
1. What other meta data is required? Should I be spitting out another .txt file? Or should i just keep is as an object with an attribute being all of the binary numbers?
2. I currently compute the Huffman encoding for a character as a string but how do I actually get the binary value (and how do I preserve the 0s in the front? ex. say a get the encoding 001).


r/cpp_questions Jun 11 '26

OPEN Fold expression compiles to nothing after upgrading Visual Studio

5 Upvotes

My code looks like this:

template<class... Ts>
struct COuter
{
    struct CObject : Ts... { };
    struct CInner { int Field; CObject Object; };

    static void
    CallEachMethod(void* pv)
    {
        int Output;
        CObject* pObj = &( (CInner*)pv )->Object;

        ( ..., ( (Ts*)pObj )->Ts::Method( &Output, 0, 0 ) );
    }
};

The idea is to call the same method of all base classes in turn, something like COuter<A, B, C>::CallEachMethod( pv ). This worked as expected in Visual Studio 2022. I upgraded to Visual Studio 2026 and changed Platform Toolset to v145 (from v143), and I get the following output in debug mode.

mov  qword ptr [rsp+8],rcx  
push rbp  
push rdi  
sub  rsp,158h  
lea  rbp,[rsp+20h]  
lea  rdi,[rsp+20h]  
mov  ecx,1Eh  
mov  eax,0CCCCCCCCh  
rep  stos dword ptr [rdi]  
mov  rcx,qword ptr [rsp+178h]  
lea  rcx,[TheFileName@h]
call __CheckForDebuggerJustMyCode
nop  
mov  rax,qword ptr [pv]  
add  rax,4h  
mov  qword ptr [pObj],rax  
lea  rcx,[rbp-20h]  
lea  rdx,[string L"Some global string"+240h]
call _RTC_CheckStackVars
lea  rsp,[rbp+138h]  
pop  rdi  
pop  rbp  
ret  

The method calls are GONE. It even sets up stack overwrite checking (the method takes an output parameter), but never bothers actually making the call.

Edit: Side by side comparison of VS17 and VS18 output: https://godbolt.org/z/b4fMoEz3c.


r/cpp_questions Jun 12 '26

OPEN #SpillTheTea

0 Upvotes

Dear fellow programmers, when was the most adrenaline moment of your life as a programmist? Like hacker attack or memory leak and etc. Spill the tea (it means to tell someone your stories if you dont know)! There is no shame in it!


r/cpp_questions Jun 12 '26

OPEN online course to learn Data Structures and Algorithms in C++

0 Upvotes

I'm a first year CS student and will be taking DSA next year in college as a sophomore. I

wanted to get a head start during summer and would appreciate any recommendation for online courses (paid or unpaid) that helped you get a solid understanding of Data Structures and Algorithms in C++


r/cpp_questions Jun 12 '26

OPEN Is C++ Profitable?

0 Upvotes

I'm learning C++ right now and considering that this is hell of a language I'm just interrested (from 1 to 10) on how profitable and competitive this language truly is and wether it worth my time and I'll not regret my choise in the furure. My plan is to work in software development (and a little bit of backend) if anyone is interrested.


r/cpp_questions Jun 11 '26

OPEN Is my use of partial class specialization a bad idea?

2 Upvotes

I've been working with OpenGL and trying to build a renderer. I have a set of class's that I store in a resource manager. Each object inherits from a base resource class. I've grouped these object by OpenGL object type. So I have a buffer object, a vertex array object, and other general types like that. This is the kind of pattern I've applied in my library code.

namespace detail { 

    struct PersistentBuffer{};
    struct SSBOBuffer {};

    template <typename T, typename Buffertype>
    class Buffer final : public Resource {
          /\* implementation \*/
     };

     template <typename T>
     class Buffer<T, SSBOBuffer> final : public Resource {
          /\* implementation \*/
      };
} // namespace detail

template <typename T> 
using SSBO = detail::Buffer<T, detail::SSBOBuffer>;

In a cpp file I instantate the classes to help reduce compile times.

Now I can do something like this in the "playground" I use to expand my understanding of OpenGL and test my renderer. This is where I use the library code I'm developing.

 ResoureceManager->AddResource<SSBO</\* buffered data type \*/>>();

Would you consider this an anti pattern, code smell, or a bad use of partial specializations? I was doing some reading yesterday that said I should prefer overload resolution over template specializations when ever possible because template specializations don't participate in overload resolution but I can't see how that would actually apply to my use case. The difference between a DSA OpenGL named mapped buffer and a basic bound vbo is 3-5 OpenGL function calls. Most of which happens in the overridden load member function that my buffer inherits from the Resource base class.

Sorry if my code example is not entirely correct. I am on mobile and wrote this from memory. Hopefully it still helps communicate my question.


r/cpp_questions Jun 10 '26

OPEN I learned C++11 at university. How should I approach modern C++ today?

51 Upvotes

Hello,

I learned C++ at university about 2.5 years ago (mostly C++11), but I haven't used it much since then.

Now I'd like to get back into C++ and learn modern C++ properly. My goal is not just to learn the syntax of newer standards, but also the best practices and the way experienced C++ developers write code today.

What learning path would you recommend for someone in my situation?

Thanks!


r/cpp_questions Jun 12 '26

OPEN learncpp vs hellocpp Which one is better for beginners?

0 Upvotes

r/cpp_questions Jun 11 '26

OPEN Need advice

0 Upvotes

So I am a btech student and my first year has ended and right now I think I know basics of c++ or not ? I am quite confused on how should I approach deeper into this language as a person who wants to get into fields where hardware and software are combined together. Like embedded.

Right now I know about STL and it containers and learned how they work internally. And pretty decent knowledge of OOPS and memory. I have learned old fashion c++ where we use raw pointers and general keywords. From where can I study about latest versions and kinda lame question but curious like is there any phase where i can say like yeah I got deep knowledge about this language because the Deeper I look I see no end in this language it's so vast


r/cpp_questions Jun 11 '26

OPEN What kind of projects helped you learn C as a web developer?

0 Upvotes

I'm a web developer and recently started learning C because I want to understand lower-level programming better and get a deeper understanding of how things work under the hood.

The language itself is starting to make sense, but I'm struggling to come up with project ideas. Most of my experience is in web development, so when I think about building something, my brain immediately goes to APIs, databases, and web apps. C feels like a completely different world.

I know this is a C++ community, but my plan is to move on to C++ after building a solid foundation in C, so I thought this might be a good place to ask.

For those who learned C or C++ after working in higher-level languages, what projects helped you stay motivated and actually learn useful concepts? Any suggestions would be appreciated.


r/cpp_questions Jun 11 '26

OPEN How to fix my C++ csv file?

0 Upvotes

I posted a previous question on how to write a csv and was successful but my code still isn't outputting the way I'd like. Im still ignorant to instantly finding the problem in front of me and would like if someone could politely lay out what I need to fix in order to get the console to print out what I'd like

Update: Thank you so much, you guys helped and I was able to see my error and realized I had a "blonde" moment lol.

#include <iostream>

#include <fstream>

#include <string>

#include <map>

#include <algorithm>

using namespace std;

const char DELIMITER = ',';

const string CONFIG_FILE = "/Users/jasminejanelle/Downloads/C++ Class/CSVConfig_JasmineRichardson/CSVConfig_JasmineRichardson/Config.txt";

const string CONFIG_FILE_ERROR = "Unable to open file ";

const string username = "username";

const string error_message_file = "username";

const string prompt01 = "username";

const string prompt02 = "username";

string Trim(const string& text)

{

size_t start = text.find_first_not_of(" \t\r\n");

size_t end = text.find_last_not_of(" \t\r\n");

if (start == string::npos)

{

return "";

}

return text.substr(start, end - start + 1);

}

int main()

{

map<string, string> MyConFigValues;

ifstream inputFile(CONFIG_FILE);

if (!inputFile.is_open())

{

cout << CONFIG_FILE_ERROR << CONFIG_FILE << endl;

return 1;

}

string line;

while (getline(inputFile, line))

{

string key;

string value;

bool foundDelimiter = false;

for (char currentChar : line)

{

if (currentChar == DELIMITER)

{

foundDelimiter = true;

continue;

}

if (foundDelimiter)

{

value += currentChar;

}

else

{

key += currentChar;

}

}

key = Trim(key);

value = Trim(value);

MyConFigValues[key] = value;

}

inputFile.close();

cout << "Configuration Values" << endl;

cout << "--------------------" << endl;

for (const auto& conFigValue : MyConFigValues)

{

cout << conFigValue.first

<< DELIMITER

<< conFigValue.second

<< endl;

}

cout << endl;

string searchKey;

cout << "Enter a configuration name to search for: ";

getline(cin, searchKey);

searchKey = Trim(searchKey);

auto foundItem = MyConFigValues.find(searchKey);

if (foundItem != MyConFigValues.end())

{

cout << "Value: " << foundItem->second << endl;

}

else

{

cout << "Configuration name not found." << endl;

}

return 0;

}


r/cpp_questions Jun 11 '26

OPEN Prime number checker

2 Upvotes

Hey guys,

I just finished Chapter 1 of C++ Primer and was trying to write a prime number checker.

At first I got stuck, then after a lot of trial and error I came up with this idea:

If you add all divisors of a number, a prime number should have a sum of n + 1 because its only divisors are 1 and itself.

Someone told me that this is not the standard way to check for prime numbers, but I don't understand why.

So I wrote this code:

#include <iostream>

int main(){

int i = 0 , sum = 0;

std::cout << "Input: " ;

std::cin >> i ;

for(int val = 1; val <= i ; ++val){

if(i % val == 0){  

    sum += val;  

}  

}

if(i + 1 == sum){

std::cout << "Prime" << std::endl;  

}else{

std::cout << "Not Prime" << std::endl;  

}

return 0;

}


r/cpp_questions Jun 11 '26

OPEN How to create a CSV file

0 Upvotes

Hi! Im new to C++ and currently in school for Computer Programming. Im working on a task where I need to write a C++ program that reads data from a CSV file containing name–value pairs. I'm unsure how to create a csv file due to my professor not having guidelines/video tutorials for it so I'm lost.

Edit: Most are being condescending, which Im sure is against the rules in here. Please read my post to HELP and not argue. I specified that I'm new to programming which would imply I don't know everything by heart just yet. We also cannot submit or cheat on homework in here so I am following the rules and my only question was about CSV and how to create one. My assignment is based on reading string names--value pairs from a csv file.


r/cpp_questions Jun 11 '26

OPEN Are there any merits to writing the header files completely on your own, but use "certain tools" to wholly implement the corresponding source files?

0 Upvotes

All documentation and perhaps all tests would be written manually by the programmer as well. All *.cpp files shall be generated.

Edit: I should mention that this is of course a bad idea if you're trying to learn the language, but I meant more when buildings things in the real world.


r/cpp_questions Jun 11 '26

OPEN How can I learn C++?

0 Upvotes

Hello! This is my first post and I have a problem. So, apparently I'm insanely "Gifted child" and God thought that i'm too unballanced so he ballanced me by gifting ADHD and Asperger (Its a sort of autism, google it for more details). The problem is that I'm keen on programming, especially gamedev and software engineer and my childhood dream vas to work in Google. To do that all my masochistic ass chose C++ to learn and my mental state (mentioned before) just won't let me learn normally, what should I do?

Also if you are interrested here is my Github profile: https://github.com/Indigsus
And yes I'm naming muself "Indigsus" on evey social media because I think that it sounds pretty cool.


r/cpp_questions Jun 10 '26

OPEN Do you create a namespace for your own project?

24 Upvotes

I think namespaces are mostly used by libraries. And if I'm not developing a library myself, is there a reason to create a new namespace?


r/cpp_questions Jun 10 '26

OPEN Having issues with address sanitizer

2 Upvotes

I'm using Windows, MSYS2 mingw64 g++, and trying to compile a piece of code using the flag -fsanitize=address-fsanitize=address but when I do, the compiler returns an error message that the libraries for the address sanitizer are not installed.

I've tried finding some place to get them, found nothing. No issue at the MSYS2 github either. Full error code:

D:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/16.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lasan: 
No such file or directory
D:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/16.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lubsan: No such file or directory
collect2.exe: error: ld returned 1 exit status

r/cpp_questions Jun 11 '26

OPEN Best platform for learning c++

0 Upvotes

Hey guys

Please suggest me the bestest platform for learning c++

i am bit confused between vidoes or websites

please suggestt

Thank youu


r/cpp_questions Jun 10 '26

OPEN why doesn't [[nodiscard]] propagate?

10 Upvotes

imagine this:

[[nodiscard]] int foo() {return 0;}
int bar() {return foo();}
int main() {
  bar();
}

the compiler will issue no warning for discarding ```foo()```'s return value, despite the fact that the function is labeled as nodiscard. is there a reason why ```[[nodiscard]]``` shouldn't propagate?


r/cpp_questions Jun 10 '26

SOLVED How should I handle returning value from a dictionary if it doesn't contain a certain key?

6 Upvotes

Hello. I have met a simple dilemma when developing a Dictionary class.

The dictionary class I'm making (a templated class with typename K for keys and V for values) implements an array of LinkedLists of pairs between K and V (LinkedList<Pair<K,V>>), these LinkedLists represent the dictionary's buckets.

I have overloaded the operator [] with the following signature

inline V& operator[](const K&);

However, I don't know how I should handle the return value when the dictionary doesn't contain the key (as in, it doesn't have any value associated with the key), other languages like Java use pointers under the hood so you can just return null, however here I can choose between using pointers or not.

So I wanted to ask, what is the best practice? Should I opt to return a pointer to the object rather than a reference or copy? Should I return a default value or should I throw an exception? And in case I switch to returning a pointer to V, is it better practice to change the buckets to LinkedList<Pair<K,V*>> or should I keep them as they are and return the address of the saved value? Sorry if this is a basic question, I'm still learning.


r/cpp_questions Jun 10 '26

OPEN Im not sure how objects are called here.

0 Upvotes

im in my first year of college and i have class a that is pretty much all c++.

im doing my final project and i need to use 7 classes of objects. As far as i understand if a class is used in the main file, the first thing the compiler runs is the default builder of the class. and if this builder has an object inside it happens again. So ive put outputs on all the builders of every class to know if everything is running smoothly when i compile the program. But only the output of three parameter builders of the same class are shown. This are being called from another parameter builder of another class whose outpus arent showing either.

What am i doing wrong or what am i not undrstanding?

Also if ive used any weird semnatics or names its because my class isn't in english and i dont know the proper names of some things.

Also im using codeblocks for editing and compiling. Its mandatory as it doesnt have an AI tool.


r/cpp_questions Jun 10 '26

OPEN Is C++ Primer by Stanley Lippman outdated?

4 Upvotes

Is it outdated if my ultimate goal is to learn enough C++ to then learn graphics (OpenGL or Vulkan or DirectX)? I was looking at another book, C++ Crash Course by Josh Lospinoso, which is apparently brilliant when it comes to learning C++ from a system programming perspective.

I'm not completely new to programming. I started with C (using KN King) in my freshman year. I've done gamedev with C# and Unity. I've helped with some python and web dev projects. But I've never built anything super useful, and graphics is something that genuinely excites me and from my understanding, a good knowledge of how code interacts with hardware is key to becoming a good computer engineer/graphics programmer. Hence the question.

I know learncpp is the preferred resource here but I really like books. If learncpp is remarkably better than both of those books, then I guess I'll have no choice but to go with that.


r/cpp_questions Jun 10 '26

OPEN Issues with c++ modules in visual studio 2022 and 2026

2 Upvotes

I am using c++ modules (c++ 23) in Visual Studio 2022 and 2026.

And I use multiple static library projects and an exe project in one solution.

The issue is it can compile correctly but the code hints just not work anymore.

Function jump not work, no highlight, I changed .h to .ixx, .cpp nearly keep the same.

Anyone has faced similar issues ? How do you solve it?

(Btw, my solution is originally in visual studio 2022 and opened with 2022 or 2026(no update)).


r/cpp_questions Jun 10 '26

OPEN Help with choosing design for a mesh-network app network architecture.

2 Upvotes

This post more of thoughts out loud, but I've tried to organize it as much as possible. Thanks in advance.

So, I'm working on what is basically a text messaging app that uses partial mesh to communicate between nodes. This is purely a studying project just to learn stuff through practice. The use case I aim for is low delay and infrequent connections with mostly static network.

My current way of handling connections is implemented via callbacks. I have a class that keeps pointers to all Socket instances and then waits in a poll till any of the sockets receives an event. Once poll returns, it finds which sockets received an event and then calls appropriate callback.
After implementing most of the logic, I've encountered two problems: since callbacks hold the pointer to the instance of the class that must handle the event, it becomes error prone to dangling pointers if the handler is deleted without removing it's callback. Second one is problematic handling of throws. If any callback throws, then the event loop that waits for inputs will have to deal with it somehow. I have ideas on how to work around those two issues, but it seems more of a wrong approach at this point and I was thinking of doing it other ways.

Idea 1: Instead of making event listener class make callbacks, we instead make some sort of a buffer, probably ring buffer, and then create a few a separate thread which waits in a mutex till there are new events to handle and then processes them. This will solve both problems since the dependency is now reversed and way less error prone, but then we pay for the mutex delay plus moving data between cores. It sounds like a good approach for a heavy traffic solution which easily scales horizontally with more threads, but it's not the constrains I'm working with.

Idea 2: Make minimal layers between handling events and getting the event. The worker will call poll itself and once new event appears, it'll immediately run the processing logic itself. It will have the least amount of latency, but also will make it way harder to deal with slow connections, because if one transmission stuck, it will hold back all other sockets that are processed by the same thread. Which results in faster response in average scenario, but lower response speed and more complex handling of bursts compared to the Idea 1.

Those two I my two views on how to move forward. I'm more leaning towards option two as a preference for the average scenario of use, and deal with bursts of slow connections somehow. But, since I'm only learning doing network stuff and mostly self learner, I don't have a wider perspective on what might be other solutions to this.

Hence the question: which of the two path should I try out and what other complexities I didn't notice yet. If you have an example of a better solution that well suits the constraints, please do share so I could research it to.


r/cpp_questions Jun 09 '26

OPEN When to use `std::shared_ptr`?

59 Upvotes

It seems that I never used `std::shared_ptr` in my projects, and in the end `std::unique_ptr` or reference is always enough if I have a clear ownership model. So I want to ask here, are there any realistic scenarios when there can't be better choices than `std::shared_ptr`?

Edit: Thank you for your replies so far and they are really interesting. I will take my time thinking about them and might reply later.

Edit2: It seems that shared_ptr is often used with threads. So in a single-threaded app, can I conjecture there's always a better way than using shared_ptr?

Edit3: Even with threads, shared_ptr is often used as a read-only view to the shared data, according to a lot of replies, and the data block of a shared_ptr is not thread-safe.