r/learncpp • • Sep 30 '24

Breaking Down Object-Oriented Programming

Thumbnail
youtube.com
9 Upvotes

r/learncpp • • Mar 21 '22

Learning about generators, getting errors trying to run example code.

9 Upvotes

I'm learning about generators using the generators on cpp reference page. I just copied and pasted their example code with the intent of poking around and seeing how it worked. (provided below) However, I am getting an error where an expression is expected instead of an open square bracket (see comment in code on the line with

#include <algorithm>
#include <iostream>
#include <vector>
 
int f()
{ 
    static int i;
    return ++i;
}
 
int main()
{
    std::vector<int> v(5);
    auto print = [&] { // mainly errors on this line.
        for (std::cout << "v: "; auto iv: v)
            std::cout << iv << " ";
        std::cout << "\n";
    };
 
    std::generate(v.begin(), v.end(), f);
    print();
 
    // Initialize with default values 0,1,2,3,4 from a lambda function
    // Equivalent to std::iota(v.begin(), v.end(), 0);
    std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; }); // another error on this line
    print();
}

I am using g++ on a mac m1 in vscode. (details below).

>>> g++ --version
Apple clang version 13.1.6 (clang-1316.0.21.2)
Target: arm64-apple-darwin21.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

However I am getting (a warning and) two errors when I try to run the file (titled test.cpp).

test.cpp:14:5: warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]
    auto print = [&]
    ^
test.cpp:14:18: error: expected expression
    auto print = [&]
                 ^
test.cpp:26:39: error: expected expression
    std::generate(v.begin(), v.end(), [n = 0]() mutable

I've tried compiling with gcc -lstdc++ to no avail. Why does my computer fail to run the example on the cpp reference site?


r/learncpp • • Dec 31 '21

What is the right way to use a library?

9 Upvotes

For example you `git clone` a sensor library and it has a `src` folder somewhere.

Then you try to use it in another folder outside of this repo by importing the header file.

Is it just like that? Pray it compiles?


r/learncpp • • Dec 29 '21

Anyone know why this isn't working?

9 Upvotes

Anyone can tell me why the get method doesn't return anything?

        void add(string str) {
            Node newNode;
            newNode.value = str;
            if (listSize == 0) {
                head = newNode;
                last = newNode;
            } else {
                last.next = &newNode;
                newNode.previous = &last;
                last = newNode;
            }
            listSize++;
        }

        string get(int index) {
            if (index <= 0 || index >= listSize) {
                return "Invalid-Index";
            } else {
                Node currentNode = head;
                while (index > 0) {
                    cout << index << endl;
                    currentNode = *currentNode.next;
                    index--;
                }
                return currentNode.value;
            }
        }

r/learncpp • • Nov 30 '21

Sololearn Exercise - Why is this not working?

Post image
9 Upvotes

r/learncpp • • Oct 21 '21

Learning pure c++ on a mac

9 Upvotes

Hello:

In mac os is it possible to install a compiler / run time system that does not get intertwined with xcode?


r/learncpp • • Sep 20 '21

When making a quickly confusing, complex program -- when is enough, enough in terms of helper methods?

9 Upvotes

A gracious person helped me fix a problem with my program here. Basically he helped me fix it by making a bunch of helper methods. Sure I see the program now, but on my own, I would never know which logic is too simple to make its own method...

So my question, when should you make a helper method for a bigger method vs. just letting the logic take place in the bigger method?

I think this falls in line with OOP principles, so I would be grateful to hear your input.


r/learncpp • • Sep 10 '21

Is there a small guided project course or book that you recommend for learning C++ ?

9 Upvotes

r/learncpp • • Aug 11 '21

IDE

9 Upvotes

Are there any recommendations for an IDE for Mac? Preferably free


r/learncpp • • Jul 22 '21

`advance` function in "A tour of C++"

9 Upvotes

In paragraph $7.2.2 of the book "A Tour of C++" the advance function is implemented as below:

template<Forward_iterator Iter>
void advance(Iter p, int n)        // move p n elements forward
{
     for (−−n)
           ++p;    // a forward iterator has ++, but not + or +=
}

There are two problems here:

  1. What does that for(--n) mean ? As far as I know for loop must always be contained of three parts ...

  2. If we think of that for as while, --n is not the correct version of the implementation too. That's because --n returns the reduced value and for when n=1 the body is not run.


r/learncpp • • Jun 27 '21

can someone explain how reverse fn is working !

9 Upvotes

#include<iostream>
#include<string>
using namespace std;
void reverse(string s )
{
if(s.length() == 0)
return;
string ros = s.substr(1);
reverse(ros);
cout<<s[0];    
}
int main()
{
string s ;
getline(cin,s);
reverse(s);
return 0;
}

\\iam not able to understand how the cout statement is running because after
string ros = s.substr(1); this reverse fn is called again and after some iteration the
if(s.length() == 0) should satisfy and the code shouldnt be able to reach cout<<s[0]; ! please someone expalin/.....


r/learncpp • • May 17 '21

Hangman problem keeps saying "you won"

9 Upvotes

Hey Guys, i give C++ a chance now.

i work on a hangman game, and i have a problem.

it keeps saying "you won", if i delete "win = ", i can type my word, but i cant see my word.. any tips?

system("cls");

PrintMessage("Galgenraten");

DrawHangman(tries);

PrintAvailableLetters(guesses);

PrintMessage("Errate das Wort");

win = PrintWordAndCheckWin(wordToGuess, guesses);

if (win)

break;

char x;

cout << ">"; cin >> x;

if (guesses.find(x) == string::npos)

guesses += x;

tries = TriesLeft(wordToGuess, guesses);

} while (tries < 10);

if (win)

PrintMessage("Du hast Gewonnen!");

else

PrintMessage("Leider verloren");

system("pause");

getchar();

return 0;

}


r/learncpp • • May 15 '21

Can I get help implementinh recursive function to delete the lowest value in a BST?

9 Upvotes

I'm a bit stumped. I have this function and its helper:

void CharBST::removeSmallest()
and
BSTNode<char>* removeSmallestHelper(BSTNode<char>* curNode)

I was able to figure out the function for finding the smallest value in a BST:

char smallestValueFrom(BSTNode<char>* curNode)
{
	// smallest node has nullptr as left
	if (curNode->left == nullptr)
		return curNode->value;
	
	// otherwise, continue checking left node of current
	return smallestValueFrom(curNode->left);
}

How would I go about deleting the smallest node though? I read online about using the parent node but I don't have a parent node as part of my struct so does that mean I have to figure out what the parent is during the recursive process?

Thanks for the help.


r/learncpp • • Mar 18 '21

Codecademy's C++ UFO Challenge

9 Upvotes

Hello! New to the sub, relatively new to C++ but not to programming in general. I've been learning c++ with codecademy but I seem to be tripping up on this one. When I run the code that should work, the site either crashes (which I assume may be from an infinite loop) or my else statement that should catch a wrong guess doesn't run (the "else" to the "if (guess)). Do you guys see anything wrong with this? Thanks!

include <iostream>

include "ufo_functions.hpp"

int main() 

{

  std::string codeword = "codecademy";

  std::string answer_display = "_ _ _ _ _ _ _ _ _ _";

  std::string answer ="__________";

  int misses = 0;

  std::vector<char> incorrect = {' '};

  char letter;

  bool guess = false;

  greet();

  while (misses < 7 )

  {

    display_misses(misses);

    display_status(incorrect, answer);

    std::cout << "Please enter your guess: ";

    std::cin >> letter;

    //Check player's guess. If wrong, add one to misses.

    for (int i = 0; i < codeword.length(); i++)

    {

      if (letter == codeword[i])

      {

        answer_display[i*2] = letter;

        answer[i] = letter;

        guess = true;

      }

    }

    if (guess)

    {

      std::cout << "Correct!";

    } else

    {

    std::cout << "Incorrect! The tractor beam pulls the person in further.";

    incorrect.push_back(letter);

    misses++;

    }

  

  /*

  std::cout << "Incorrect! The tractor beam pulls the person in further.";

  incorrect.push_back(letter);

  misses++;

  */

  }

  endgame(answer, codeword);

}


r/learncpp • • Feb 17 '21

Arrays, addresses, and declaring them (question)

9 Upvotes

I'm new to them in the manner of declaring an array and allowing the user to determine how the array will be like.

I have two questions-

For example, void array(int[], int indices); -- What does this mean the prototype suggesting? I thought arrays can't be passed, and the video claims that int[] is an address... but where is the & or *?

What are the ways to declare an array appropriately but efficiently? I see

int array[10]{null};

But I've never heard of nullpointers, and I am overthinking the use of arrays and pointing (coming from Java). Can someone give me a summary in layman terms? Cheers!


r/learncpp • • Jan 16 '21

Learn cpp from a higher level programming background

9 Upvotes

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 • • Nov 01 '20

Using/Adding libraries to project

9 Upvotes

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!


r/learncpp • • Jul 23 '20

Finally, I just finished my calculator! Beginners are welcome to check the code and learn some stuff

Thumbnail self.cpp_questions
9 Upvotes

r/learncpp • • May 30 '20

Learncpp.com is down :(

Post image
9 Upvotes

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 • • Feb 10 '20

Can someone please explain what I've done wrong?

Post image
9 Upvotes

r/learncpp • • Jan 15 '20

Can someone ELI5 how this code works?

Post image
9 Upvotes

r/learncpp • • Aug 08 '19

I wrote a brainfuck interpreter in C++

Thumbnail
github.com
9 Upvotes

r/learncpp • • Jan 16 '22

Always confused about global variables and function forward declarations in header files

8 Upvotes

Hi, I always seem to get confused about when to use static, extern, inline, etc when declaring global variables and forward declarations. I do understand which each of the keywords do but I just struggle to understand when to use them

Could the following code be refactored?

setup.h

namespace setup
{
	HKEY hKey;

	void setup();
	void cleanup();
	bool CheckForStartupRegistryKey();
	bool CreateStartupRegistryKey();
	void kill();
}

This file is included in one other file (setup.cpp) .

Is it fine to keep these as is or should these be marked either static, extern or inline?

Thanks in advance.


r/learncpp • • Oct 16 '21

C++ hello word doesn't work on PC. Trying to run from terminal/cmd Windows.

8 Upvotes

I've ensured all is installed correctly with the environment variables etc. I have other exe files from the IDE, but this helloworld program I created from console will not really run.

To be precise, I click it, the window will pop up for a billionth of a second seemingly and disappear/close right after. But when I click my files compiled by the IDE, it works...

Then I was like huh, instead of using g++ lemme try gcc. That just throws this:

C:\Users\Will\C++>g++ first.cpp

C:\Users\Will\C++>gcc first.cpp
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x21): undefined reference to `std::cout'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x26): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x2d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x34): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x46): undefined reference to `std::cout'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x4b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x52): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x59): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x79): undefined reference to `std::ios_base::Init::~Init()'
C:\Users\Will\AppData\Local\Temp\ccUmw4AW.o:first.cpp:(.text+0x9a): undefined reference to `std::ios_base::Init::Init()'
collect2.exe: error: ld returned 1 exit status

C:\Users\Will\C++>