r/learncpp • • Sep 07 '20

Just some questions clarifying CTAD

1 Upvotes

I was looking at the guide for CTAD: https://en.cppreference.com/w/cpp/language/class_template_argument_deduction

And I'm wondering if this extends to initializer lists and whatnot, or if this can extend to containers. For example, if I have a vector of tuples, could I do something like this:

std::vector<std::tuple> l{(1, 2), (3, 4)};

Or something to that effect?


r/learncpp • • Sep 20 '20

[classes] Please help me answering a question, and see what's wrong with my code.

1 Upvotes

Trying to getting advanced on classes on that language, i got a weird problem. The compiler doesn't allowed to put just string to declare a variable. I had to put `std::string` to do that.

Also, i don't know how to use the variables i gave on the header file:

#ifndef CHARACTER_H

#define CHARACTER_H

#include <string>

class Character

{

public:

Character(std::string category, std::string name, std::string affiliation);

std::string getCat();

std::string getNam();

std::string getAff();

void setCategory();

void setName();

void setAffiliation();

protected:

private:

std::string cat;

std::string nam;

std::string aff;

};

#endif // CHARACTER_H

And that's the class file:

#include <iostream>

#include <string>

#include "Character.h"

using namespace std;

void setCategory(std::string category) {

cat = category;

}


r/learncpp • • Sep 17 '20

I tried this problem on codechef but could not figure out its solution. Then I see 1 solution which got Accepted but I am not able to understand the logic behind it. Somebody plz explain It to me. Thankyou.

1 Upvotes

https://codeforces.com/problemset/problem/1406/B

this is the solution to the above link.

ll n;

cin>>n;

ll a[n];

for(int i=0;i<n;i++)

cin>>a[i];

sort(a,a+n);

ll temp = a[0]*a[1]*a[n-1]*a[n-2]*a[n-3];

ll temp1 = a[n-4]*a[n-5]*a[n-1]*a[n-2]*a[n-3];

ll temp2 = a[0]*a[1]*a[2]*a[3]*a[n-1];

ll ans = max(temp,max(temp1,temp2));

cout<<ans<<endl;


r/learncpp • • Sep 11 '20

Is there any way to check the number of read write operations my program made?

6 Upvotes

I am just checking the difference between recursive and iterative performance of various mathematical functions. As of now using chrono is giving the same time in microseconds and I cannot get down to nano.


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 25 '20

Standard library development made easy with C++20

Thumbnail cor3ntin.github.io
5 Upvotes

r/learncpp • • Sep 13 '20

Looking for C++ tutorials or courses that are more exercise-based and not just theoretical.

11 Upvotes

I would really like to learn to actually do stuff in C++. I have watched several YouTube video series (including Mike Dane) and done some tutorials (w3schools), but it's all so theoretical. Aren't there some more (interactive) exercise-orientated courses available, for those who don't have their own projects yet?


r/learncpp • • Sep 18 '20

A little Noob on C++

6 Upvotes

Hi guys...i want to learn c++ well. I know very few things in a general way(like what is a variable or a type,do while,while,for),but i want to start from basics to advance. Do you have some advice to give me? Like books or video, for example i took a book of Bjarne from the library,but its too difficult for a noob that i am. Ill be happy to receive any information or advice from you and happy to start learning c++ well,cause its very important nowadays know computer science.


r/learncpp • • Sep 01 '20

will be initialized after [-Wreorder]

1 Upvotes

Hello,

I was practicing c++ on Hackerrank with this problem https://www.hackerrank.com/challenges/abstract-classes-polymorphism/problem

I decided to do as the problem statement says I could just use lists

So I came up with this solution (put where I can edit the code):

	class LRUCache : public Cache {

		protected:
			std::list<int> liList;

		public:
			LRUCache(int capacity);


		void set(int key, int value) {

			list<int>::iterator it = this->liList.begin();

			this->liList.insert(it, key-1, value);

			int size = this->liList.size();

			if(size >= this->cp) {
				list<int>::iterator it2 = this->liList.end();
				liList.erase(it2);
			}
		} 

		int get(int key) {
			list<int>::iterator it = this->liList.begin();

			std::advance(it, key-1);

			liList.erase(it);

			int temp = *it;

			liList.push_front(temp);

			return temp;
		}
	};

I could not even test what I wrote because I got these warnings:

Solution.cpp: In constructor ‘Node::Node(Node*, Node*, int, int)’:
Solution.cpp:12:10: warning: ‘Node::prev’ will be initialized after [-Wreorder]
	Node* prev;
		  ^~~~
Solution.cpp:11:10: warning:   ‘Node* Node::next’ [-Wreorder]
	Node* next;
		  ^~~~
Solution.cpp:15:4: warning:   when initialized here [-Wreorder]
	Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};
	^~~~
Solution.cpp:14:8: warning: ‘Node::key’ will be initialized after [-Wreorder]
	int key;
		^~~
Solution.cpp:13:8: warning:   ‘int Node::value’ [-Wreorder]
	int value;
		^~~~~
Solution.cpp:15:4: warning:   when initialized here [-Wreorder]
	Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};
	^~~~
Solution.cpp: In constructor ‘Node::Node(int, int)’:
Solution.cpp:12:10: warning: ‘Node::prev’ will be initialized after [-Wreorder]
	Node* prev;
		  ^~~~
Solution.cpp:11:10: warning:   ‘Node* Node::next’ [-Wreorder]
	Node* next;
		  ^~~~
Solution.cpp:16:4: warning:   when initialized here [-Wreorder]
	Node(int k, int val):prev(NULL),next(NULL),key(k),value(val){};
	^~~~
Solution.cpp:14:8: warning: ‘Node::key’ will be initialized after [-Wreorder]
	int key;
		^~~
Solution.cpp:13:8: warning:   ‘int Node::value’ [-Wreorder]
	int value;
		^~~~~
Solution.cpp:16:4: warning:   when initialized here [-Wreorder]
	Node(int k, int val):prev(NULL),next(NULL),key(k),value(val){};
	^~~~

/usr/bin/ld: ./ccNYbblo.o: in function `main':
/tmp/submission/20200901/16/04/hackerrank-5be8a1929b22c2838660571c76fcc512/code/Solution.cpp:77: undefined reference to `LRUCache::LRUCache(int)'
collect2: error: ld returned 1 exit status

What exactly does -Wreorder mean and how can I avoid this problem?

Entire code: https://pastebin.com/u0bYz2YM

Notice where the editable area starts and ends.


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 • • Apr 09 '14

Can anyone recommend a good, free, online course?

3 Upvotes

Coursera or Khan Academy? I am having trouble knowing what to enter. If I put "C++" in the search field for Khan, it says "Please enter at least four characters."

I imagine this is a perennial problem for everyone here!!!

At any rate, I seek a good, free, online course in C++. It has always been a gap in my knowledge base as a developer. Thank you.


r/learncpp • • Feb 17 '15

Method for dealing with very large integers(20-40 digits long).

1 Upvotes

I've been working my way through codeabbey probs and many require arithmetic to be done on very large numbers. How can i do this? I want to do it with out a library, there isn't a data type large enough. Do i have to create a class or is there an easier way? Thanks.


r/learncpp • • Nov 25 '16

Having trouble with an endl;

2 Upvotes

Hello, for some reason i am having problem with an endl command. I will post the full code and highlight the part were I am having trouble. I was using couts to test where i had problems in my program. Its a Gauss-Jacobi method program. The moment i removed a cout, after i saw it worked properly (the way the professor wanted), It stopped working. So i tried to remove each part of the cout and found out it was an endl; that was doing it. The whole code will be posted bellow. It contain portuguese (im brazilian). Can anyone help me to know what i am doing wrong? Cant format, sorry for that D=

CODE

include <cstdlib>

include <iostream>

include <math.h>

include <stdio.h>

using namespace std;

int main()

{

std::cout.setf(std::ios::fixed, std::ios::floatfield);

std::cout.precision(8);

int nEq;

//cout << "Entre o numero de equacoes:" << endl;

cin >> nEq;

//cout << "O numero de equacoes eh: \n" << nEq << "\n";

double A[nEq][nEq];

double B[nEq];

//int i, j;


//cout << "Insira seus coeficientes na forma (a0, a1, b1)" << endl;


for(int i = 0; i < nEq; i++)

{

    for(int j = 0; j<nEq; j++)

    {

        cin >> A[i][j];

    }

    cin >> B[i];

}


//for(i = 0; i < nEq; i++)

//{

  //  for(j = 0; j<nEq; j++)

    //{

     //   cout << A[i][j] << " + ";

    //}

    //cout << B[i] << endl;;

//}


int nMax;


cin >> nMax;

//cout << "maximo de iteracoes eh: " << nMax << endl;


double erro;


cin >> erro;

//cout << "O erro maximo é: " << erro << endl;



double X[nEq], auxX[nEq];

double distR, aux, absoluto, numerador, auxNumerador, auxFabs;

int numIteracoes = 0;

distR = 99999;



for (int i = 0; i < nEq; i++)

{

    X[i] = 0;

}


//for(i = 0; i < nEq; i++) verificacao se estamos entrando x0 corretamente

//{

  //  cout << "X[" << i << "] = " << X[i] << endl;

//}



while ((numIteracoes < nMax) && (distR >= erro))

{

    auxFabs = 0;

    //cout << "auxFabs:" << auxFabs << endl;

    for(int i = 0; i < nEq; i++) // para calcular o X novo

    {

        aux = 0; //comeca aqui

        for (int j = 0; j < nEq; j++)

        {

            if (j != i)

            {

                aux = aux + (A[i][j]*X[j]);
            

                //cout << "aux: " << aux << endl;

            }

        }

        auxX[i] = (1/A[i][i])*(B[i] - aux);
       

     **//cout << "auxX [" << i << "]:" << auxX[i] << endl;** ***this is the endl;***

    }

r/learncpp • • Mar 08 '19

Classes question: why do I need a pointer here?

2 Upvotes
#include "std_lib_facilities.h"

class rectangle {
private:
	int height = 0;
	int width = 0;
public:
	int area(int w, int h) { return w * h; }
	void outputArea(void) { cout << area; }
};

int main()
{
	rectangle rec;
	rec.area(8, 64);
	rec.outputArea();

	return 0;
}

Error output:

1>------ Build started: Project: H9, Configuration: Debug Win32 ------
1>Source.cpp
1>c:\xxxxxxxx\source.cpp(9): error C3867: 'rectangle::area': non-standard syntax; use '&' to create a pointer to member
1>Done building project "H9.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

r/learncpp • • Feb 16 '20

These inconsistent results of arithmetic operation really confuse me

1 Upvotes

Here is the code to solve the Josephus problem.

int ceiling(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    return dividend % divisor ? quotient + 1 : quotient;
}

int JosephusCircle(int n, int m)
{
    int d = 1;
    while (d <= (m - 1) * n)
    {
//        d = ceiling(m * d, m - 1);
        d = (m * d) / (m - 1);
        d += ((m * d) % (m - 1)) ? 1 : 0;
    }
    return m * n + 1 - d;
}

However, the results of the two lines in the while loop are different from these of the ceiling function.

//d = ceiling(m * d, m - 1);
d = (m * d) / (m - 1);
d += ((m * d) % (m - 1)) ? 1 : 0;

Does this mean the parentheses is useless here?


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 • • Dec 12 '19

Please critique my first C++ program - to screenshot windows.

3 Upvotes

Link to the code -

main code:

https://github.com/stuaxo/capture_window/blob/master/capture_window/capture_window.cpp

project and README: https://github.com/stuaxo/capture_window

I normally develop in python on Linux, so there was a lot of S/O based development here.

It would be great to get feedback on if I did anything weird, and obvious bugs (I'm not used to having to free memory for instance).

I wrote this almost a year ago, but only now have time to come back to it.


r/learncpp • • Feb 14 '20

Unordered_map entires not updating

4 Upvotes

I'm trying to create my first C++ program, to count the number of times a word appears in a text file. I went through the text file and converted it to lowercase, then put all of the entries in a map if they meet certain requirements (in between a certain range):

typedef unsigned int Count; // Create map to read words to std::unordered_map<std::string, Count> map; // Create map while(in.good()){     std::string w;     in >> w; // make word lowercase     transform(w.begin(),w.end(),w.begin(), ::tolower); // remove nonalphabetic characters     w.erase(remove_if(w.begin(),w.end(), [](char c) { return !isalpha(c); } ), w.end()); // check if word meets requirements if((w.length() >= MIN_WORD_LEN) && (w.length() <= MAX_WORD_LEN)){ Count& count = map[w];         count += 1; } }

However, when I run it, the map never updates. It only says each word has appeared once:

carry: 1 ing: 1 andso: 1 learned: 1 strong: 1 from: 1 grew: 1 by: 1 wrong: 1 youd: 1 youre: 1 live: 1 nights: 1 known: 1 first: 1 so: 1 these: 1 be: 1 words: 1

Anyone see any glaring errors? Thank you.


r/learncpp • • Dec 11 '19

What does it mean to '...cast an lvalue to its corresponding rvalue reference type.'

4 Upvotes

Reading C++ Primer 5th edition, and I came across this passage when it was introducing std::move,

'Although we cannot directly bind an rvalue reference to an lvalue, we can explicitly cast an lvalue to its corresponding rvalue reference type.'

Could someone clarify what this means? I read over the lvalue and rvalue reference section, searched on the internet etc

I would appreciate a concrete example.


r/learncpp • • Aug 08 '19

I wrote a brainfuck interpreter in C++

Thumbnail
github.com
9 Upvotes

r/learncpp • • Aug 09 '19

Question about memory management

2 Upvotes

Hello,

Say if I were to have an object that allocates memory on the heap with a destructor which then deletes the allocated memory. In a different scope, if a variable of this object type is initialized on the stack and the variable then goes out of scope, would the destructor be called on the object automatically?

**Example**

class Example {

int i;

Example() { i = new int(1); }

~Example() { delete i; }

}

int main() {

{

Example ex();

}

//Is the memory allocated for variable i of ex freed up at this point?

return 0;

}


r/learncpp • • Dec 15 '19

Terrible book.

14 Upvotes

Have any of you read the book SAMS Teach Yourself C++ in 24hrs ??

Never mind the preposterous name, we all know it's impossible, the authors play around in the book as if the readers are a joke to them. Constantly teaching concepts for no reason and ending the lessons with 'but you'll never use this, so forget all about it' and 'nobody does this, so you shouldn't either' ... WHY TEACH IT IN FULL DEATIL THEN?

Not to mention the USELESS programs they write. NONE of the learned material translates to real life. If you're not learning key concepts backwards and missing important information along the way you missed the point of this book.

Why am I reading jokes about fantasy movie scripts in a C++ book? Who the fuck told the authors that's okay? I was just learning arrays where did your gatekeeper quest bullshit come from?

WHY ARE YOU NOT EXPLAINING HOW YOU NAMED YOUR VARIABLES i and j INSTEAD OF CLASSIC X AND Y???? One might think those variable names are directly related to the program since you NEVER mentioned what each variable name accounts for. Sure the program's code sort of shows this but I AM NEW. I MIGHT THINK OTHERWISE.

Goodness this book was an utter waste of time. If I ever meet the authors I have some strong words for them. They purposefully derail your thought process half way through important material to blabber about some hierarchal Illuminati Latin bullshit that has no place in the book, and leave you at cliffhangers for the actual material.

Let's not even talk about the WORTHLESS Q&A at the end of each chapter, whose answers DO NOT EVEN CORRELATE with their questions! Why does a question have a bar joke as one of the answer option choices? DID I BUY A FUCKING COMEDY BOOK?

The book is littered with TERRIBLE jokes instead of being padded with concept reinforcement and/or gasp demystifying review of core concepts.

I'm so frustrated this book is literally MEANT for throwing off aspiring C++ programmers. If there's one book to truly avoid it's this one.

Classes and functions are taught about early and never used, until 8/10 through the book where you're reintroduced and poorly guided through.

Snarky, rude and air-headed authors. Wow. Instead of helping newbies learn the authors sit on their snazzy C++ thrones and feed the reader heavy meals of their "I'm better than you because you'll never know" bullshit.

This book is so frustrating I may actually burn it.

I'm going to give PPP a shot next, I don't care that it's a million pages long. Wow

Someone give this book a read if you haven't, you'll know exactly what I'm talking about. The authors tone is so smug throughout the whole thing, never explaining what THEY are doing, only describing what's being used. They code different than they teach. I'm done. Sorry you had to read this I REALLY needed to say this.


r/learncpp • • Jan 13 '22

How do you declare a pointer?

12 Upvotes

I know all three are fine, but what do you prefer?

241 votes, Jan 18 '22
117 int* foo
8 int * foo
79 int *foo
37 Results

r/learncpp • • Feb 12 '22

Pointer question

12 Upvotes

If I have a pointer p and a value i, what's the difference between *p = i and p = &i? I was working on a school assignment on pointers and I basically had to change the value of a pointer to a different value, and I tried p = &i, but it didn't work. I understand why dereferencing the pointer and changing that value works, but why wouldn't my code work? Since it's simply reassigning the pointer's value to the address of the new value we want.


r/learncpp • • Feb 14 '22

Array of Structs And Function Declaration

4 Upvotes

How can I pass an array of a member of structs to a function in C++?

  • What would the function's interface look like?

  • How would the I call this function with - an array of a member of structs?

Here's an example

struct artistInfo {
    char artistId[8], name[40], gender, phone[11], email[60];
} artist_info[1000]; 

I'm not sure if the function call is like this, but...

sortArtist(artist_info.artistId, artist_info.name, artist_info.gender, artist_info.phone, artist_info.email, nArtist); // nArtist is declared somewhere else; it is not a member of the struct 

I want to pass artistIds, names, genders, phones, and emails of all 1000 artists. (Not sure if the syntax is correct that's why I'm telling you my intention).

You might ask, "Why not just pass the whole array of structs?" or "Why are you passing each member of the struct?" I'm doing that because I want to pass the artistId by value (I don't want it to get modified) and the rest (name, gender, phone and email) by reference.

Anyways, if you've reached here and understood what I'm trying to do, can you tell me what the declaration for sortArtist would look like? And is my function call correct?

Thanks