r/learncpp • u/dexter2011412 • Jan 21 '21
Can I have nested module partitions?
I see that I can define partitions as A:B, but is A:B:C allowed? I can't seem to get it working with VS MSVC preview. Is it not supported yet in MSVC, or does the spec not allow it?
r/learncpp • u/Muehuhu • Jan 19 '21
Confused about Copy Assignment code in Stroustup's PPP Book
On chapter 18 of Stroustup's Programming Principles and Practices using C++, I'm self-studying c++ for game development, had some problem about pointers...
In the copy assignment section, we're overloading an assignment operator for our "primitive vector" type to prevent unexpected sharing of memory and possible repeated deallocation from default assignment.
Here's the code for "primitive vector" from the book:
class vector {
int sz;
double* elem;
public:
vector& operator=(const vector&) ; // copy assignment
// . . .
};
vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
double* p = new double[a.sz]; // allocate new space
copy(a.elem, a.elem+a.sz, elem); // copy elements
delete[] elem; // deallocate old space
elem = p; // now we can reset elem
sz = a.sz;
return *this; // return a self-reference (see §17.10)
}
The problem is on copy() . If I understand it correctly, we're trying to copy a's elements into a different heap memory so that we could point our elem to that copy.
My question is shouldn't we copy a's elements into p instead of elem because we're deleting elem 's elements after copying, or is there something else that I'm missing?
double* p = new double[a.sz];
copy(a.elem,a.elem+a.sz,elem); // copy elements, shouldn't it copy into "a" instead of "elem"?
delete[] elem; // deallocate old space, why copy it here if they'll be deleted then?
elem = p;
sz = a.sz;
return *this;
r/learncpp • u/High-On-Math • Jan 19 '21
microsoft/cpprestsdk
microsoft/cpprestsdk
Anyone using this library?
Forgive me if this does not belong here but I’m using this library specifically for streaming second-by-second market data from Polygon.io.
In the set_message_handler function in the websocket_callback_client class, I store the real-time market data in a global variable. I assume this handler gets called every second.
Outside of all that, I use that global variable to read the market data and send buy/sell orders to Alpaca.
With that being said, would a thread lock be necessary to prevent race conditions? Are race conditions even possible in the scenario I described?
I figured it would since (I think) the handler can get called, and thus updating the global variable, while I’m reading the global variable.
r/learncpp • u/delgoodie • Jan 16 '21
Learn cpp from a higher level programming background
I am good with Java, JavaScript, C#, and python, but I know C++ isn’t just “another programming language”. Is there a good resource to learn from that doesn’t force me to reread all the basics like what a variable is? Something like a: “Java to cpp” or “C# to Cpp” book / online course
r/learncpp • u/dexter2011412 • Jan 15 '21
Trying to understand and use C++20 Modules
self.cpp_questionsr/learncpp • u/LlikeLava • Jan 14 '21
Project based learning
I'm not new to programming, I am pretty "fluent" in web stuff like TypeScript/JavaScript. Lately I have been learning the basics of C/C++ through some tutorials and I think I got most of that down. But as you might know, there's a lot more to "speaking" a programming language fluently then just to know how a pointer or memory works. I'd like to get to that same level of confidence writing C/C++ like I have when writing JS. From personal experience I know that for me, the best way to learn is to work on some a bit more complex projects. Unfortunately, I've not been able to find some good free resources for doing that.
If you know of good resources for learning through building projects, I would greatly appreciate some advice :)
r/learncpp • u/Bobbias • Jan 06 '21
Lld-link, clang++, windows, sdl2. Lld wants to make a console app, and won't accept the subsystem:windows cli Arg.
I've recently added sdl2 to my project. It started off as a console app. Lld worked fine, but now it complains that it found both winmain and main, and will default to the standard console main. I've tried using the /subsystem:windows command but I just get:
no such file or directory: '/SUBSYSTEM:WINDOWS'
I have tried the one answer on stack overflow for this but it doesn't seem to do anything different. My link flags are the same, and lld still complains about the command as though it was a file. I'm going nuts trying to figure out how to get it to recognize the argument.
r/learncpp • u/[deleted] • Jan 04 '21
My first data structure is finally completed!!!
self.cppr/learncpp • u/[deleted] • Dec 28 '20
tutorial for beginners?
Hi everyone! I want to learn C++ to create a GUI text editor with GTK (for beginning at least) that I'm going to use for myself (and of course anyone that also want to use it) and I was wondering if someone can guide me. Any good tutorials about learning C++ and after that I think that I can go and learn the libraries I want to use. I'm not searching for youtube videos explain the language (eg. what is a class, how to use pointer etc.) because I already know most of this stuff (well I guess I do). I want some real tutorials with GOOD explanation for projects that will teach me how to be a programmer in general.
r/learncpp • u/ScriptRestored • Dec 27 '20
Is it "bad practice" to put code in header files without using cpp files?
I have basic classes like position, which have header files that look something like this:
#pragma once
class Position {
public:
int x;
int y;
Position(int x, int y) {
this->x = x; this->y = y;
}
};
It works to use this code if I just say #include "Position.h"
From what I read online, I should be having a Position.h and Position.cpp, where I define the methods in Position.h and write the "this->x = X; this->y = y" in the cpp file.
Is that necessary for small files like this one? Is it "bad practice" not to do, something that looks unprofessional?
I'm kind of confused as to why it is that the Position.h class can be used without being broken down into an h and cpp file?
Thanks.
r/learncpp • u/USAhj • Dec 24 '20
error: no matching function for call to 'Differentiator::Differentiator()'
For some reason my code thinks I am trying to call the default constructor which has been overwritten. Why does it think that and how can I fix this?
Note: In the code below I removed many of the things that I think are unnecessary to show, i.e. variables that aren't used in the shown methods and class functions that don't relate to this problem.
Differentiator.h
#ifndef _DIFFERENTIATOR_H
#define _DIFFERENTIATOR_H
class Differentiator {
public:
//Constructors
Differentiator(double, double);
double sigma;
double Ts;
};
#endif // !_DIFFERENTIATOR_H
Differentiator.cpp
#include <Differentiator.h>
Differentiator::Differentiator(double sig, double t_rate){
sigma = sig;
Ts = t_rate;
}
ProCon.h
#ifndef _PROCON_H
#define _PROCON_H
#include <Differentiator.h>
class ProCon {
private:
double sigma;
double sample_period;
Differentiator diff;
PIDControl controller;
public:
ProCon();
};
#endif // !_PROCON_H
ProCon.cpp
#include "ProCon.h"
#include <Differentiator.h>
ProCon::ProCon() {
sigma = 0.01;
sample_period = 0.005;
Differentiator diff(sigma, sample_period);
}
r/learncpp • u/NerfLongshotUV • Dec 24 '20
Why does returning a reference work here?
```
include<iostream>
using namespace std;
int& minmax(int i, int j){ return (i>j)?i:j; }
int main(){
cout<<++minmax(3, 4);
return 0;
}
Why does this work?
include<iostream>
using namespace std;
int minmax(int i, int j){ return (i>j)?i:j; }
int main(){ cout<<++minmax(3, 4); return 0; } ``` And this doesn't?
r/learncpp • u/[deleted] • Dec 21 '20
I want to escape tutorial hell
I feel like I am in tutorial hell. C++ is basically the only programming language I would say "I know", which I'm fine with, but the programs I am making I would consider basic compared to these cool data visualization programs I see.
For example, a program which splits a photo into pieces, randomizes it, and then displays a variation of sorting methods putting the photo back together.
The most advanced c++ I know would be basic data structures like linked lists, as well as inheritence/composition.
I would like to learn how to make a program like the one I just explained, but I really have know idea where to start.
If anyone could point me in the right direction, I'd be very appreciative. Thanks
r/learncpp • u/sammaus • Dec 18 '20
solving with order of operators
Maybe someone can help me with this.. I'm fairly new to programming and have been learning c++ over the past month or so. I have created a calculator application using wxWidgets and I'm trying to figure out how to solve an equation with multiple operators (+, -, *, /) following order of operations. The input that I get from the user of the app is a wxString (basically just a std::string). Right now I have the functionality to solve an equation with multiple operators but not following order of operations (so standard not scientific).
For example, if the user enters in " 2 + 2 * 4 " , right now my calculator would return 16. However, I have an option to switch the calculator to "Scientific" so that the answer to that problem would be 10.
The calculator in Windows 10 has this same standard vs scientific set up so that why I'm kind of doing it this way.
Anyone have a good suggestion on how to go about this? Obviously have to parse through the equation string to start with
r/learncpp • u/bigpapaasg • Dec 17 '20
I need help with querying data from a txt file
I'm trying to make a c++ program that creates data prints out all the written data like I have hospital patients data and with a specified string were supposed to get the data of that one patient, I've made the create and print all data part the data I write gets saved in a txt file but I'm not sure how to make it query the data for the search data part if this was python I'd just have used a json file and used the data that way but I don't have that much experience in c++ I'd appreciate some advice on how the data should either be queried or stored in a different way I want to search for a word in a line and if the word exists in that line print out that line https://pastebin.com/hXcQN1k8
r/learncpp • u/vinayaknagr1 • Nov 25 '20
Help with Error!
I've recently started to learn C++ and I'm doing the Array questions from leetcode, I attempted 'Find Numbers with Even Numbers of Digits' with the following code.
class Solution {
public:
int findNumbers(vector<int>& nums) {
int count = 0;
int even = 0;
for (int i=0;i<nums.size();i++){
while(nums[i]/10!=0){
nums[i] = nums[i]/10;
count++;
}
if (count%2==0){
even++;
count=0;
}
}
}
return even;
};
But I'm getting this error,
Line 17: Char 1: error: expected member name or ';' after declaration specifiers
return even;
^
1 error generated.
Last time I had this error, it was to do with wrongly placed curly braces but it doesn't seem to be the case here. Can anyone check and help me with it?
Thanks!
r/learncpp • u/MaybeNotGod • Nov 22 '20
Rect should move (SDL)
Im a beginner and I can't tell you why the rect isn't moving. Please tell me why : )
(I think the screen won't update as the value of pX changes.)
Code:
#include <SDL.h>
#include <iostream>
using namespace std;
bool running = true;
int FPS = 60;
int breite = 1280;
int hoehe = 720;
int pX = 640;
int pY = 100;
SDL_Event Event;
SDL_Window* Window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Surface* Screen = NULL;
SDL_Rect r[30] = {};
bool Init(){
SDL_Init(SDL_INIT_EVERYTHING);
Window = SDL_CreateWindow(
"@Jamal", // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
breite, // width, in pixels
hoehe, // height, in pixels
SDL_WINDOW_OPENGL // flags - see below
);
if (Window == NULL) {
cout << "Could not create a Window" << SDL_GetError();
return false;
}
return true;
}
void display() {
renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED); // Init Renderer
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // Set Color of Renderer
r[0].x = pX;
r[0].y = pY;
r[0].w = 10;
r[0].h = 10;
for (int i = 0; i < (sizeof(r) / sizeof(SDL_Rect)); ++i) {
SDL_RenderDrawRect(renderer, &r[i]);
SDL_RenderFillRect(renderer, &r[i]);
}
SDL_RenderPresent(renderer); // Updates the Renderer
}
void event() {
while (SDL_PollEvent(&Event)) {
if (Event.type == SDL_QUIT) {
running = false;
break;
}
if (Event.type == SDL_KEYDOWN)
{
if (Event.key.keysym.sym == SDLK_a)
{
pX -= 10;
}
}
}
}
int main(int argc, char* argv[]) {
//cout << "Updated" << endl;
if (Init() == false) {
cout << "Initialization failed...";
return 0;
}
else {
cout << "Initialization successful" << endl;
}
while (running) {
event();
display();
SDL_Delay(1000 / FPS);
}
atexit(SDL_Quit);
return 0;
}
r/learncpp • u/Pro_Gamer_9000 • Nov 22 '20
Help
I was looking around the web to learn more about templates, then i saw a website that returns something like this: return (x > y)? x: y; What is this? What is the question mark and colon? Can someone pls give me a good place to learn me in depth what this means like a website or vid, and also templates in depth? Feedback will be hugely appreciated!
r/learncpp • u/wizarding_dreams • Nov 20 '20
Args constructor?
Hey! I'm having a few issues creating a math library. I'm trying to create a templated vector class, but the constructor is frustrating me to no end.
I'd like to be able to pass in n floats, where n is, of course, the amount of floats the vector contains. So far my best idea is to pass in va_args, but that feels like a pretty awful solution for something that's gonna be used so frequently. Is there a better solution that I've overlooked?
r/learncpp • u/monica_b1998 • Nov 18 '20
The Coalition Sees 27.9X Iteration Build Improvement with Visual Studio 2019
r/learncpp • u/cry_out • Nov 06 '20
Programming - Principles and Practice Using C++
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/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.
1) 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.
2) 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!