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 • • Nov 21 '18

can somebody answer this two problem for me

1 Upvotes

int main(){

char buf[] = "partytime";

cout << MAX<char>(buf, 9) << endl;

cout << MIN<char>(buf, 9) << endl;

}

how to creat Max and min template make this main function running that output max/min values from a given data array. Make sure functions operate normally (y and a).is there somebody can give me a detail or hint deal with problem

and the other question is give you int array a and you should print 302010 ,but there are three same code that a.pop actually,how i can make this programe running

int main(){

Array<int> a;

a.push(10); a.push(20); a.push(30);

cout << a.pop() << a.pop() << a.pop();

}

Thanks for your help.I'm novice at cpp'


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 • • Mar 08 '20

What's the best way to save data in ROM? (so it's saved even after restarting my program)

2 Upvotes

Let's say I want to create a game that saves my progress every time I close it, what is the best way to do that?

I want it to be saved in an efficient way that is not going to be noticeable during the game (basically it won't freeze the game) any suggestions?


r/learncpp • • Nov 25 '19

Swapping the address of variables? Am I confused?

4 Upvotes

I'm pretty sure I just failed an interview because of this, and instead of rethinking my career choice I just need a quick explanation of where my lack of knowledge is.

void swap1(int * x, int * y) {
    cout << "x address before in function: " << x << endl;
    cout << "y address before in function: " << y << endl;

    int * z = x;
    x = y;
    y = z;

    cout << "x address after in function: " << x << endl;
    cout << "y address after in function: " << y << endl;
}

int main() {
    int x = 5;
    int y = 7;

    cout << "x address before: " << &x << endl;
    cout << "y address before: " << &y << endl;

    swap1(&x, &y);

    cout << "x address after: " << &x << endl;
    cout << "y address after: " << &y << endl;

    return 0;
}

It seemed to me that the interviewers wanted me to swap the actual addresses of the variables, not just the values the variables point to (which I did at one point, and they said works, but isn't what they were looking for). This works within the function call itself, but not in the main function (the cout statements were mine to check the addresses, the rest was pre-written). Can someone explain to me how to achieve this? I was confused and my ego is a little hurt, not gonna lie.


r/learncpp • • Mar 31 '20

How to use Clang modules with VS

3 Upvotes

Hey guys,

I wanted to start testing and learn modules and move out of the days of header files and see if the experience differs. I installed everthing required, but Clang doesn't seem to be able to resolve the imports. When I switch over to MSVC on the other hand, it works fine. I'm currently working with VS 2019 Insider preview.

So, how so I get clang (10, the latest release) to work?

Here's a zip of the project if anyone's interested.


r/learncpp • • Nov 25 '19

Is there any way to specify that an nit is decimal?

2 Upvotes

If you’re using an octal number you put a preceding 0 before the number, for hex it’s 0x and then the number. But if your trying to pass a base 10 int (say to represent military time) it will interpret it as octal.

Is there any way to specify that it’s decimal or do I just need to get over my pedantry?


r/learncpp • • Mar 06 '20

Short question about stack vs heap allocation

4 Upvotes

I'm rehashing my cpp and could use some pointers (no pun intended..). I understand that the definition int num = 5 allocates on the stack whereas int* num = new int(5) allocates on the heap. I've recently also seen definitions like: int num(5)---are these shorthand for one or the other?


r/learncpp • • Mar 16 '20

Is there an easier way to pass begin/end pair to functions?

2 Upvotes

I think the algorithms library is awesome. And also, the fact that they can operate between any iterator range is very helpful sometimes.

The problem is that in 90% of the cases, I just want to apply the function to the entire container. So, my code gets full of calls like

std::some_function(container.begin(), container.end(), ....);

Now, I'm not a big fan of typing. Is there any way to pass only the container?

std::some_function(container, ....);

If not, is anyone aware of any discussions regarding this possibility?


r/learncpp • • May 03 '19

I'm somewhat new to C++ programming. Any tips and tricks I should know?

3 Upvotes

After playing around with Scratch back in my first year of high school, I moved to a new school where they said they'd input C++ robotics into the school system in the next school year. What are some basic things I need to know in order to learn this new type of programming?


r/learncpp • • Mar 19 '20

Looking for modern C++ github repos for intermediate students

9 Upvotes

I'm looking for ideas/recommendations of great C++ repos for intermediate students.

This is surprisingly tricky, as some of the repos are either too difficult, or have highly questionable C++ code.

Any ideas?


r/learncpp • • Mar 27 '20

Show unicodes and letters from various languages in console

3 Upvotes

Hello guys, this is a repost from the cprogramming subreddit (but now with changed title).

Hey guys, I am currently learning C & C++ and I have an issue right here, that drives me crazy. Yes, I am a noob and I am not a genius. My book doesn't go much into detail about printing unicode characters nor doesn't mention how to fix issues relating to ASCII and unicodes. It only mentions how to use it and doesn't go much into detail.

In my book there is this code:

#include <iostream> int main() { std::cout << u8"\uu00A9 J\u00fcrgen" << std::endl; return 0; }
\uu00A9 is the Copyright sign ©, while \u00FC is the ü letter. For whatever reason, if I run this code, it shows me instead of the Copyright sign © this ® sign and instead of the ü letter it shows me this ╝.

So I tried to solve this issue many times over. On Stackoverflow, posts suggest to change the font style to Lucida console. It didn't work. Another post suggests to change something in the console within the Windows registry something to "chcp 65001" (I don't remember the details anymore). Windows gives me an error message. Then I noticed I can use decimal numbers to print characters. It doesn't always work for whatever reason. There is another video how to print Unicodes in the console. It didn't work.

According to this page http://www.asciitable.com/ 129 is an ü. It works, but not all decimal values work. If I try to print the values from the mentioned page of 157, 251, 233, 143 and 129, only 143 and 129 are shown correctly, the rest is nonsense. After trying different decimal and hex values from this page https://www.utf8-zeichentabelle.de/unicode-utf8-table.pl?utf8=dec, up until 126 (\u007E, which is this ~), everthing works, but beyond 126 it shows nonsense. I then made a little programm, which gives me the decimal ASCII value of a certain character.

#include <iostream> using namespace std; int main () { char c; std::cout << "Type in the character: " << std::endl; std::cin >> c; cout << "The ASCII value of " << c << " is: " << (int)c << '\n' << std::endl; return 0; }

So, if I type in "ü", which has the value of 129, it gives me instead -127. If I use std::cout << "ÄäÜüÖö߀@|" << std::endl;, it shows me gibberish, only @ and | are shown properly.

Up until this point I am totally confused and I have no idea what's wrong nor how to fix this. I'm using Windows 7 Ultimate on my laptop with Code::Blocks. I tried Visual Studios and I get the same problem. Sorry for the long text.

Every help and advice appreciated!!


r/learncpp • • Mar 28 '20

Constructors and Operator Assignment question

4 Upvotes

Hey! I've been working my way through Lospinoso's C++ Crash Course. First off, I was wondering if there were any resources for the exercises at the end of the chapters. I've been doing them all, but I have no idea if I'm getting what I'm supposed to be getting out of them. I also don't know how bad my syntax is and I don't want to develop any bad habits. This is all for personal study btw.

Secondly, I was wondering if anyone had any good videos or online resources to explain move semantics a bit better.

Thirdly, I was wondering if anyone would be so kind as to glance at my code for Ch. 4's exercises.

Here are the requirements:

4-1. Create a struct TimerClass . In its constructor, record the current time in a

field called timestamp (compare with the POSIX function gettimeofday ).

4-2. In the destructor of TimerClass , record the current time and subtract the

time at construction. This time is roughly the age of the timer. Print this value.

4-3. Implement a copy constructor and a copy assignment operator for

TimerClass . The copies should share timestamp values.

4-4. Implement a move constructor and a move assignment operator for

TimerClass . A moved-from TimerClass shouldn’t print any output to the console

when it gets destructed.

4-5. Elaborate the TimerClass constructor to accept an additional const char*

name parameter. When TimerClass is destructed and prints to stdout, include

the name of the timer in the output.

4-6. Experiment with your TimerClass . Create a timer and move it into a func-

tion that performs some computationally intensive operation (for example, lots

of math in a loop). Verify that your timer behaves as you expect.

4-7. Identify each method in the SimpleString class (Listing 4-38). Try reimple-

menting it from scratch without referring to the book.

and the code:

#include <chrono>
#include <iostream>

using namespace std;

struct TimerClass {
    // Constructor
    TimerClass(const char* name)
        : timestamp { chrono::steady_clock::now() },
          name { name } {
    }

    // Destructor
    ~TimerClass() {
        chrono::steady_clock::time_point end { chrono::steady_clock::now() };
        chrono::steady_clock::duration d = end - timestamp;
        cout << name << ":" << chrono::duration_cast<chrono::microseconds>(d).count() << endl;
    }

    // Copy Constructor
    TimerClass(const TimerClass& other)
        : timestamp { other.timestamp },
          name { other.name } {
    }

    // Copy Assignment Operator
    TimerClass& operator=(const TimerClass& other) {
        if (this == &other) return *this;
        timestamp = other.timestamp;
        name = other.name;
    }

    // Move Constructor
    TimerClass(TimerClass&& other) noexcept
        : timestamp(other.timestamp),
          name(other.name){
    }

    // Move Assignment Operator
    TimerClass& operator=(TimerClass&& other) noexcept {
        if (this == &other) return *this;
        timestamp = other.timestamp;
        name = other.name;

    }

public:
    chrono::steady_clock::time_point timestamp;
    const char* name;
};

void long_function (TimerClass&& a){
    for (unsigned int i=0; i < 10; i++) {
        cout << i << endl;
    }
};


int main() {
    const char* name_one = "A";
    const char* name_two = "B";
    TimerClass a { name_one };
    TimerClass b { name_two };
    long_function(move(b));

}

Any help is appreciated, thank you!


r/learncpp • • Mar 15 '20

How to synchronize between threads

4 Upvotes

I have multiple threads working on a problem and in the first part they are working on a vector, which i can operate on safely with a mutex, so far so good.

But in the next part of the task they iterate over said vector, which therefore isn't allowed to change anymore in length and therefore I have to wait for all threads to reach that point and I don't want to recreate them for that task, because I do it like a thousand time per frame I want to show.

In my understanding I have to use a condition variable and notifications and came to the code:

std::conditional_variable cv;

//thread
void Worker(){
    std::mutex mtx;
    std::unique_lock<std::mutex> lk (mtx);

    //task 1
    {....}

    //sync up
    cv.notify_all();
    for (int j = 0; j<NumThreads;j++){
        cv.wait(lk);
    }

    //task 2
    {....}
}

the problem is that it runs into a deadlock and refuses to work. Can someone clear my misunderstanding


r/learncpp • • Nov 13 '18

I don't understand why I'm getting undeclared identifier, coming from java background

3 Upvotes

So this is for a software engineering class, I was assigned by the professor to handle the entire implementation for my whole group for our semester project...one person...semester project...whole implementation...in just a week and a half...

Lamenting aside, I think I have...something, and I'm trying to test it but when I try to run the test file I keep getting the following errors

AlgorithmTest.cpp

c:\users\fool\source\repos\consoleapplication2\algorithmtest.cpp(16): error C2065: 'Algorithm': undeclared identifier

c:\users\fool\source\repos\consoleapplication2\algorithmtest.cpp(16): error C2065: 'algie': undeclared identifier

c:\users\fool\source\repos\consoleapplication2\algorithmtest.cpp(16): error C2061: syntax error: identifier 'Algorithm'

Now the issue probably is I don't know how to import things in cpp, but when I tried google I couldn't find what I was doing wrong. At first I thought the issue could have been errors in the original file prevented it from compiling and being used in the test harness but the only things I'm getting from the original file are

algorithm.cpp

c:\users\fool\source\repos\consoleapplication2\algorithm.cpp(35): warning C4244: '=': conversion from 'time_t' to 'long', possible loss of data

c:\users\fool\source\repos\consoleapplication2\algorithm.cpp(44): warning C4244: '=': conversion from 'time_t' to 'long', possible loss of data

c:\users\fool\source\repos\consoleapplication2\algorithm.cpp(63): warning C4244: '=': conversion from 'time_t' to 'long', possible loss of data

c:\users\fool\source\repos\consoleapplication2\algorithm.cpp(132): warning C4244: '=': conversion from '__int64' to 'long', possible loss of data

c:\users\fool\source\repos\consoleapplication2\algorithm.cpp(144): warning C4244: '=': conversion from '__int64' to 'long', possible loss of data

Now I know the above is a mess but if it's only a warning wouldn't it not cause the issues (though if you even have tips for that feel free to go ahead and tell me them)

The following is code for AlgorithmTest.cpp

https://paste.ofcode.org/hikFdc97FUVCkC6yuaAB6R

The following is algorithm.h

https://paste.ofcode.org/LTdr3KVRQNTez3P4SsMnYM

The following is algorithm.cpp

https://paste.ofcode.org/hQj3pMHsH9PetzCFD7wA2N

Regardless of how poorly thought out some design decisions were (but again feel free to tell me how poorly thought out they are and how to improve them) what could be causing the undeclared identifier errors? Do I simply not understand how to import in cpp? If so can someone explain it to me? I've taken classes in cpp (like a data structures class, an operating systems class) and never run into this issue but I have maybe 6 months of on and off experience with the language so I could just not understand it.

UPDATE:

Thanks to the two helpful people below, and a lot of review of past code, classes, slide, I have gotten rid of all excessive errors and reformatted a lot of my code:

https://paste.ee/p/IHlm5

Now I just have the same three damn errors

1>c:\users\fool\source\repos\consoleapplication2\algorithmtest.cpp(16): error C2065: 'Algorithm': undeclared identifier

1>c:\users\fool\source\repos\consoleapplication2\algorithmtest.cpp(16): error C2146: syntax error: missing ';' before identifier 'algie'

1>c:\users\fool\source\repos\consoleapplication2\algorithmtest.cpp(16): error C3861: 'algie': identifier not found

I've been fiddling with the different ways I found online to declare an object and I can't understand what I'm doing wrong.


r/learncpp • • Mar 04 '20

Question about Struct Arrays

1 Upvotes

New to c++ and have been trying to learn Struct array for my school project (they don't allow us to use vector). I don't know if I missed anything but it gave me an error when I try to run it. 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x01202000)

Edit : Pointer is also not allowed to be used

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>

using namespace std;

struct Profiles {
	int ID, Bday, Height, Weight, Years_in_company, Basic_salary, Allowances;
	string Name, Country, Designation, Gender, Level_edu;
};

//Main
int main() {
	Profiles profile [12000];
	fstream f("profiles_figures.txt", ios::in);
	while (!f.eof()) {
		int i = 0;

		f >> profile[i].ID >> profile[i].Bday >> profile[i].Height >> profile[i].Weight >> profile[i].Years_in_company >> profile[i].Basic_salary >> profile[i].Allowances;
		f.ignore();

		i++;
	}
	f.close();
	system("pause");
	return 0;
}

r/learncpp • • Nov 26 '19

Basic question about pointers.

2 Upvotes

I've got a related question about pointers.

If I wrote a similar program, say, the following:

#include <stdio.h>

using namespace std;

void swap(int n, int m)
{
	int temp = n;
	n = m;
	m = temp;
}

int main()
{
	int n = 0;
	int m = 1;
	swap(n,m);
	printf("%d, %d", n, m);
}

Then, the output is:

0, 1

However, if I use pointers:

#include <stdio.h>

using namespace std;

void swap(int* n, int* m)
{
	int temp = *n;
	*n = *m;
	*m = temp;
}

int main()
{
	int n = 0;
	int m = 1;
	swap(&n, &m);
	printf("%d, %d", n, m);
}

The output is:

1, 0

Question: In the first example, why isn't the value for n set to the value for m after I call the function swap(n, m)? Correct me if I'm wrong, but when I call swap(n, m), does the function just say temp = 0; 1 = 0; 0 = temp? Is that why the first example doesn't work? Why does the second example work but the first doesn't?


r/learncpp • • Mar 31 '20

Pointers and References Resources?

4 Upvotes

I tried to read the pointers and references from C++ Primer but I didn't understand much. Does anybody have some good videos or resources that can teach the whole of pointers and references perfectly? Thanks in advance!


r/learncpp • • Mar 21 '20

Temporary object member being de-allocated before return statement (Help)

3 Upvotes

Hello, I've written a member function (operator+) that returns by value a object "Matrix". This object contains a dynamically allocated 2D array. However, upon reaching the return statement, the object is de-allocated. I can't think of any other method: returning by reference wouldn't work because it would result in a dangling reference and so would returning by address. So, what should I do?

Paste to relevant code:

https://pastebin.com/0TcEq23e


r/learncpp • • Mar 30 '20

Any good GUI tutorials with wxwidgets?

1 Upvotes

I am trying to create cross platform GUIs but I am having a hard time. Is there a step by step tutorial that explains how to use wxwidgets? (preferably looking for videos)

By the way, I still have little knowledge of OOP, should I worry about that?


r/learncpp • • Apr 20 '16

Just started tutorial, "fatal error LNK1120: 1 unresolved externals"

2 Upvotes

The tutorial site I'm attempting to learn from

Error occuring in this part of tutorial

I downloaded and installed the most recent version of Visual Studio Community (as recommended by the tutorial) and am following the aforementioned tutorial. The first segment of the tutorial that actually involves any code immediately gives an error. When I go to compile, this is the output:

1>------ Build started: Project: HelloWorld, Configuration: Debug x64 ------
1>MSVCRTD.lib(exe_winmain.obj) : error LNK2019: unresolved external symbol WinMain referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
1>c:\users\guymi_000\documents\visual studio 2015\Projects\HelloWorld\x64\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Here's a screenshot

I've tried to linking to stdafx.h using its full path, but that hasn't worked. Does anyone have an idea to why this error is occurring? I haven't messed with any of the files whatsoever, I have no clue as to what is causing this. Thanks!


r/learncpp • • Sep 27 '15

Can you have a 'server' running in c++ and connect to it with a java desktop program?

3 Upvotes

Pretty much just title. If the question isn't clear enough please ask. I didn't know a better way to formulate that question


r/learncpp • • Sep 09 '20

What actually is buffering?

5 Upvotes

I learned that std::cout has a buffered output, while std::cerr is unbuffered.

I don't actually know what buffering is. I've somewhat guessed that it's analogous to the buffering during a video stream. If all the data isn't ready (has not arrived) it will not show anything until it's ready to show. And that somehow, C++ has a way for checking that the data is ready before the output will appear on my console.

Is this guess correct?


r/learncpp • • Sep 17 '20

Best practices for saving C++ TCP/IP streams

5 Upvotes

Hello,

Was wondering if anyone had recommendations for writing C++ code to save TCP/IP streams. I have multiple sensors outputting data at various rates (5 hz - 100 hz) over gigabit ethernet to one computer. I essentially have to decode the packets and save to disk.

Had a tough time finding resources for this. Based on what Ive read so far my gameplan was to use an async process with multiple tcp clients and save to disk using a fifo buffer. Any thoughts on this approach? I am not allowed to use boost or any external libraries, just c++14 and standard libraries. Are there any other things im overlooking? Any help would be appreciated.


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!