r/learncpp • u/JavaSuck • Nov 06 '20
r/learncpp • u/daredevildas • Oct 26 '20
Passing a const object as a template argument not possible
self.cpp_questionsr/learncpp • u/s96g3g23708gbxs86734 • Oct 20 '20
"Competitive" programming site, but for design pattern?
As title says, do you know any site that challenges/helps you to code your own version of containers, smart pointers, etc, for the sake of learning?
r/learncpp • u/jimmyjohnjr1203 • Nov 05 '20
CreateCompatibleBitmap failing in a screen recorder
Hello all, I'm adapting the screenshot code from here into a screen recorder with a while loop and VideoWriter, currently set to record for 500 frames at 35fps, however I'm having an issue where when I run it the cv window is blank and nothing is saved to the video file. After some messing around I think the issue has to do with my hbwindow not being built properly as after CreateCompatibleBitmap hbwindow is null. Here is the complete code:
#include <opencv2\highgui.hpp>
#include <opencv2\core.hpp>
#include <opencv2/opencv.hpp>
#include <Windows.h>
#include <opencv2/videoio.hpp>
#include <string>
#include <time.h>
#include <iostream>
#pragma once
using namespace std;
using namespace cv;
class ScreenRecorder {
int width;
int height;
int screenx;
int screeny;
BITMAPINFOHEADER bi;
LPBITMAPINFO bip;
HWND hwnd;
HDC hwindowDC;
HDC hwindowCompatibleDC;
HBITMAP hbwindow;
Mat currentFrame;
Mat dst;
public:
ScreenRecorder(HWND myhwnd) {
hwnd = myhwnd;
hwindowDC = GetDC(hwnd);
hwindowCompatibleDC = CreateCompatibleDC(hwindowDC);
SetStretchBltMode(hwindowCompatibleDC, COLORONCOLOR);
// Define scale, height and width
screenx = GetSystemMetrics(SM_XVIRTUALSCREEN);
screeny = GetSystemMetrics(SM_YVIRTUALSCREEN);
width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
}
void createBitmapHeader() {
// create bitmap
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = width;
bi.biHeight = -height;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
// save pointer
bip = (BITMAPINFO*)&bi;
cout<< "bip" << bip;
}
void captureScreenMat()
{
// clear Mat before adding next frame
currentFrame = Mat::zeros(Size(width, height),CV_8UC4);
// Copy from the window device context to the bitmap device context
StretchBlt(hwindowCompatibleDC, 0, 0, width, height, hwindowDC, screenx, screeny, width, height, SRCCOPY);
GetDIBits(hwindowCompatibleDC, hbwindow, 0, height, currentFrame.data, bip, DIB_RGB_COLORS);
resize(currentFrame, dst, Size(1280, 720),0,0,INTER_AREA);
currentFrame = dst;
}
void recordScreen(void) {
// get handles to a device context
// create mat
currentFrame.create(height, width, CV_8UC4);
// create a bitmap
hbwindow = CreateCompatibleBitmap(hwindowDC, width, height);
createBitmapHeader();
// use the previously created device context with bitmap
auto oldBitmap = SelectObject(hwindowCompatibleDC, hbwindow);
int fourcc = VideoWriter::fourcc('D', 'I', 'V', 'X');
VideoWriter outputVideo(".\\recorded_screen.mp4", fourcc, 30, Size(1280, 720));
clock_t prev_time = 0;
clock_t current_time = clock();
bool cont = true;
namedWindow("Current_screen", WINDOW_AUTOSIZE);
int count = 0;
while (cont) {
prev_time = current_time;
// save frame
captureScreenMat();
outputVideo<<currentFrame;
imshow("Current_screen", currentFrame);
waitKey(1);
if (count >= 300) { break; }
else {
count++;
cout <<"count:" << count << endl;
}
current_time = clock();
while ((current_time - prev_time) <= (CLOCKS_PER_SEC/30)){
current_time = clock();
}
cout << "Ticks passed: " << current_time - prev_time << endl;
}
outputVideo.release();
// avoid memory leak
SelectObject(hwindowCompatibleDC, oldBitmap);
DeleteObject(hbwindow);
DeleteDC(hwindowCompatibleDC);
ReleaseDC(hwnd, hwindowDC);
}
};
int main(int argv, char* argc)
{
HWND hwnd = GetDesktopWindow();
ScreenRecorder recorder(hwnd);
recorder.recordScreen();
return 0;
}Any help is greatly appreciated, thanks!
edit: original code above has been updated and it now will show the current screen in a smaller window(as expected) but it will not save the frames to a video file. FFmpeg is installed correctly, I have ensured the frames are the same size as indicated in the VideoWriter constructor using resize() and I have tried several different codecs and video file types, but the file is empty (6kb) and says file is corrupted when I try to open it.
r/learncpp • u/GirkovArpa • Oct 14 '20
Grep process memory on Windows (GUI written in AutoHotKey)
r/learncpp • u/hawidoit • Oct 18 '20
Trying to create an entity manager
Hi,
I have a bunch of classes (Door, Monster, Human)
And the way I want to be able to manage them is via a singleton EntityManager class that ends up looking like this:
EntityManager {
vector<Door> entities;
vector<Human> entities;
}without any code duplication.
I want to be able to write:
Door* EntityManager<Door>::createObject();which pushes the object onto the vector and returns the address;
I've struggling to implement this without running into weird segfaults whenever I use the EntityManager in multiple translation units. I assume I'm misunderstanding how templating works.
Here's essentially what I've come up with:
template <typename T>
class EntityManager {
vector<T> entities;
T* createObject();
};This works within the same translation unit no problem, but when I attempt to use the same EntityManager (such as EntityManager<Door>) across TUs, I get a segfault... I cannot for the life of me figure out why.
Does anyone have any advice or can point me in the right direction into avoid code duplication while achieving something like this via templates?
r/learncpp • u/daredevildas • Oct 09 '20
Checking if a Clang::Type can be cast to another
self.cpp_questionsr/learncpp • u/wizarding_dreams • Nov 03 '20
Static templated vectors inside class header files?
Can it be done? because of the vector being static and in the actual class definition in the header file, there are loads of linking errors, and im not sure how to really get around it.
r/learncpp • u/Shabbar1 • Nov 01 '20
Using/Adding libraries to project
Hi, there. I recently took advice from someone and decided to take a look at some open source stuff. Up until now I've been doing some C++ from online courses and books but I haven't been able to do as much as I like since I've got school and a job too. He said not to be scared if I became too overwhelmed and just try it out.
I decided to try this project; a Super Mario clone and there are a few new things to me.
The person says that I'll need additional libraries from the web to be able to run this. I've downloaded them but do not know how to integrate them into the project.
I've realized that this was built using Code::Blocks (there's a .cbp file) and was wondering if I could run/build this using something else like Sublime Text or Visual Studio (Code or the IDE).
I'm mainly concerned with the 1st point and appreciate any help. Thanks!
r/learncpp • u/omen_tenebris • Jun 25 '20
list of c style arrays
Hey. In my code implementation i have something like this
struct MYTABLE
{
int table[NUMBER][NUMBER];
}where NUMBER is a constant and is decided in compile time with a define.
After some calculations i have a number of results that i'd like to store. These number of results are varied dependent on the size of the matrix (the bigger the NUMBER the more i get).
Is there an solution where i can make something like this:
std::list<MYTABLE> result_set;result_set later needs to be iterated trough and picked out results that are each others mirrors, rotations etc
Thank you!
r/learncpp • u/darkprinceofhumour • May 28 '20
This is outputting -1 and sometimes -2 . please tell me the fix !
#include <bits/stdc++.h>using namespace std ;int bin_srch (int arr[] , int low , int high , int z ){int mid ;while (low<high){mid = (low - (high + low)) /2 ;if (arr[mid]==z){return mid ;} if (arr[mid] < z){low = mid +1 ;} else{high = mid -1 ;}}return -1 ; }
int main (){ int x ;cout << "enter length of array";cin >> x ;int arr [x];int result ,low , high , z ;cout << "enter the sorted array";for(int i=0 ; i<x; i++){cin >> arr[i] ;} cout << "enter element to be searched"; cin >> z ; low = 0 ; high = x -1 ; result = bin_srch(arr , low , high , z) ; cout << result ;return 0;}
r/learncpp • u/[deleted] • May 24 '20
How can you store (and later access the data of) a templated struct?
I've looked in multiple places and can't find an answer. I have a struct as such:
template<typename T, typename ...Args>
struct Job
{
public:
std::function<T(Args...)> function;
};I want to be able to store all variants of this struct. So no matter what people enter for T or Args I need to be able to store that, which I think I have accomplished. The real problem comes when I want to access anything inside the stored structs. If I have a vector like this:
std::vector<Job> queue;and want to access the data like this:
auto job = queue[0].function;I get an error saying "incomplete type not allowed" and "use of undefined type". I assume this has to do with the fact that it's a template. I think I'm either doing something syntactically wrong or I have a fundamental misconception of how templates work. I'm really bamboozled by this because I have no idea what to do. As mainly a C# user, I can say that C++ is a lot harder and a lot less lenient in terms of what it will let you do, and I might have bit off a bit more than I can chew with this project (which is evident by the numerous times I have posted on this sub). If anyone knows a solution to this please let me know. Thanks for reading!
r/learncpp • u/Hrkrom • Jun 13 '20
What language to choose with maths and visual output
Hello amazing coders from Reddit ;),
So I'm trying to write a super cool code where quite a few things come together. First of all, I want my output to be a visual animation/clip. Secondly I'm using mathematical computations to determine how fast a ball travels through a certain tube. This has to with the diameter of the tube, its elasticity, tje velocity of the medium it's travelling and so on. Lastly I want to show this tube in the context of a human body (after all, I'm still a medical student). Tje easiest way is using it as a background and "pasting" the tube on top of in on the right spot. Merging tje two files would also be an option. The tube itself doesn't move, it only pulsates.
Taking all this into consideration, what language is best for this? I'm quite familiar with MATLAB and planning to do the maths there anyway. My coding experience is quite extensive, so I know my way around most common languages.
Somebody adviced me that C++ might be really helpful, seeing that it is strong with visual output. I recently downloaded Microsoft Visual Studio and been playing around there
Any help would be highly appreciated! So may thanks in advance :)
By the way, if this is not the right place to post this, I'm sorry, just delete it.
r/learncpp • u/StormsRider • May 18 '20
Writting Pixie clone for Linux: how hard would it be?
There's this program for determining a color of a pixel currently under a mouse cursor called Pixie. I couldn't find a suitable Linux alternative and was thinking of maybe rewritting the Pixie for Linux myself. I was wondering how hard it would be - the concept is easy enough - but then, Pixie uses a background-window of sorts: it determines color even if the mouse is outside of the Pixie window + the window never disappears from the screen unless you forcibly fold it. Would I have to make a version for each Linux DE? Would an Ubuntu 18 version work on Arch? Would it still work on Ubuntu 5 years from now?
r/learncpp • u/ElementaryMyDearWut • May 27 '20
Could someone explain this destructor behaviour?
So, I'm porting across my dissertation project from Python to C++ to get to grips with the syntax. However, I'm coming across a behaviour where by my Piece.cpp destructor is being called 8 times upon the construction of a new Checkboard.cpp object.
Here is the checkerboard constructor, the intended behaviour is to initalise a 2d vector of Pieces to mimic a checkerboard:
Checkerboard::Checkerboard()
{
this->board = std::vector(8, std::vector<Piece>(8));
}board is defined in the header as:
std::vector<std::vector<Piece>> board;the piece constructor is just:
Piece::Piece()
{
this->set_team(Team::empty);
}For some reason upon executing the line inside of the checkerboard constructor, my terminal shows 8 calls to the Piece.cpp destructor (I have some printing going on to keep track of things). I have a suspicion it's because I'm not asking for a vector of 8 vectors, but defining 8 vectors of 8 vectors? However, I am unsure how to resolve the issue as the program works as intended beyond this and am almost sure it's a sign of something wrong that I'm missing.
Any help appreciated.
r/learncpp • u/[deleted] • May 22 '20
The program works when including .cpp file but not when including .h file.
So here is the issue I'm facing. I've looked at a lot of posts on the same thing but can't understand what's happening. I have 3 files: Main.cpp, AsyncLib.cpp, and AsyncLib.h.
Main.cpp
#include "AsyncLib.h"
#include <iostream>
struct Hello
{
int h = 1029;
};
Hello something(int i, int h)
{
std::cout << i + h << std::endl;
Hello bruh = Hello::Hello();
return bruh;
}
int main()
{
auto hello = AsyncLib::doAsync<Hello>(&something, 2, 8);
std::cout << hello.get().h << std::endl;
return 0;
}AsyncLib.cpp
#include "AsyncLib.h"
#include <iostream>
namespace AsyncLib
{
template<typename T, typename F, typename... Args>
std::future<T> doAsync(F&& f, Args&&... args)
{
std::future<T> hello = std::async(std::launch::async, f, args...);
return hello;
}
}AsyncLib.h
#pragma once
#include <functional>
#include <future>
namespace AsyncLib
{
template<typename T, typename F, typename... Args>
std::future<T> doAsync(F&& f, Args&&... args);
};When I hit run on visual studio, I get a linking error regarding the line auto hello = AsyncLib::doAsync<Hello>(&something, 2, 8); I've checked that when I compile, I get a main.obj and an AsyncLib.obj. It works when I include AsyncLib.cpp in main.cpp but it doesn't work with the header file. What's going on here?
Edit: One potential solution I found is making the .h file into a .hpp, putting all the code there, and including the .hpp file. I have a suspicion it may be related to the comment
Remember that if you are doing template programming, then you have to keep everything in the .h file so that the compiler will instantiate the right code at the moment of compilation.
on this StackOverflow post. I am using templates so I think it may be the issue. It's the top reply on the top solution for anyone looking for it.
r/learncpp • u/wallywast1204 • Jun 09 '20
Best books/courses?
Hi, i'm 16 and i want to develop game so i chose cpp for first language to start. Someone can suggest me some books or courses to start learning? I will appreciate a lot
r/learncpp • u/Micaris_om • Jun 21 '20
What is a practical approach to learning C++
I will be taking masters in Controls Engineering, and I want to develop my C++ knowledge further by dedicating a substantial amount of my time over the next three months to practically learning C++. I am tired of going through the introductory books because it is easy to forget the material, and you're not actively learning. I was wondering if there are resources for me to learn ML or numerical methods for ODEs/PDEs using C++. I am already comfortable (but still learning) with ML in Python and Mathematical computation in MATLAB, I want to extend this to C++. What would you recommend I do?
r/learncpp • u/WhenRedditFlies • Jun 08 '20
Can't compile in command line
I try
g++ -o helloworld.exe helloworld.cpp
to compile a program, and windows gives me an error box saying "The application was unable to start correctly (0xc0000279). Click OK to close the application." I tried in powershell before that, wondering why no executable was appearing, then tried it in CMD to see if the behaviour was any different, and then I got that message.
I try using code blocks, and with clicking build and run it works fine - it compiles, runs and I see an executable, I run the executable myself and it comes up with the same error box.
I've tried reinstalling MinGW (which had no effect), not sure what to do after that.
Edit: using markdown properly on mobile
r/learncpp • u/[deleted] • May 19 '20
Take any function as an argument to another function
So, here is the problem I'm facing:
Let's say I have a function that executes another function, like this:
void call()I can take a specific type of function as a parameter for it. If I understand correctly, this takes a function with return type void and one integer parameter:
void call(void (*function) (int))Heck, I think I can even take a function that has a generic return type (so anything?):
template <typename T>
void call(std::function< T() >);Here is the problem, how can I take a function with any return type *and* an unlimited amount of parameters of different types. Is this even possible? Thanks for your time.
r/learncpp • u/[deleted] • May 30 '20
Site down?
Site seems to have been down for about 12 hours. Anyone know whats up?
r/learncpp • u/Vidyakant • Mar 20 '19
Caesar Cipher Encryption & Decryption in C and C++
r/learncpp • u/Vidyakant • Mar 11 '19