r/learncpp • • Jan 01 '25

std:: Vs using namespace std. || #pragma once Vs #ifndef #define #endif

3 Upvotes

This is a question with one aim: What is the route to develop healthy practices and professional like code manners in C++.

I have been using `using namespace std;` you can guess the level, and fine so far with the very small program exercises I do, however everyone who saw an exercise I shared was like wtf, all have commented the same about it almost.
Therefore, is the healthy professional practice to use std:: ?
What about being selective and only do `using std::cout` and `std::cin` at least as these tend to occur a lot? What are the consequences of that. Forget about small programs, what are the consequences in mid sized programs.

Second `#pragma once Vs #ifndef #define #endif` ;
While I do not mind using each, since at this stage I am not creating any significant code. Reading about them gets me back to the same thing; both are valid and even some people tend to say `#pragma once` is better and safer. I cannot judge that claim from where I am standing.

Therefore, what do professionals use? What is the healthiest one of them?

Thank you community.


r/learncpp • • Apr 08 '22

How to check if an object can be cast to string?

3 Upvotes

What is the most concise, clean, and modern C++ way to check if an object can be cast to a std::string?

for example const char * can be cast to the std::string but bool can't. You get the point


r/learncpp • • Mar 27 '22

Is this book too outdated to learn from? Just starting out.

Thumbnail
amazon.com
3 Upvotes

r/learncpp • • Jul 22 '21

ncurses wont work with vscode i believe I've tried everything

3 Upvotes

first, the problem arose when i tried to make a cpp game but the tutorial showed it with the conio.h file which is something macOS devices apparently cant run. i tried using dummy header files but the conio.h file contained even more headers and it seemed like it would take forever to track down what I needed. then I found ncurses and after about an hour of trying to download the library I got it through homebrew but VSCode won't run some the snake game with ncurses stuff in it. is there any game-friendly input stuff like ncurses that already comes with every macOS device? it seems like every solution is unavailable to me because of the OS. Ive tried editing the path of where the ncruses library is saved even putting it in the same folder as the snake game file and nothing works. I included a screen capture in case it helps

ps. I've also realized for some reason XCode wont run anything. The Run thing is grayed out and when I do cmd+R it does the annoying beep shit pls help. I'm not logged into git hub which apparently causes problems and everything else for xcode seems fine just half my commands do nothing.


r/learncpp • • Apr 18 '21

Linked List Copy Constructor last index not copying over?

3 Upvotes

Hello, I have a bug that I cannot track down so hopefully someone can help me find it? I've been looking at a lot of online resources over linked lists and I have all but the copy constructor and and assignment operator done. As the title suggests, the last value of my original list isn't copied over and I cannot figure out why. Care to take a look?

I am using a templated struct:

template <class T>
struct ListNode
{
    T data;
    ListNode* next;

    static int nodeCount;

    ListNode(const T& value) {
        data = value;
        next = nullptr;
        nodeCount++;
    }

    ~ListNode() {
        nodeCount--;
	}
};

And this is the copy constructor that I have:

template <class T>
LinkedList<T>::LinkedList(const LinkedList<T>& other) {

	// check empty
	if (other.head == nullptr) {
		head = tail = nullptr;
		return;
	}

	ListNode<T>* current = nullptr;
	ListNode<T>* temp = other.head;

	head = new ListNode<T>(temp->data); // constructor takes in data value as param
	head->next = nullptr;
	current = head;

	temp = temp->next;

	while (temp != nullptr) {
		current->next = new ListNode<T>(temp->data);
		current = current->next;
		current->next = nullptr;
		temp = temp->next;
		length++;
	}
}

Any help highly appreciated.


r/learncpp • • Feb 27 '21

HW Help: Not sure what return type should be for templated function.

3 Upvotes

Hello, thank you for being a community as I struggle to learn c++. It's been rough having to take it online during a pandemic and while working through power outages. My entire college closed down so I am essentially without my professor. Okay, now that my sob story is out of the way (you guys rock!):

I am learning about templated functions but I am a little confused on what my return type should be. The question reads, "Write a templated function sumList that will take in an array of any type and the length of the array. It should add all the elements in the array and return the total.
Hint: you can declare a variable sum of type T and initialize it like this:
T sum {}; "

Does that mean that sum is going to be an array? That's what I do not understand. I currently have:

#include <iostream>
using namespace std;

template<typename T>
T sumList(T array, int n) {
	T sum {};
	for (int i=0; i<n; i++) {
		sum = array[i];
	}
	return sum;
}

int main()
{
	int nums[] = {4, 2, 8, 7};
	string words[] = {"hello", "there"};

	cout << sumList(nums, 4) << endl;
	cout << sumList(words, 2) << endl;

	return 0;
}

But that of course has the error: main.cpp:8:9: error: assigning to 'int *' from incompatible type 'int'; take the address with &

Can someone please help point me in the right direction? I am not allowed to change main. I am only allowed to write the templated function.


r/learncpp • • Feb 12 '21

Does std::vector have any quirks that change its behavior that prevent reinterpret_cast on it?

3 Upvotes

frame rainstorm rob coherent grab fine hobbies special towering wine

This post was mass deleted and anonymized with Redact


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

Static templated vectors inside class header files?

3 Upvotes

Can it be done? because of the vector being static and in the actual class definition in the header file, there are loads of linking errors, and im not sure how to really get around it.


r/learncpp • • Oct 20 '20

"Competitive" programming site, but for design pattern?

3 Upvotes

As title says, do you know any site that challenges/helps you to code your own version of containers, smart pointers, etc, for the sake of learning?


r/learncpp • • Oct 09 '20

Checking if a Clang::Type can be cast to another

Thumbnail self.cpp_questions
3 Upvotes

r/learncpp • • Sep 02 '20

Clang-Tidy: Operator=() does not handle self-assignment properly

3 Upvotes

this is my code , CLion give me this warning on operator= implementation what is wrong and why it doesn't handle it correctly

template <class Type>
class StackType
{
private:
    int maxStackSize, stackTop;
    Type * list;
    void copyStack(const StackType<Type> &);
public:
    const StackType<Type>& operator=(const StackType<Type>&);
    bool isEmptyStack() const ;
    bool isFullStack() const ;
    void push(const Type&);
    void pop();
    Type top()const;
    StackType(int);
    StackType(const StackType<Type>&);
    ~StackType();
};

template <class Type>
void StackType<Type>::copyStack(const StackType<Type>& otherStack)
{
    delete[]list;
    maxStackSize = otherStack.maxStackSize;
    stackTop = otherStack.stackTop;
    list = new Type[maxStackSize];
    for (int j = 0; j < stackTop; j++)
        list[j] = otherStack.list[j];
}


template <class Type>
const StackType<Type>& StackType<Type>::operator=(const StackType<Type> &otherStack)
{
    if (this != &otherStack)
        copyStack(otherStack);
    return *this;
}

r/learncpp • • Aug 15 '20

Help starting out

3 Upvotes

What math should I master before I start? Details and depth would be really appreciated.


r/learncpp • • Jul 31 '20

dev c constantly crashing?

3 Upvotes

hello im starting learning c programming and decided to use dev c but i always notice that it constantly hangs every minute or so no matter how simple or compex my code is and its making my time inefficient. i don't know why this is. can this be fixed? im using a laptop with an i5 8250u and mx150 with 12 gb ram


r/learncpp • • Jul 14 '20

Dev C++ I cannot link libraries...

3 Upvotes

I am trying to use curlpp and have downloaded the .zip version which I extracted... but I am extremely confused with how linking works... I come from a python background where linking was pretty much automated once you downloaded the library...

could someone explain me step by step how to link properly? thanks...

(googled a lot before deciding to post here...)


r/learncpp • • Jul 09 '20

Transform recursive function into an iterative function

3 Upvotes

I have a sample function -

template <typename T>
void foo(
        T** tocarry,
        int64_t* toindex,
        int64_t* fromindex,
        int64_t j,
        int64_t stop,
        int64_t n,
        bool replacement) {
    while (fromindex[j] < stop) {
        if (replacement) {
            for (int64_t k = j + 1; k < n; k++) {
                fromindex[k] = fromindex[j];
            }
        }
        else {
            for (int64_t k = j + 1; k < n; k++) {
                fromindex[k] = fromindex[j] + (k-j);
            }
        }
        if (j + 1 == n) {
            for (int64_t k = 0; k<n; k++) {
                tocarry[k][toindex[k]] = fromindex[k];
                toindex[k]++;
            }
        }
        else {
            foo<T>(tocarry,
                    toindex,
                    fromindex, j + 1,
                    stop,
                    n,
                    replacement);
        }
        fromindex[j]++;
    }
}

I want to translate the above recursive into its equivalent iterative form.

I have a sample test case, which can be invoked like -

int main() {
    std::vector<int64_t*> tocarry;
    int64_t bla1[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla2[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla3[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla4[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla5[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla6[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla7[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla8[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla9[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t bla10[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    tocarry.push_back(bla1);
    tocarry.push_back(bla2);
    tocarry.push_back(bla3);
    tocarry.push_back(bla4);
    tocarry.push_back(bla5);
    tocarry.push_back(bla6);
    tocarry.push_back(bla7);
    tocarry.push_back(bla8);
    tocarry.push_back(bla9);
    tocarry.push_back(bla10);
    int64_t toindex[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    int64_t fromindex[9] = {5, 3, 2, 6, 4, 8, 1, 9, 4};
    foo<int64_t>(tocarry.data(), toindex, fromindex, 0, 7, 9, true);
    std::cout << "tocarry - " << std::endl;
    for (int i=0; i<tocarry.size(); i++){
        for (int j=0; j<10; j++) {
            std::cout << tocarry.at(i)[j] << " ";
        }
        std::cout << "\n";
    }
    std::cout << "toindex - " << std::endl;
    for (int i=0; i<9; i++) {
        std::cout << toindex[i] << " ";
    }
    std::cout << "\n";
    std::cout << "fromindex - " << std::endl;
    for (int i=0; i<9; i++) {
        std::cout << fromindex[i] << " ";
    }
    std::cout << "\n";
    return 1;
}

to return the output -

tocarry - 
5 5 5 5 5 5 5 5 5 6 
5 5 5 5 5 5 5 5 6 6 
5 5 5 5 5 5 5 6 6 6 
5 5 5 5 5 5 6 6 6 6 
5 5 5 5 5 6 6 6 6 6 
5 5 5 5 6 6 6 6 6 6 
5 5 5 6 6 6 6 6 6 6 
5 5 6 6 6 6 6 6 6 6 
5 6 6 6 6 6 6 6 6 6 
0 0 0 0 0 0 0 0 0 0 
toindex - 
10 10 10 10 10 10 10 10 10 
fromindex - 
7 7 7 7 7 7 7 7 7 

Since I am more proficient in Python, I translated the function to Python hoping that I can translate the code into its iterative form in Python and then back to C++ -

def bar1(tocarry, toindex, fromindex, j, stop, n, replacement):
    while fromindex[j] < stop:
        if replacement:
            for k in range(j + 1, n):
                fromindex[k] = fromindex[j]
        else:
            for k in range(j + 1, n):
                fromindex[k] = fromindex[j] + k - j
        if (j + 1) == n:
            for k in range(n):
                tocarry[k][toindex[k]] = fromindex[k]
                toindex[k] += 1
        else:
            bar1(tocarry, toindex, fromindex, j + 1, stop, n, replacement)
        fromindex[j] += 1

which I verified is correct since it gives the same output for the same test case.

But I am still unable to translate the function..

I went through some failed attempts like -

def bar2(tocarry, toindex, fromindex, j, stop, n, replacement):
    for i in range(j, n):
        if replacement:
            for k in range(i + 1, n):
                fromindex[k] = fromindex[i]
        else:
            for k in range(i + 1, n):
                fromindex[k] = fromindex[i] + k - i
        if i + 1 == n:
            for k in range(n):
                tocarry[k][toindex[k]] = fromindex[k]
                toindex[k] += 1
            fromindex[i] += 1
    for i in range(n - 1, j - 1, -1):
        while fromindex[i] < stop:
            if i + 1 != n:
                fromindex[i] += 1
            if replacement:
                for k in range(i + 1, n):
                    fromindex[k] = fromindex[i]
            else:
                for k in range(i + 1, n):
                    fromindex[k] = fromindex[i] + k - i
            if i + 1 == n:
                for k in range(n):
                    tocarry[k][toindex[k]] = fromindex[k]
                    toindex[k] += 1
                fromindex[i] += 1

but which clearly does not work and gives the following incorrect output -

toindex =  [2, 2, 2, 2, 2, 2, 2, 2, 2]
tocarry =  [[5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 5, 0, 0, 0, 0, 0, 0, 0], [5, 6, 0, 0, 0, 0, 0, 0, 0]]
fromindex =  [7, 7, 7, 7, 7, 7, 7, 7, 7]

I would really appreciate any help!


r/learncpp • • Jul 08 '20

Compile-time errors come from compilers, linking errors come from linkers, and runtime errors come from...?

3 Upvotes

Basically, the title.

I've seen a bunch of online courses just say that "the compiler will throw a runtime error if you try to do a double delete", for example.

Maybe there are cases where the compiler is smart enough to detect something like that, but what about other cases where it's not obvious? What is throwing the runtime error that's causing the program to segfault? Do we just refer to it as the "system" that's throwing the error? Or is there something under the hood for C++ that we refer to (e.g. "the JVM threw an error" in Java)?


r/learncpp • • Jun 09 '20

Best books/courses?

3 Upvotes

Hi, i'm 16 and i want to develop game so i chose cpp for first language to start. Someone can suggest me some books or courses to start learning? I will appreciate a lot


r/learncpp • • May 30 '20

Site down?

3 Upvotes

Site seems to have been down for about 12 hours. Anyone know whats up?

https://isitdownorjust.me/learncpp-com/


r/learncpp • • Apr 13 '20

which data type to use..

3 Upvotes

I want to add all the digits of this number

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

i am getting this error long long long is too long for GCC

Thank you in advance


r/learncpp • • Apr 07 '20

Runtime Polymorphism with std::variant and std::visit

Thumbnail
bfilipek.com
3 Upvotes

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 • • 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 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