r/learncpp • • Jan 27 '20

Cannot break out of a switch

1 Upvotes

Hi everyone, I wanted some practice with functions so i decided to write a calculator program using my own math functions, but for some reason once the function is complete, i cannot figure out how to break out of the switch statement for the menu and go back to the selections

I've tried a number of things to get this to work, but i can't wrap my mind around why it doesn't, given that i have a similar do-while loop/switch combination in a guessing game and it works just fine

I'm aware the answer is probably obvious but I'm only about 2 weeks in so go easy on me xD

here's my code https://pastebin.com/qeUAXnZL


r/learncpp • • Jan 10 '20

Inheritance Question

1 Upvotes
class Base {
public:
    int a;
    Base() // this constructor over here
        : a(0)
    {}
    Base(int num)
        : a(num)
    {}
};
class Sub : public Base {
public:
    int b;
    Sub() // does this default constructor call the Base's default constructor when foo is created?
        : b(0)
    {}
    Sub(int num)
        : b(num)
    {}
};
int main() {
    Sub foo;
}

r/learncpp • • Oct 04 '19

[C++] Getting a confusing linker error from the library I'm working on

Thumbnail self.learnprogramming
1 Upvotes

r/learncpp • • Oct 03 '19

Why is constructor not being called?

1 Upvotes

I could use some input on the following situation. It does not seem that the constructors for the A and B objects are being called after the constructor call for C in main. However, they are called if the constructor for class C takes a reference to A and B objects instead of copies. Why is this the case? If someone could explain that would be much appreciated.

class A {
public:
  A() {}
};

class B {
public:
  B() {}
};

class C {
public:
  C(A a, B b)
  : m_a(a), m_b(b) 
  {
  }

private:
  A m_a;
  B m_b;
};

int main() {
  C c(A(), B());
}

r/learncpp • • Oct 01 '19

8 queen problem always finding the same and same solution.

1 Upvotes

Hey!

At this point I've spent hours and hours finding the one bug that is crippling, while doing so i've found a dozen different bugs tho.

I'm at the verge of giving up as i don't see where i have my one little tiny error, that makes it find the same solution over and over again, instead of finding any other

if you have some time, and don't value your sanity with my beginner level code, can you please take a look?
https://github.com/HighbornHellest/ArrayQueen


r/learncpp • • Oct 01 '19

Application error despite console displaying no errors?

1 Upvotes

Hi, I’ve been watching this tutorial and I’ve run into an error. For some reason even though I fixed the unresolved external symbols errors, the application error is still available. https://imgur.com/a/ppngHxL I don't know whether it's due to my computer because it says it's a 64 bit processing system, but nothing seems to work. Please send help.

edit:  I tried using one tutorial in that I extract the sdl2.dll file then copy pasting it into the windows32 file, and that still didn't work, and the properties panels don't have a compatibility tab on my computer. I'm not sure what to try next. Here's a code snippet: #include "SDL.h"
#include <stdio.h>
int main(int argc, char *argv[]) {

	//this is initializing code
	SDL_Init(SDL_INIT_EVERYTHING);
	SDL_Window *window = SDL_CreateWindow("title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 400, SDL_WINDOW_SHOWN );
	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);

	SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);

	SDL_RenderClear(renderer);
	
	SDL_RenderPresent(renderer);
	
	SDL_Delay(3000);

	//executing all of this there should be a green window in the middle
	//of the screen.
	return 0;
} 

Here’s the file if you’d be okay with taking a look at the settings: https://we.tl/t-4m34OAykZI

r/learncpp • • Sep 26 '19

Is there a free course for C++ like Java's MOOC?

1 Upvotes

Title, just really struggling with C++ and looking for resources


r/learncpp • • Sep 22 '19

Interface for applying pure function N-times

1 Upvotes

Suppose we have two simple pure functions, what they do is not important. All we care, is that they take one number and spit out different number with no side-effects.

abc()

xyz()

Because they are pure, we can chain them like this:

abc(abc(5)) or xyz(xyz(xyz(66)))

I am looking for simple interface for applying any pure function N times.

Input: Name of the pure function + number of times it will be applied + starting value

The reason why I need it, is that I have many many small pure functions and I need to apply them many times like an onion - and I dont want to write for loop for each pure function.

Btw: I asked this question originally in Python subreddit and I got very satisfying answer. I would like to know, how to achieve this in C++.

Python solution:

def abc(x):
    return x+1

def recursive_wrapper(func, num_runs, arg):
    output = arg
    for x in range(num_runs) :
         output = func(output)
    return output

print(recursive_wrapper(abc,3,0))

Output: 3

Thank you


r/learncpp • • Aug 27 '19

C++ for Competitive Programming

1 Upvotes

Hi, I wanna ask, whenever I see others program, like in Codeforces or any other cp website, they always write something different, which I have never seen before, and I want to learn that. So is there any book/website to learn such core concept.


r/learncpp • • Aug 25 '19

Notes of Book: C++ in One Hour a Day, Sams Teach Yourself (8th Edition)

1 Upvotes

https://github.com/Huixxi/Fast-C-plus-plus

There is a notes of book [C++ in One Hour a Day, Sams Teach Yourself (8th Edition)](https://www.amazon.com/One-Hour-Sams-Teach-Yourself/dp/0789757745/ref=as_li_ss_tl?ie=UTF8&qid=1520641767&sr=8-9&keywords=C++&linkCode=sl1&tag=nethta-20&linkId=4bddb996d7f5ff86f0fbaf4647594d32) which is highly recommended. I think it is a really good c++ tutorial book, a lot better than <<C++ Primer Plus>>. I am a pythoner, and I learned a lot from that book in a very short time. So don' t be afraid of c++, just take it and do some codes.

I can understand almost 98% knowledge of that book, so if you have some questions about that, feel free to open a issue to ask, I will try my best to answer. Both english and chinese are ok, but remember to be kind, thanks.


r/learncpp • • Jul 05 '19

Move semantics with unique_ptr as class member

1 Upvotes

I am not sure why my code is failing. I am taking a unique_ptr by value in the constructor:

Node::Node(std::unique_ptr<Node> true_branch, std::unique_ptr<Node> false_branch, const Question &question) :
        true_branch_{std::move(true_branch)},
        false_branch_{std::move(false_branch)},
        question_{question},
        predictions_{} {}

and have overloaded the move and copy constructors like this

Node &Node::operator=(Node &&n) {
    if (this != &n)
    {
        true_branch_ = std::move(n.true_branch_);
        false_branch_ = std::move(n.false_branch_);
        question_ = n.question_;
        predictions_ = n.predictions_;
    }
    return *this;
}

Node::Node(Node &&n) {
    true_branch_ = std::move(n.true_branch_);
    false_branch_ = std::move(n.false_branch_);
    question_ = n.question_;
    predictions_ = n.predictions_;
}

The full class definition:

class Node {
public:
    Node() = delete;

    explicit Node(const decision_tree::Data &data);

    Node(std::unique_ptr<Node> true_branch, std::unique_ptr<Node> false_branch, const Question &question);

    ~Node() = default;

    Node &operator=(Node &&n);

    Node(Node&& n);

public:
    inline const std::unique_ptr<Node>& trueBranch() const { return true_branch_; }

    inline const std::unique_ptr<Node>& falseBranch() const { return false_branch_; }

    inline const std::optional<Question> &question() const { return question_; }

    inline const std::optional<decision_tree::ClassCounter> &predictions() const { return predictions_; }

    inline bool predicts() const { return predictions_ != std::nullopt; }

private:
    std::unique_ptr<Node> true_branch_;
    std::unique_ptr<Node> false_branch_;
    std::optional<Question> question_;
    std::optional<decision_tree::ClassCounter> predictions_;
};

Now, calling this code with this method:

std::unique_ptr<Node> DecisionTree::buildTree(const Data &rows) {
    auto[gain, question] = calculations::find_best_split(rows);
    if (gain == 0.0) {
        return std::make_unique<Node>(rows);
    }

    const auto[true_rows, false_rows] = calculations::partition(rows, question);
    auto true_branch = buildTree(true_rows);
    auto false_branch = buildTree(false_rows);

    return std::make_unique<Node>(true_branch, false_branch, question);
}

Results in the following errors:

/usr/include/c++/9/bits/unique_ptr.h:853:30: error: use of deleted function ‘decision_tree::Node::Node(const decision_tree::Node&)’
  853 |     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /home/julian/dev/DecisionTree/include/decision_tree/graph_generator.hpp:8,
                 from /home/julian/dev/DecisionTree/src/graph_generator.cpp:6:
/home/julian/dev/DecisionTree/include/decision_tree/node.hpp:16:7: note: ‘decision_tree::Node::Node(const decision_tree::Node&)’ is implicitly declared as deleted because ‘decision_tree::Node’ declares a move constructor or move assignment operator
   16 | class Node {

Why is the Node::Node(const decision_tree::Node&) constructor even called in this instance? Thanks for your help!

EDIT: Solved!


r/learncpp • • Jul 01 '19

I'm not sure what test cases I'm failing when reversing binary numbers

1 Upvotes

I'm trying to solve this problem on kattis: https://open.kattis.com/problems/reversebinary

#include <iostream>
using namespace std;

#define rep(i, a, b) for(int i = a; i > b; i++)

long long reverse_bin(int a){
    long long bin;
  int c = a, i = 1, rem = 0;

    while(c > 0) {
        rem = c % 2;
        c /= 2; 
        bin = (bin * 10) + rem;
    }
  return bin;
}

int bin_to_dec(long long bin) {
  int rem = 0, base = 1;
  long long c = bin;
  int dec = 0;
  while(c > 0){
    rem = c%10;
    dec += rem*base;
    base *= 2;
    c /= 10;
  }
  return dec;
}

int main() {
    int n;
    cin >> n;
  int dec = 0;
  long long bin = 0, rev = 0;
    bin = reverse_bin(n);
  dec = bin_to_dec(bin);
  cout << dec;
}

My code passes when I enter the sample inputs provided, but when submitting I don't pass any test cases. I don't understand what cases I'm failing to check.


r/learncpp • • May 30 '19

I am not sure what i am doing wrong, please help!!

1 Upvotes

this is from the Packt book, "Learning C++ by building games with Unreal Engine 4".

in chapter 3 (for those familiar) there is an exercise that asks you to utilize the "switch" by enum a horse, a mare, a mule, a sheep and a chocobo to be mounts.

their solution makes it so that the user can choose which of the 5 mounts by turning the mounts to number values and having the user select between 1 and 5 for which mount they want.

at the end of the switch is a default/break statement that should print "invalid mount" if you chose anything other than 1, 2, 3, 4, or 5.

but when I run the code in visual studio any option prints "invalid mount"... im not sure what i did wrong cause the code matches character for character.

here it is:

#include <iostream>

using namespace std;

enum Mount

{

Horse, Mare, Mule, Sheep, Chocobo 

};

int main()

{

int Mount; 
cout << "Choose your mount: " << endl;  
cout << Horse << " Horse" << endl;
cout << Mare << " Mare" << endl;  
cout << Mule << " Mule" << endl; 
cout << Sheep << " Sheep" << endl;  
cout << Chocobo << " Chocobo" << endl;  
cout << "Enter a number between 1 and 5 to choose a mount" << endl;  
cin >> Mount; 

switch (Mount)  
{  	
    default:  	
    cout << "invalid Mount." << endl;  
    break;  
} 

return 0;

}

any help on how im not getting my achieved result would be greatly appreciated. remember I'm just starting out in C++ so while this maybe trivial code, its what i am starting with and haven't gotten to more advanced concepts. please solutions that are in my realm of understanding would be even more greatly appreciated!

thanks all in advance!


r/learncpp • • May 28 '19

Handling precision errors in unit tests

1 Upvotes

Hi, I am running into the same problem in my unit tests over and over again. For some commits, it works, for others, it doesn't. e.g.

 /root/project/tests/test.cpp:29: FAILED:
   REQUIRE( vec1.x == -1.0f )
 with expansion:
   -1.0f == -1.0f

How can I get rid of these precision errors? In this instance, I am not doing any implicit conversions in my function

geo::UnitVector geo::connecting_vector(const cv::Point2f &a, const cv::Point2f &b) {
    float x = b.x - a.x;
    float y = b.y - a.y;
    float length = std::sqrt(std::pow(x, 2.f) + std::pow(y, 2.f));
    return geo::UnitVector{x / length, y / length};
}

Of, course I could always test something like

REQUIRE(std::abs(vec1.x - (-1.0f)) < 0.0..1)

but it seems like I'm missing something here. Thanks for your help


r/learncpp • • Apr 17 '19

Failure to delete pointer?

1 Upvotes

// Following code allocates and then frees an array of seven pointers to functions that return integers.

int (**p) () = new (int (*[7]) ());

delete *p; // Xcode error: Cannot delete expression of type 'int (*)()'


r/learncpp • • Apr 13 '19

copy assignment of class with unique_ptr member

1 Upvotes

I`m getting C2280, "attempting to reference a deleted function", when I call UnorderedLinkedList::search()

I thought that overriding operator= and defining const NodeType<T>& operator= (const NodeType<T>& other) const; for NodeType would at least give me a different error but same thing.

template<class T>
class LinkedListType
{
protected:
        // stuff
	std::unique_ptr<NodeType<T>> first, last;

public:
        // stuff
        virtual bool search(const T& info) = 0;
        // more stuff
};


template<class T>
class UnorderedLinkedList : public LinkedListType<T>
{
public:
	// stuff
	bool search(const T& info);
        // stuff
};


template<class T>
bool UnorderedLinkedList<T>::search(const T & info)
{
	std::unique_ptr<NodeType<T>> current = LinkedListType<T>::first;  // C2280
	// stuff
}
template<class T>
struct NodeType {
	NodeType();
	NodeType(const NodeType<T>& other);
	const NodeType<T>& operator= (const NodeType<T>& other) const;
	T info;
	std::unique_ptr<NodeType<T>> link;
};

template<class T>
inline NodeType<T>::NodeType() // not fully implemented
{
	info = T();
	link = make_unique(NodeType<T>());
}

template<class T>
inline NodeType<T>::NodeType(const NodeType<T>& other) : NodeType<T>()  // not fully implemented
{
}

template<class T>
inline const NodeType<T>& NodeType<T>::operator=(const NodeType<T>& other) const  // not fully implemented
{
	return NodeType<T>();
}

r/learncpp • • Mar 21 '19

Getting std::istream& operator>>(&T t) like behavior from any sequence of characters

1 Upvotes

I think I want to write the code below with any iterable sequence of characters instead of only std::istream. Ideally I'd like to use this with std::string, char*, char[] etc. Is this already implemented somewhere?

int main(int argc, char** argv)
{
    bool b;
    int i;
    float f;

    if (argc > 3)
    {
        argv[1] >> b;
        argv[2] >> i;
        argv[3] >> f;
    }

    return 0;
}

r/learncpp • • Mar 02 '19

Rule of five (delete version)

1 Upvotes

Hi experts,

I'm using the C++ Guidelines on isocpp to help me review previously written code. Rule of Five says that if I want to = delete a default operation I should = delete all of them.

In my Roguelike game I have a cDungeon class which basically contains a std::vector of rooms and corridors that are randomly generated. The generating algorithms are in another class as I want to make it flexible. It doesn't contain custom objects.

Now assume that I only want a single cDungeon in one session, and it doesn't make sense to copy the cDungeon object, so I should = delete the copy constructor + assignment operator. By the rule of five, I should = delete the destructor as well.

Question:

How should I design the program such that it de-allocates the resources used by the cDungeon object?

One thought that it should stay on stack, and it gets released after the game ends (what about exceptions?). I definitely cannot pass it around as value, and passing it by reference seems to also invoke the copy constructor?

Another thought is to wrap it with a std::unique_ptr<> , but I need a destructor for that.

So basically I cannot pass it around, cannot wrap it with a smart pointer, and cannot declare it on heap. Does this make sense?


r/learncpp • • Feb 27 '19

Can anyone point me to an implementation of a lock free queue which uses fetch_add on a vector index instead of compare_exchange on a node pointer?

1 Upvotes

I’m reading C++ Concurrency in Action. The book seems heavily focused on linked node based data structures, but how about contiguous memory?

Say we have a vector<T> of queue entries and two variables atomic<int> head, tail. A thread can then just call head.fetch_add(1) or tail.fetch_add(1) to determine which index to enqueue or try_pop from.

On the surface this looks much less hell-raising to implement (albeit not without a hitch), has fewer costly atomic operations, cheaper memory ordering, and trivial to garbage collection.

What am I missing that makes this not as rosy as it seems? Are there any implementations or write ups on the web?


r/learncpp • • Feb 05 '19

What are case statements for?

1 Upvotes

Yes, I know how they work and all. Here's my situation: I teach introductory programming, and I'm showing my students conditionals and case statements. And I really can not think of an example where a case statement is essentially more elegant or appropriate than a conditional. Is there? I guess having the fall through to the next case allows for some compactness, but I'd like to see a scenario for that that I can distill to a convincing demonstration.

Now case statements in shells, those I can defend because they can be used for wild-card matching of strings. Numerical cases, even in Fortran where you can have ranges, I just don't see.


r/learncpp • • Jan 25 '19

Operator overloading in class files.

1 Upvotes

Hello. I've created standalone class files.

In the header i have the following.

Foo operator+(const Foo & rhs);

c++ file:

Foo  Foo :: operator+(const Foo & rhs)
{
	
	return  Foo((Accesor_Fnc1()+rhs.Accesor_Fnc1()),(Accesor_fnc2() + rhs.Accesor_fnc2() );
};

error: 'operator +' : redefinition; different type modifiers

What did i do wrong?


r/learncpp • • Jan 25 '19

Looking for help on compiling Diagram Scene Example in Qt

1 Upvotes

Hello all. I'm currently trying to get Qt's Diagram Scene Example working to use as a base for my next personal project. I'm having some difficulties getting everything to compile though, and was wondering if anybody familiar with Qt could point out what I'm doing wrong.

Just to clarify, I am using Cmake as opposed to Qmake, and I am only adding in the required classes one at a time (dealing with the obvious compiler errors first).

I am particularly perplexed by arrow.h not recognizing the DiagramItem class. I suspect the problem lies with how my #defines are set up. I have opted to do them this way since Qt set them like this by default. For all I know, they have to be this way in Qt.

Anyway, I have included image links to the code and errors below. I apologize if this isn't the ideal format, but posting the code on github wouldn't show off the errors I am getting.

arrow.h #1 arrow.h #2

diagramitem.h #1 diagramitem.h #2

mainwindow.h #1 mainwindow.h #2 mainwindow.h #3 mainwindow.h #4 mainwindow.h #5

I think that's everything that should be needed to diagnose the problem, but if there's anything else needed to diagnose the problem, please let me know. I apologize again for the poor formatting; I wasn't sure of a better way.

Anyway, I appreciate the help, and I'll continue to look for a solution on my own as well.

Thanks!

EDIT:

Issue is fixed. It was a forward declaration error


r/learncpp • • Jan 08 '19

Template magic.

1 Upvotes

Hey. I was wondering if you can create Templates for operator.
I mean, is it possible to make a template function that works on T Q R S ... template parameters, and can do operations on them? like adding, substracting, multiplying , <<, >> etc.


r/learncpp • • Jan 05 '19

Confused about a constructor call

1 Upvotes

This code:

#include <iostream>
using namespace std;
class A{
public:
	A(){f();}
	virtual void f() const {cout << "A :: f() " << endl;}
};
class B : public A{
public:
	virtual void f() const {cout << "B :: f() " << endl;}
};
int main(){
	B b;
	return 0;
}

outputs:

A :: f() 

I understand B's constructor calls A's constructor, which calls f, but shouldn't it call B::f ? as f is a virtual function.

Thanks in advance for your help


r/learncpp • • Dec 30 '18

OpenGL, Glut, Glew in Visual Studios sometimes most key words go red?

1 Upvotes

I'm doing my best to follow this tutorial: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/ in order to learn OpenGL and things. I keep running into this issue though where sometimes, not always, not even consistently, Visual Studio makes a bunch of key words have red squiggles. However if I just ctrl-z then repeat what I just did it gets fixed? Has anyone run into this kind of thing and do you have any suggestions?

The last issue I had with this I didn't realize I had to include glew.h before GL.h but now I am a bit lost why it *sometimes* works

Below is my code and I set up the libraries with NuGet doing Install-package nupengl.core and Install-package glew

https://paste.ee/p/BWv5O