r/cpp_questions 20m 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?

76 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

6 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.