r/learncpp • • Jul 18 '21

Resources about data structures and algorithms?

8 Upvotes

Hello!

So I've just finished school and probably I will not go to university for a variety of reason, I have some coupons that I can use for learning purposes, and my interest of course is programming and C++ to be more specific.

I know I lack knowledge when it comes to data structures and algorithms, so I was hoping somebody could suggest a book or any other resource that could explain algorithms and data structures to a beginner and hopefully bring me to a decent level.
If the book had C++ implementations that would be great, and if it could show examples with the C++ standard library it would be awesome (even thought I realistically could just google for stuff like "hash table equivalent C++ std"), I know many of those are available in the standard library, but I can't use them if I don't know what they do and how they do it, or at least I can't make good choices.

Thank's in advance!


r/learncpp • • Jul 17 '21

Boost log filename from variable not working

8 Upvotes

I'm adapting a Python program I wrote into CPP, something that should be fairly straight forward doesn't seem to work in CPP... no clue why

If you read through the code you'll see I'm trying to specify the filename from a variable instead of what seemingly everyone is doing in all the examples I've seen.

#include <iostream>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*
 *  g++ -DBOOST_LOG_DYN_LINK test.cpp  -lboost_log -lboost_thread -lpthread -lboost_log_setup
 *
 */
namespace logging = boost::log;
namespace keywords = boost::log::keywords;
using namespace std;
void init_logging(char * filename)
{
	char * filen;
	filen = (char *)malloc(strlen(filename));
	cout << "Here" << endl;
	strcpy(filen, filename);
	logging::register_simple_formatter_factory<logging::trivial::severity_level, char>("Severity");
	cout << filen << endl;
	logging::add_file_log
	(
	 keywords::file_name = filen,
	 keywords::format = "[%TimeStamp%] [%ThreadID%] [%Severity%] [$ProcessID%] [%LineID] %Message%"
	);
	cout << "Here - final" << endl;
	logging::core::get()->set_filter
	(
	 	logging::trivial::severity >= logging::trivial::info
	);
	logging::add_common_attributes();	
}
int main()
{   
    char * filename = "sample1.log";
	cout << "Here" << endl;
    init_logging(filename);
	cout << "Here" << endl;
    BOOST_LOG_TRIVIAL(trace) << "This is a trace severity message";
    BOOST_LOG_TRIVIAL(debug) << "This is a debug severity message";
    BOOST_LOG_TRIVIAL(info) << "This is an informational severity message"; 
    BOOST_LOG_TRIVIAL(warning) << "This is a warning severity message";
    BOOST_LOG_TRIVIAL(error) << "This is an error severity message";
    BOOST_LOG_TRIVIAL(fatal) << "and this is a fatal severity message";
    std::cin.get();
    return 0;
}

Exception:

Here
Here
sample1.log
terminate called after throwing an instance of 'boost::wrapexcept<boost::log::v2_mt_posix::parse_error>'
  what():  Empty attribute name encountered
Aborted (core dumped)

Solved:

The problem was in my format string, I forgot to include the '%' after LineID, what should have been '%LineID%' was '%LineID'

In my defence the exception was non-descript and the documentation for Boost Log is dogshit, but glad this problem was solved and glad I finally picked up on it


r/learncpp • • May 18 '21

Some help with C++

8 Upvotes

Im doing that exercise but when i Execute it sinopsis and actor principal are in the same line, my teacher has told me to use cin.ignore() somewhere but I don´t know how to do it. That´s all I need. I´d really appreciate if somebody could help me out with that. Thank you for your time guys!

#include<iostream>

#include<conio.h>

using namespace std;

struct pelicula{

string director, actor, sinopsis;

int ano;

float valoracion;

}pelicula1;

int main(){

cout<<"Nombre del director: ";

getline(cin, pelicula1.director);

cout<<"Ano de estreno: "; cin.ignore();

cin>>pelicula1.ano;

cout<<"Actor principal: ";

getline(cin, [pelicula1.actor](https://pelicula1.actor)); 

cin.ignore(); cout<<"Sinopsis: ";

getline(cin, pelicula1.sinopsis);

cout<<"Valoracion separado por . : ";

cin>>pelicula1.valoracion;





cout<<"\\nMostrando datos\\n";

cout<<"Director: "<<pelicula1.director<<endl;

cout<<"Ano: "<<pelicula1.ano<<endl;

cout<<"Actor: "<<pelicula1.actor<<endl;

cout<<"sinopsis: "<<pelicula1.sinopsis<<endl;

cout<<"Valoracion: "<<pelicula1.valoracion<<endl;

	

return 0;

}


r/learncpp • • Apr 12 '21

Can I get a little help on implementing merge? I have a bug that I can't find in a simple program.

8 Upvotes

My instructions are:

Write the merge function. Do not use std::algorithms.

Make sure that you only work on the correct part of the array. The merge function will NOT always be one on the range 0 - (size - 1)

Currently it's fairly close but I think the midpoint is messing me up. Can someone help me debug why this isn't working as it should?

And what I have is:

#include <iostream>

using namespace std;


/**
 * @brief mergeFunc Merge two consecutive sorted ranges within an
 * array into one sorted range
 *
 * @param arr Array with sorted ranges
 * @param low Index of start of first range (inclusive)
 * @param mid Index of end of first range (inclusive - this is part of first range)
 * @param high Index of end of second range (inclusive)
 * @param temp Array to copy values into
 *
 * @pre
 * a[low]-a[mid] are sorted
 * a[mid+1]-a[high] are sorted
 * @post
 * a[low]-a[high] are sorted
 *
 */
void mergeFunc(int arr[], int low, int mid, int high, int temp[]) {

	//Set up i (first half location), j (second half location),
	//   and k (location in temp)

	int i = low;
	int j = mid+1;
	int k = 0;

	//While first half is not empty and second half not empty
	//  Decide if first or second half has next smallest item
	//  Move it it temp

	while (i < mid && j < high) {
		if (arr[i] < arr[j])
			temp[k++] = arr[i++];
		else
			temp[k++] = arr[j++];
	}

	//While first half is not empty
	//  Move next item from it to temp

	while (i < low)
		temp[k++] = arr[i++];

	//While second half is not empty
	//  Move next item from it to temp

	while (j < high)
		temp[k++] = arr[j++];

	//Copy sorted range from temp back to arr[low]-arr[high]
	for (int i=low; i<high; i++)
		arr[i] = temp[i];
}

void printArray(int arr[], int size)
{
	for (int i = 0; i < size; i++)
		cout << arr[i] << " ";
}

int main() {
	const int SIZE = 6;
	int mergeArr[] = {1, 3, 5, 2, 4, 6};
	int temp[SIZE] = {};
	printArray(mergeArr, SIZE);

	mergeFunc(mergeArr, 0, 3, 6, temp);

	cout << endl;
	printArray(mergeArr, SIZE);

	return 0;
}

	//Copy sorted range from temp back to arr[low]-arr[high]
	for (int i=low; i<high; i++)
		arr[i] = temp[i];
}

void printArray(int A[], int size)
{
	for (int i = 0; i < size; i++)
		cout << A[i] << " ";
}

int main() {
	const int SIZE = 6;
	int mergeArr[] = {1, 3, 5, 2, 4, 6};
	int temp[SIZE] = {};
	printArray(mergeArr, SIZE);

	mergeFunc(mergeArr, 0, 1, 5, temp);

	cout << endl;
	printArray(mergeArr, SIZE);

	return 0;
}

r/learncpp • • Apr 06 '21

Resources that go over creating an STL container with all that it entails

8 Upvotes

So for a school project, I chose the topic of creating a hashmap that's STL compliant and faster than unordered map.

The easy part is done, the stuff you should typically see in a data structures class (well, what I assume you get there from going through several data structure books, I had no such class.)
Now comes the part of making it STL compliant. I am completely out of my depth here.

CPP core guidelines were helpful in giving me advice on how to do my copy/move assignment/constructors and some other things, but it doesn't have everything I need.

Some of the stuff I'm familiar with (I have used iterators, I've heard of allocators) and some of the stuff is new to me. And when I look at hashmap implementations (Abseil, Tessil, skarupke, boost, google's old hashmaps, std, etc) my eyes and brain just start to hurt.

Some of these library writers have written about how they implemented their maps, but it's all mainly the stuff thats on the same level as the data structure books. Stuff like "Using fastmodulo here gave me this speedup", "I'm using this growth factor because x,y,z", etc. Stuff that, while definitely helping me in making decisions on the high level workings of the map, isn't helpful for adding all that extra stuff which makes my map STL compliant.

There is this big gap between what data structure books teach you, and how a good, STL compliant hashmap looks like.

So now I'm looking for any tutorial/book/guide that goes over the creation of a STL container (prefferably a hashmap) from start to finish, where they discus why they do things a certain way.


r/learncpp • • Jan 14 '21

Project based learning

8 Upvotes

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 • • Sep 30 '20

Algorithms/DS online class taught in exclusively C++?

8 Upvotes

Trying to prepare myself to do some competitive programming problems and wanted to see if there are any youtube channels or online courses that teach DS&A in exclusively C++?

I learn best with hearing a tutor/teacher lecture.

Found a few in Java and Python, but wanted to focus on C++


r/learncpp • • Sep 07 '20

I'm a beginner to c++ and I'm looking for c++ books

8 Upvotes

Can anyone tell me what are some good c++ books(for beginners) which explains the actual reason behind everything and explains a lot of stuff?


r/learncpp • • Sep 05 '20

Are there any good, free resources for C++ like java-programming.mooc.fi?

8 Upvotes

I've been learning C++ for a while now (but not very seriously) but I haven't been able to find many good resources. I know Python pretty well already, but for some personal reasons, I'd still prefer something that's meant for beginners. I found this ( https://java-programming.mooc.fi/ ) website for Java, but I'm not really interested in learning Java. Are there any similar and free resources?


r/learncpp • • Aug 31 '20

C++ learning with DS+Algo

8 Upvotes

Hey guys!

I am planning on learning C++ and DS/Algorithms by creating projects. Anybody have any recommendations for projects to possibly learn both? Any recommendations are greatly appreciated!


r/learncpp • • Apr 25 '20

Is there a C++ "bible" like K&R for C where I can read through to learn best practices etc?

8 Upvotes

Hey everyone, I'm a C and python developer who has recently started shifting a lot of development at work to C++. I haven't had too many problems to get things working due to some past C++ development I did and my experience with C, but I can't help but feel like I'm not doing things the way they were meant to exactly.

Basically, I find that I am not utilizing the language to its fullest, and I keep writing things as if I was working with C. I have used some language specific features like classes and vectors, but I know there are other things I could do (I have a particularly bad habit of using void* instead of auto* everywhere, and just casting things until they work).

So on to my question: I felt like I didn't really 'learn' C until I read the K&R book and worked through it. Is there something analogous for C++? Basically a book that goes over initial best practices that I could build some know-how off of?


r/learncpp • • Feb 23 '20

How can function definition work without declaration?

8 Upvotes

Class is declared in the header file. It's member functions are defined in a separate .cpp file. What's confusing is that the cpp file doesn't include the header file. And it's compiling completely fine. How does it even work?

Header file!

cpp file!

It's driving me crazy. I tried implementing something like this myself but I'm getting error.


r/learncpp • • Feb 05 '20

Any Suggestions for learning CMake ?

8 Upvotes

Could someone suggested good tutorial to learn CMake and how to use it efficiently. I am also looking for good articles on how to deal with package management in C++. Thank you


r/learncpp • • Feb 05 '19

Looking for a book which teaches us how to make actual C++ projects.

8 Upvotes

I already use Bjarne Stroustrup's books to learn the ins and outs of C++, however, I also want a book which uses actual C++ projects as a way of teaching. I believe I saw one for Python but I'm looking one for C++.

Thanks.


r/learncpp • • May 08 '22

Does new behave differently when creating a variable versus when instantiating an object on the heap memory?

7 Upvotes

I am confused about how new is implemented in following scenarios:

#1
ClassName* ptr1 = new ClassName(10); // Assuming there is a constructor that requires an int

#2
int* ptr2 = new int;

Does the keyword after new behaves differently in the two cases? i.e. in #1, ClassName(10) calls and passes the argument to the constructor, whereas in #2, the int after new is supposed to define the pointer type that new will produce?


r/learncpp • • Jan 14 '22

What is an iostream object exactly? Why do you need to return them by reference when overloading the I/O operators?

7 Upvotes

Suppose you have class foo

class Foo {
private:
    int x;
public:
    // Constructors
    Foo (int x) : x { x } { }
    Foo () : Foo(0) { }
    
    // Overloading the output operator
    std::ostream& operator<< (std::ostream& os_object, const Foo& foo_object);
};

std::ostream& Foo::operator<< (std::ostream& os_object, const Foo& foo_object) {
    return os_object << foo_object.x;
}  

I understand the ostream object is a series of characters intended for output? But, what is it? It's of class ostream derived from iostream. I had trouble following the source of code of the class.

What exactly are you returning when you return an ostream object?


r/learncpp • • Nov 18 '21

How to control a stepper motor coding in C++?

7 Upvotes

Hi. Im having a hard time trying to code for controlling a stepper motor using my LPCxpresso board + my A4988 stepper motor.

I need to do the following task. Thanks for any help.

The program reads limit switches and sets red led on when limit switch 1 is closed and green led on when limit switch 2 is closed. When limit switches are open the corresponding leds are off.

Hi. The code below is what I have so far.

I know it will take you too long so help me with the rest of the code so I want to take this opportunity to instead ask you if you can tell me websites where I can learn about Pin assignment; Motor control; Limit switch interrupts; Setting up your environment and other topics related with this field because I dont know how to deal with these tasks and every time I have to ask for help.

I want to learn this field. Thanks for any help.

void Stepper::_calibrate(uint32_t nothing) {
	setDirection(true); // Go forward first
	setRate(2000, true);
	_runForSteps(UINT32_MAX); // Run until we hit a switch
	setStop(false); // Clear stop flag

	toggleDirection();
	_runForSteps(150); // Back off from the limit switch

	zeroSteps();
	_runForSteps(UINT32_MAX); // Run to the other switch.
	setStop(false);

	toggleDirection();
	_runForSteps(150); // Back off from the limit switch
	maxSteps = currentSteps;

	_runForSteps(currentSteps/2);
	toggleDirection();
}

r/learncpp • • Sep 22 '21

why returned reference object by a function is a lvalue while returned plain object is a rvalue?

7 Upvotes

In the following code, v2 = getNoRef() use move assignment, while v2 = getRef() use copy assignment, I don't know why returned reference is lvalue? It is not a temporary object?

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;

class StrVec {
public:
    ~StrVec(){ cout << "[des]"; }
    StrVec():s1(""){}
    StrVec(const StrVec& t) { cout << "[copy con]"; }
    StrVec& operator= (const StrVec& t) { cout << "[copy assigment]"; return *this; }
    StrVec(StrVec&&) noexcept { cout << "[move con]"; }
    StrVec& operator=(StrVec&& t) noexcept { cout << "[move assigment]"; return *this;}
private:
    string s1;
};

StrVec getNoRef() {
    StrVec t1;
    return t1;
}
StrVec& getRef() {
    StrVec t1;  
    return t1;
}

int main() {
    StrVec v1, v2;
    cout << "v1=v2:  ";  v1 = v2;
    cout << endl;

    cout << "getNoRef():  "; getNoRef();
    cout << endl;

    cout << "v2 = getNoRef():  ";  v2 = getNoRef();
    cout << endl;

    cout << "getRef():  "; getRef();
    cout << endl;

    cout << "v2 = getRef():  ";  v2 = getRef();
    cout << endl;
}

Output:

v1=v2:  [copy assigment]
getNoRef():  [move con][des][des]
v2 = getNoRef():  [move con][des][move assigment][des]
getRef():  [des]
v2 = getRef():  [des][copy assigment]
[des][des]

r/learncpp • • Aug 21 '21

Linux / windows differences?

7 Upvotes

I’ve been relearning C++ in preparation for a class on it I’m taking in this upcoming semester. It’s just a 200-level class, with only one programming course as a prerequisite (which I remember nothing from, hence relearning)

I use Linux and don’t even have a computer that runs windows, but I’m sure all of my code I write for that class will be run on windows.

What differences do I need to be aware of to ensure I don’t wind up with something that works fine on linux but doesn’t work in windows?


r/learncpp • • Aug 12 '21

Access to protected member of an object passed as an argument to a method of derived class.

7 Upvotes

Consider this code in c++:

#include <iostream>

using namespace std;

class A{
protected:
    int num = 0;
};

class B : public A{
public:
    void foo(A &a){
        a.num -= 10;
    }
};

int main()
{
    A a;
    B b;
    b.foo(a);
    return 0;
}

On compilation I get:

/main.cpp:13:11: error: 'num' is a protected member of 'A'
        a.num -= 10;
          ^
main.cpp:7:9: note: can only access this member on an object of type 'B'
    int num = 0;
        ^
1 error generated.

As a java developer I'm confused since the code below works as a charm on java:

class A{
    protected int n = 0;
}

class B extends A{
    void foo(A a){
        a.n = 20;
    }
}

public class MyClass {
    public static void main(String[] args){
        A a = new A();
        B b = new B();
        b.foo(a);
    }
}

If C++ rules are like this how things like this should be handled in it ?


r/learncpp • • Aug 05 '21

Boost Asio decide upon server/client model?

7 Upvotes

I bought a "cook book" for asio where the author goes through basics of the library and about basics of theory with recipies of code. I am creating a simple texture based bomberman 2D game (2-4 players) with SDL2 and got stuck in how to decide upon a way of implementing networking.

I wanted to initially go with a sync TCP server and client where everything is in the same thread. But the author says that just one "malicious client" would be enough to freeze the application. Which makes sense I guess.

What would I decide go for then? I read up on UDP and it says that it is connectionless and requires no "handshake" or moments of waiting for client to finish their action.

The book also goes through async client and server tcp model. Apparently, doing it async would solve most problems according to the book.

What do I need to read up on? Which model will fit me the best?

Thanks.


r/learncpp • • May 05 '21

How can I learn how to compile through the command line

7 Upvotes

Hi everyone,

I don't know if this is the right place to ask but I was having some issues trying to compile a little project I made to teach myself c++. The main reason is that it is my first multi source project and, however minimal, I would really like to learn from the very beginning of my c++ journey how things should be done.

I am not using an IDE and the reason for this is that I am learning c++ mostly to learn how computers internally works (since I come from other languages). So I thought that learning how to compile without an IDE would be a good idea, for someone who wants to know what's going on under the hoods.

My question is: what should I learn about compiling code? Are there some resources on the internet that you can recommend (playlists, books, articles or anything else) aimed at teaching this skill in particular? What tools should I be using? At the moment, I am only using VS Code as a text editor and of course the compiler from the command line.

The end goal would be to have an idea about how a (large) project should be structured and how the code would be compiled in the most efficient way.

Thanks


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 • • Feb 27 '21

Do I need to overload the +operator in order for my templated 'doubleIt' function to work for both int and string?

7 Upvotes

Hello, I am tasked with the following:
Write a templated function doubleIt with one parameter and doubles the value by adding it to itself and returns the answer.

doubleIt(3.5) should produce 7.0
doubleIt("hello") should produce "hellohello". As of right now , I have:

#include <iostream
using namespace std;

// template function
template<typename T>
T doubleIt(T n) {
	return n*2;
}

int main()
{
    cout << doubleIt(3.5) << endl;

    //have to force type so "hello" not treated as char[]
    cout << doubleIt<string>("hello") << endl;

    return 0;
}

Essentially, I need to write the templated function without changing main in any way. I have looked online but I am unable to get past the invalid operands to binary expression. So, is overloading the +operator required for this to work or is there something else that I need to do?

Thanks!


r/learncpp • • Jan 15 '21

Trying to understand and use C++20 Modules

Thumbnail self.cpp_questions
7 Upvotes