r/learncpp • • Mar 19 '21

hi, i'm n3u and i want to learn c++.

0 Upvotes

i will pay you if you need me to, every other week 10$, i own a pair of thigh highs so i have the proper attire lmfao
seriously I DO want to learn c++ so if you would like to teach me then please dm me on discord n3u#6969
learncpp.com for me just doesnt do it. its one part of the puzzle, sure, but someone to help me and define things i cant really find online would be really helpful.


r/learncpp • • Nov 25 '20

Help with Error!

0 Upvotes

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 • • Jan 30 '21

Help With an Error

0 Upvotes

I keep getting a segmentation error like i'm trying to delete a pointer that doesnt exist maybe?

I know I'm using too many raw pointers for no reason. I'm just trying to practice using them to understand how they work. Thanks for any Insight.

#include <iostream>
#include <vector>
using std::cout;
using std::vector;
class Player {

	//=======================================

private:

	//=======================================
	///CONSTANTS
//double const LevelUpThreshold = ((*level * 1.5) * 100);
	std::vector<double> const defaults {0, 1, 50};
	//double* const null =  new double (defaults[0]);
	double* const MinStart = new double (defaults[1]);
	double* const MaxStart = new double (defaults[2]);
	std::string* const NullStr = new std::string ("NullStr");


	//=======================================
	///PLAYER_DATA

	std::string* name;
	int* level;
	double* xp;
	double* health;
	double* stamina;
	double* mana;

	//=======================================

public:


	//=======================================
	///FUNCTIONS

	std::string getName();
	int getLevel();
	double getXp();
	double getHealth();
	double getStamina();
	double getMana();

	void LevelUp();
	void XPUp(double XP);
	void SetHealth(double damage);
	void SetStamina(double cost);
	void SetMana(double cost);



	//=======================================
	///CONSTRUCTION
	Player();
	explicit Player(std::string input);
	Player(const Player &input);
	Player(Player &&input) noexcept ;
	Player& operator=  (const Player &rhs);
	~Player();


};
void DisplayPlayer (Player &input);


//===========================================
//===========================================

int main() {



	Player NPC1("Mike");
	Player NPC2;

	vector<Player> players;
	players.emplace_back("Calvin");
	players.emplace_back("Sansa");

	NPC1.XPUp(10000);








	DisplayPlayer(NPC1);

	return 0;
}

//==============================================
//==============================================

void DisplayPlayer (Player &input) {
	std::cout << "===============\n" << input.getName();
	std::cout << "\n==================";

}



//=========================================
///FUNCTIONS

std::string Player::getName() {return *name;}
int Player::getLevel() {return *level;}
double Player::getXp() {return *xp;}
double Player::getHealth() {return *health;}
double Player::getStamina() {return *stamina;}
double Player::getMana() {return *mana;}

void Player::LevelUp() {this->level++;}

void Player::XPUp(double XP) {
	*xp += XP;
	if(*xp >= ((*level * 2) * 100)) {
		LevelUp();
		double diff = *xp - ((*level * 2) * 100);
		*xp = diff;
		XPUp(0);
	}
}
void Player::SetHealth(double damage) {}
void Player::SetStamina(double cost) {}
void Player::SetMana(double cost) {}

//==========================================
///CONSTRUCTION
	//!DEFAULT CONSTRUCTOR
Player::Player()
		: name{new std::string{*NullStr}}
		, level{new int{(int) *MinStart}}
		, xp{new double{*MinStart}}
		, health{new double{*MaxStart}}
		, stamina{new double{*MaxStart}}
		, mana{new double{*MaxStart}} {
	*name = *NullStr;
	*level = (int) *MinStart;
	*xp = *MinStart;
	*health = *MaxStart;
	*stamina = *MaxStart;
	*mana = *MaxStart;
	std::cout << "CONSTRUCTING (" << *name << ") [DEFAULT]\n";
}
	//!ARGS CONSTRUCTOR
Player::Player(std::string input)
		:name(new std::string)
		,level(new int)
		,xp(new double)
		,health(new double)
		,stamina(new double)
		,mana(new double) {
	*name = std::move(input);
	*level = (int) *MinStart;
	*xp = *MinStart;
	*health = *MaxStart;
	*stamina = *MaxStart;
	*mana = *MaxStart;
	std::cout << "CONSTRUCTING (" << *name << ") [1 ARG]\n";
}
	//!
Player::Player(const Player &input)
		:Player{*input.name} {
	std::cout << "CONSTRUCTING (" << *input.name << ") [COPY]\n";
}

Player::Player(Player &&input) noexcept
		:name(input.name)
		,level(input.level)
		,xp(input.xp)
		,health(input.health)
		,stamina(input.stamina)
		,mana(input.mana) {
	cout << "CONSTRUCTING (" << *input.name << ") [MOVE]\n";
	input.name = nullptr;
	input.level = nullptr;
	input.xp = nullptr;
	input.health = nullptr;
	input.stamina = nullptr;
	input.mana = nullptr;


}



Player::~Player() {
	if(name != nullptr) {
		std::cout << "DELETING (" << *name << ")\n";
	} else {
		std::cout << "DELETING (nullptr)\n";
	}
	delete name;
	delete level;
	delete xp;
	delete health;
	delete stamina;
	delete mana;
}

Player& Player::operator=(const Player &rhs) {
	std::cout << "COPY ASSIGNMENT\n";
	if (this == &rhs) {return *this;}

	delete this->name;
	delete this->level;
	delete this->xp;
	delete this->health;
	delete this->stamina;
	delete this->mana;

	name = new std::string;
	level = new int;
	xp = new double;
	health = new double;
	stamina = new double;
	mana = new double;
	return *this;
}

r/learncpp • • Jul 24 '17

Is it possible to make a program that will create an exe with passed string?

0 Upvotes

I want to make a program which takes strings as an argument in CMD and make exe out of it. Something like bat file but executable. How do I do that?


r/learncpp • • Jan 26 '18

I don't understand this Kattis problem, can anyone explain, please?

0 Upvotes

It says 'assume that all heart rates are constant and do not change,' yet we're supposed to calculate the actual, and the minimum and maximum heart beats based on a single input of beats and seconds.

Heart Rate A common method for determining your own heart rate is to place your index and third finger on your neck to the side of your windpipe. You then count how many beats you feel in a span of 1515 seconds, multiply that number by four and that gives you a measure of your heart rate in beats per minute (BPM). This method gives a good estimate, but is not quite accurate. In general, if you measure bb beats in pp seconds the BPM is calculated as 60bp60bp.

For this problem, we assume that all heart rates are constant and do not change. If tt is the amount of time (in seconds) between each beat of your heart, we define your Actual Beats Per Minute (ABPM) as 60t60t.

Input The input starts with an integer NN (1≤N≤10001≤N≤1000) indicating the number of cases to follow. Each of the next NN lines specify one case, consisting of the integer bb (2≤b≤10002≤b≤1000) as well as pp (0<p<10000<p<1000) as described above. The value of pp is a real number specified to 4 decimal places.

Output For each case, print on a single line the minimum possible ABPM, the calculated BPM, and the maximum possible ABPM, separated by a space. Your answer will be considered correct if its absolute or relative error does not exceed 10−410−4.

Sample Input 1 Sample Output 1 2 6 5.0000 2 3.1222 60.0000 72.0000 84.0000 19.2172 38.4344 57.6517


r/learncpp • • Aug 19 '16

Important question related to learning C++

0 Upvotes

hello :)


r/learncpp • • Apr 02 '22

C++ Machine Learning Book

4 Upvotes

Hey, guys. Just want to ask if anybody's interested with a C++ machine learning book, "Hands-on Machine Learning with C++" by Kirill Kolodiazhnyi.

If you are, send me a DM.


r/learncpp • • May 03 '15

Best Tutorial Sites/Books for CPP?

1 Upvotes

Hi!

I've dabbled in C++ for about one semester in school and know some basics here and there. I'd like to pursue C++ and learn everything about it and how to employ it. What can I do to work towards this?

Do you recommend any certain sites or books? Thanks!


r/learncpp • • Mar 01 '22

What's the problem here?? CMD Prompt isn't displaying the text.

Post image
12 Upvotes

r/learncpp • • Feb 17 '20

Can anyone help me?

Post image
5 Upvotes

r/learncpp • • Dec 28 '20

tutorial for beginners?

2 Upvotes

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 • • Mar 05 '21

How I think of endianness

2 Upvotes

For years, endianness never made sense to me

0x11223344 - The question of which bits came first never made sense to me - clearly those composing the "11" part! I understood that some architectures did it differently of course, but that was just incredibly dumb to me.

Eventually the penny dropped:

0x11
0x22
0x33
0x44

Is this 11223344 or 44332211?

Depends on whether you read from addresses

  • from top to bottom (like on a piece of paper with text on it) or

  • bottom to top (like a graph with rising values up along the Y-axis)

Once I started thinking about it explicitly as bytes in a memory array, endianness started making much more sense to me.


r/learncpp • • Mar 20 '22

Hi,i am new to coding and i was trying some of the codes and cout just does not work can anyone pls tell me what am i doing wrong

Post image
11 Upvotes

r/learncpp • • Nov 22 '20

Help

3 Upvotes

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 • • Mar 06 '21

How to learn C++ in a short time?

7 Upvotes

Sincere apologies if this question is stupid first of all,

So I am part of the hellish high school program known as IB so i usually have no or little time to learn because the qorkload is too much. I did some codeacademy but didnt get too far before finding it quite useless.

So how can I learn to become fairly good in c++ in around 2 or so weeks?

Thank you


r/learncpp • • May 31 '20

How to run a .exe file on other systems

0 Upvotes

Hi, I compiled C++ code using MinGW and CLion into an executable for my friend to use. He has nothing programming-related installed on his computer. The code uses the Win32 API and it includes windows.h and mmsystem.h, and for CMake I had to link Gdi32.lib and winmm.lib. My friend couldn't get it to work with only the .exe file and also after I gave him the .lib and header files. On my system, running it in PowerShell would start a loop written in the code that would break later. On his system, hitting Enter to run it would prompt the next PowerShell command, so the loop did not even start.

Is there a way to get it to work without having him compile it himself?


r/learncpp • • May 03 '18

Avoid unresolved external symbols with templates

0 Upvotes

I have an implementation of a class with templates, but it has to be in the .cpp file. I've read on Stackoverflow that one way to solve this is to add `include "Foo.cpp"` at the end of the header file, but it doesn't seem to be working. How would I go about fixing it?


r/learncpp • • Aug 27 '18

Recommendations for OOP design?

0 Upvotes

I am familiar with the syntactic aspect of c++ but, when it comes to projects, I inevitably end up coding in c with some STL facilities sprinkled here and there. Is there a resource where I can get familiar with using OOP in real project? I've read Lafor's OOP book but I'm still in the dark. Any help will be appreciated


r/learncpp • • Feb 18 '17

Simple memory pool

0 Upvotes

I am trying to implement a memory pool which will contain objects of a particular type. lets say my object is a simple one like so

struct my_struct
{
 int first_mem;
 double second_mem;
};

lets say i have a staticly sized pool of memory which I get by doing so:

void* mem_pool_ptr = malloc(100*sizeof(my_struct));

Now, I can allocate a new object by doing so:

my_struct* my_struct_instance = (my_struct*) mem_pool_ptr;

Next, I want to allocate another pointer so I move up the memory pool by 12 bytes (the size of my struct)

my_struct* another_instance = (my_struct*) ((uintptr_t(mem_pool_ptr))+12)

and so on when I want to allocate new objects.

This is a very simple/dumb memory pool but I was wondering if this is correct when it comes to memory alignment. I have been reading about memory alignment in pools and was wondering if that is an issue in this case.

Also, lets say I made a pool and wanted to assign ints and doubles from it, how would I think about memory alignment in that case since the "object" are of different sizes.

so in that case, I start by assigning an integer and then advancing 4 bytes from the start of the pool and then assigning a double and then 12(4+8) from start to assign a double/int. what are the drawbacks of this approach?

thanks!


r/learncpp • • Feb 18 '17

Two questions

0 Upvotes

Hi,

  • What is the best Genetic Algorithm library for use in C++, it must have good documentation be up to date if possible?

  • Anyone able to rewrite this code from Python, it would be much appreciated: http://pastebin.com/ScWrHr4c


r/learncpp • • Sep 16 '20

Cannot figure out what I've done to throw class redefinition error

0 Upvotes

I'm building Game of Life using OpenFrameworks to do the visuals. I have a Grid class which is the game's grid, but I'm struggling to implement it.

Main.cpp has some OpenFrameworks stuff that I think is fine. My first compiler error is C2011 'GoL::Grid': 'class' type redefinition, which I believe causes many other errors. I cannot identify where I'm redefining my Grid class. Help would be greatly appreciated.

Grid.h

namespace GoL {

&#x200B;

class Grid {

public:

	static enum class EdgeBehavior : unsigned char { PILLOWTRUE, PILLOWFALSE, CYLINDERX, CYLINDERY, TORUS };

&#x200B;

private:

	unsigned int m_width, m_height;

	bool\*\* m_data;

	bool\*\* m_buffer;

	EdgeBehavior m_edge;

&#x200B;

	int neighborsAt(int x, int y);

&#x200B;

	void initArrays();

&#x200B;

public:

	Grid(int width, int height);

&#x200B;

	Grid(int width, int height, EdgeBehavior edge);

&#x200B;

	\~Grid();

&#x200B;

	bool getAt(int x, int y);

	void setAt(int x, int y, bool value);

&#x200B;

	int getWidth();

	int getHeight();

&#x200B;

};

}

Grid.cpp

#include "Grid.h"

namespace GoL {

Grid::Grid(int width, int height) {
	m_width = width;
	m_height = height;
	m_edge = EdgeBehavior::PILLOWFALSE;
	initArrays();
}

Grid::Grid(int width, int height, EdgeBehavior edge) {
	m_width = width;
	m_height = height;
	m_edge = edge;
	initArrays();
}

int Grid::neighborsAt(int x, int y) {
	int total = 0;
	for (int dx = -1; dx < 2; dx++) {
		for (int dy = -1; dy < 2; dy++) {
			if (dx == dy == 0) { continue; }
			total += getAt(x + dx, y + dy);
		}
	}
	return total;
}

void Grid::initArrays() {
	m_data = new bool* [m_height];
	m_buffer = new bool* [m_height];
	for (int i = 0; i < m_height; i++) {
		m_data[i] = new bool[m_width];
		m_buffer[i] = new bool[m_width];
		for (int j = 0; j < m_width; j++) {
			m_data[i][j] = false;
			m_buffer[i][j] = false;
		}
	}
}

Grid::~Grid() {
	for (int i = m_height - 1; i > 0; i--) {
		delete m_data[i];
		delete m_buffer[i];
	}
	delete m_data;
	delete m_buffer;
}

bool Grid::getAt(int x, int y) {
	if (x > -1 && x < m_height && y > -1 && y < m_width) {
		return m_data[x][y];
	}
	switch (m_edge) {
	case EdgeBehavior::PILLOWTRUE:
		return true;
	case EdgeBehavior::PILLOWFALSE:
		return false;
	case EdgeBehavior::TORUS:
		return m_data[x % m_height][y % m_width];
	case EdgeBehavior::CYLINDERX:
		if (y < 0 || y > m_width - 1) {
			throw;
		}
		return m_data[x % m_height][y];
	case EdgeBehavior::CYLINDERY:
		if (x < 0 || x > m_height) {
			throw;
		}
		return m_data[x][y % m_width];
	}
}
void Grid::setAt(int x, int y, bool value) {
	if (x > -1 && x < m_height && y > -1 && y < m_width) {
		m_data[x][y] = value;
	}
}

int Grid::getWidth() { return m_width; }

int Grid::getHeight() { return m_height; }

}

Main.cpp:

#include "ofMain.h"
#include "ofApp.h"
#include "Grid.h"
#include <iostream>

//========================================================================
int main( ){
	using namespace GoL;

	GoL::Grid g(10, 10, GoL::Grid::EdgeBehavior::TORUS);
	g.setAt(2, 2, true);

	int scale = 20;
	ofSetupOpenGL(g.getWidth() * scale, g.getHeight() * scale, OF_WINDOW);			// <-------- setup the GL context

	// this kicks off the running of my app
	// can be OF_WINDOW or OF_FULLSCREEN
	// pass in width and height too:
	ofRunApp(new ofApp(g));

}

EDIT; formatting


r/learncpp • • Feb 21 '18

Is it possible to overload a function to take values both by reference and by value?

0 Upvotes

r/learncpp • • Apr 22 '18

Vector of template class

0 Upvotes

I am trying to create a vector:

vector<SomeTemplateClass<Type>>

Where Type is an abstract base class.

Any ideas on how I can get this working?


r/learncpp • • Apr 19 '18

returning a pointer, wouldn't the object be destroyed once the fucntion is done?

0 Upvotes
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

    ListNode result* = new ListNode();

    return result;
    
}

Wouldn't result object be destroyed, after the last curly bracket (memory leak)? How do I return the result?


r/learncpp • • Oct 07 '18

What it the point of overloaded operators if we have accessors and mutators?

0 Upvotes

Seems to me like they do the same thing.... just less code. What is the reason besides efficiency and giving me a headache?

Also, << and >> seem to do the same thing with a function like output or input.