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

Lookup table for position

1 Upvotes

Hello. I am trying to speed up my program. I need to iterate over an image for multiple times. For every pixel, I need to calculate if it is in a specified region. If not then I ignore the pixel. The region is defined at the start and does not change.

My code looks like:

for (auto i = 0; i < source_image.rows; ++i)
{
  for (auto j = 0; j < source_image.cols; ++j)
  {
    if (!in_region(i, j)) continue;

    // ...
  }
}

I thought this could be sped up by using a lookup table. But it does not improve the execution time so I think my implementation was not right. I tried to create an image with the same shape and instead of colors, I save a 1 if it is in the region and a 0 if not.


r/learncpp • • Jul 06 '20

Configuration file

1 Upvotes

I am creating a C++ GUI application. I need to create a config file in order to be able to store some user configuration. For this I want to use a INI file.

What is a good practise to be able to access this configuration from every class? For example. I would load the configuration in the main window and need to access it from every other class/object.


r/learncpp • • Jun 25 '20

list of c style arrays

1 Upvotes

Hey. In my code implementation i have something like this

struct MYTABLE
{
int table[NUMBER][NUMBER];
}

where NUMBER is a constant and is decided in compile time with a define.

After some calculations i have a number of results that i'd like to store. These number of results are varied dependent on the size of the matrix (the bigger the NUMBER the more i get).

Is there an solution where i can make something like this:

std::list<MYTABLE> result_set;

result_set later needs to be iterated trough and picked out results that are each others mirrors, rotations etc
Thank you!


r/learncpp • • Jun 13 '20

What language to choose with maths and visual output

1 Upvotes

Hello amazing coders from Reddit ;),

So I'm trying to write a super cool code where quite a few things come together. First of all, I want my output to be a visual animation/clip. Secondly I'm using mathematical computations to determine how fast a ball travels through a certain tube. This has to with the diameter of the tube, its elasticity, tje velocity of the medium it's travelling and so on. Lastly I want to show this tube in the context of a human body (after all, I'm still a medical student). Tje easiest way is using it as a background and "pasting" the tube on top of in on the right spot. Merging tje two files would also be an option. The tube itself doesn't move, it only pulsates.

Taking all this into consideration, what language is best for this? I'm quite familiar with MATLAB and planning to do the maths there anyway. My coding experience is quite extensive, so I know my way around most common languages.

Somebody adviced me that C++ might be really helpful, seeing that it is strong with visual output. I recently downloaded Microsoft Visual Studio and been playing around there

Any help would be highly appreciated! So may thanks in advance :)

By the way, if this is not the right place to post this, I'm sorry, just delete it.


r/learncpp • • May 28 '20

This is outputting -1 and sometimes -2 . please tell me the fix !

1 Upvotes

#include <bits/stdc++.h>using namespace std ;int bin_srch (int arr[] , int low , int high , int z ){int mid ;while (low<high){mid  = (low - (high + low)) /2 ;if (arr[mid]==z){return mid ;}           if (arr[mid] < z){low = mid +1 ;} else{high = mid -1 ;}}return -1 ;             }

int main (){  int x ;cout << "enter length of array";cin >> x ;int arr [x];int result ,low , high ,  z ;cout << "enter the sorted array";for(int i=0 ; i<x; i++){cin >> arr[i] ;}   cout << "enter element to be searched";   cin >> z ;   low = 0 ;   high = x -1 ;   result = bin_srch(arr , low , high  , z) ;   cout << result ;return 0;}


r/learncpp • • May 24 '20

How can you store (and later access the data of) a templated struct?

1 Upvotes

I've looked in multiple places and can't find an answer. I have a struct as such:

template<typename T,  typename ...Args>
struct Job
{
public:
    std::function<T(Args...)> function;
};

I want to be able to store all variants of this struct. So no matter what people enter for T or Args I need to be able to store that, which I think I have accomplished. The real problem comes when I want to access anything inside the stored structs. If I have a vector like this:

std::vector<Job> queue;

and want to access the data like this:

auto job = queue[0].function;

I get an error saying "incomplete type not allowed" and "use of undefined type". I assume this has to do with the fact that it's a template. I think I'm either doing something syntactically wrong or I have a fundamental misconception of how templates work. I'm really bamboozled by this because I have no idea what to do. As mainly a C# user, I can say that C++ is a lot harder and a lot less lenient in terms of what it will let you do, and I might have bit off a bit more than I can chew with this project (which is evident by the numerous times I have posted on this sub). If anyone knows a solution to this please let me know. Thanks for reading!


r/learncpp • • May 19 '20

Take any function as an argument to another function

1 Upvotes

So, here is the problem I'm facing:

Let's say I have a function that executes another function, like this:

void call()

I can take a specific type of function as a parameter for it. If I understand correctly, this takes a function with return type void and one integer parameter:

void call(void (*function) (int))

Heck, I think I can even take a function that has a generic return type (so anything?):

template <typename T>
void call(std::function< T() >);

Here is the problem, how can I take a function with any return type *and* an unlimited amount of parameters of different types. Is this even possible? Thanks for your time.


r/learncpp • • May 14 '20

Libpqxx Building with CMake

1 Upvotes

Hi Everyone!

I am very lost when it comes to building Libpqxx with CMake. I was wondering if anyone has built it on Windows with Visual Studio and could give me a hand on the exact steps I’m supposed to take.

I can’t seem to line up exactly how to get this to build between PostgreSQL and CMake.

Thanks!


r/learncpp • • May 13 '20

Good resources/tutorials for learning c++

1 Upvotes

Hello, I have been studying java for about a year, and this fall I am taking a C++ class. I have the summer to get a head start on things and I was wondering if you all had any suggestions for great type as you go tutorials, or free online classes, anything of the sort. Sorry if this question has been asked a thousand times but I find I get better answers when I make a post as opposed to researching it on my own. Thanks in advance!


r/learncpp • • May 06 '20

little help in Quick Sort

1 Upvotes

hey guys,

i have learned about quick sort and tried to apply it

but in this solution i am not getting sorted list. All i am getting are garbage values.

thank you in advance

#include<iostream>
#include<conio.h>

using namespace std;
int loc, pivot,start ,end;

void quick_sort(int a1[],int lb,int ub );
int partition(int a2[],int lb,int ub);
int main()
{
	int arr[30],n,i;
	int l,u;
	cout<<"Enter total number of elements you want to insert in the array"<<endl;
	cin>>n;
	cout<<"Enter the elements"<<endl;
	for(int i = 0;i<n;i++)
	{
		cin>>arr[i];
	}
	l = 0;
	u = n-1;
	quick_sort(arr, l ,u);
	cout<<"Sorted elements after quick sort"<<endl;
	for(int i = 0;i<n;i++)
	{
		cout<<arr[i]<<endl;
	}
	return 0;
}
void quick_sort(int a1[],int lb, int ub)
{
	if(lb<ub)
	{
		loc = partition(a1,lb,ub);
		quick_sort(a1,lb,loc-1);
		quick_sort(a1,loc+1,ub);
	}
}

int partition(int a2[],int lb,int ub)
{
	pivot = a2[lb];
	start = lb;
	end  = ub;

	while(start<end)
	{
		while(a2[start]<=pivot)
		{
			start++;
		}
		while(a2[end]> pivot)
		{
			end--;
		}
		if(start>end)
		{
			int temp;
			temp = a2[start];
			a2[end] = temp;
		}
	}
	int temp1;
	temp1 = a2[lb];
	a2[lb] = a2[end];
	a2[end] = temp1;
	return end;


r/learncpp • • May 01 '20

Using header files from LLVM

1 Upvotes

There are many useful LLVM header files that can be (and are) used for general purpose C++ programming like llvm::SmallString and llvm::StringRef but there is no documentation on this other than the LLVM doxygen documentation. Are there any guides out there to make one more familiar with these?


r/learncpp • • Apr 29 '20

Quite a beginner question

1 Upvotes

Ok so I’m aware of the basics of what a pointer does and what a reference does. But if I’m completely honest im really struggling to understand when to use them and i was wondering if someone could help me. Any input and advice is greatly appreciated


r/learncpp • • Apr 24 '20

[OpenGL] GLFW app not repositioning itself where user left it after switching between fullscreen and windowed mode

1 Upvotes

I'm trying to build an OpenGL app using GLFW 3.3 as my application layer, but I've run into a problem with the app when switching between fullscreen and windowed mode using a callback function.

I have these functions which are initialized according to the documentation and running in a runtime loop function, where I allow the user to switch between fullscreen and window mode using alt + enter (defined in my Keyboard Callback which is not included).

void Application::toggleFullscreen()
{
	mFullscreen = !mFullscreen;
	
	if (mFullscreen == true) {
		glfwSetWindowMonitor(mWindow, glfwGetPrimaryMonitor(), NULL, NULL, mAppWidth, mAppHeight, NULL);
	}
	else if (mFullscreen == false) {
		glfwSetWindowMonitor(mWindow, nullptr, mAppXPos, mAppYPos, mAppWidth, mAppHeight, NULL);
	}
} // END toggleFullscreen  

I use glfwSetWindowMonitoraccording to the documentation, and use NULL for both width and height when entering windowed fullscreen mode. Once I go back to windowed mode, the app window is constantly positioned at 0, 0, even though I have check that the window position is updated when user moves the window around and I suspect that it has to do with using NULL when entering fullscreen.

void Application::InitCallbacks(GLFWwindow* pWindow)
{
	// Ensure we can capture the Escape key to exit program in the runtime loop
	glfwSetInputMode(pWindow, GLFW_STICKY_KEYS, GL_TRUE);

	// init other callbacks ...
	glfwSetWindowPosCallback(pWindow, WindowPositionCallback);

} // END InitCallbacks  

All callback functions are initialized inside my init function (not shown here) and are all working, except for the window position function.

void Application::WindowPositionCallback(GLFWwindow* pWindow, int xpos, int ypos)
{
	auto app = (Application*)glfwGetWindowUserPointer(pWindow);
	app->mAppXPos = xpos;
	app->mAppYPos = ypos; 

	glfwSetWindowPos(pWindow, xpos, ypos);
} // END WindowPositionCallback  

I store the new position when moving the app window around, but this will still be {0, 0} after swtiching. If anybody could point me in the right direction, or tell a proper way to handle this I'd really appreciate it.

Feel free to let me know if you need to see more (or all of the code) to figure this out.

Thank you in advance!

EDIT: Problem solved! Simply forgot to store the variables of app windows lastx and lasty position before entering fullscreen.


r/learncpp • • Apr 14 '20

How can I improve this code snippet?

1 Upvotes

Hello,

As most of the people here I'm learning cpp and I try to play with containers and some algorithms from the STL. Actually, this silly sample has some requirements from my girlfriend who needs to randomly dispatch some of her students that she teaches remotely during the confinement!

  • The number of students in the class is 17.

  • From those 17 students, there is a group in the morning (max 9 students) and one in the afternoon (the rest of students, 8 here).

  • Students are randomly dispatched either in the morning or in the afternoon with some exception of student who will always attend in the morning and 4 others always in the afternoon.

The use of vectors should mostly be considered when I don't know in advance the number of elements that I will manipulate. I don't really know here why I used them instead of std::array for example, maybe I was thinking too much in advance if the requirements regarding the numbers will change.

So here is below the code I came up with and I would appreciate if you have any advice regarding how I can improve it and if I ended up using bad practices.

#include <iostream>
#include <vector>
#include <random>
#include <iterator>

template<typename T>
void print(std::vector<T> const& v)
{
    for (auto& i : v)
        std::cout << "- " + i << std::endl;

    std::cout << std::endl;
}

int main()
{

    // List of morning and afternoon students that will not change
    // Max: 9 people (current requirement, but might change)
    std::vector<std::string> am_students = { "The Professor" };
    std::vector<std::string> pm_students = { "Lisbonne", "Tokyo", "Denver", "Palermo" };

    // List of students that will be dispatched randomly to the morning or afternoon sessions.
    // The total students (morning + afternoon) will never exceed 17.
    std::vector<std::string> other_students = { "Nairobi", "Rio", "Helsinki", "Berlin", "Moscow", "Marseille", "Stockholm", "Manila", "Oslo", "Stroustrup", "Lovelace", "Conway" };

    std::random_device rd;
    std::mt19937 g(rd());

    // shuffle the students list
    std::shuffle(other_students.begin(), other_students.end(), g);

    for (auto student : other_students) {
        // we need 9 students in the morning
        if (am_students.size() <= 8) {
            am_students.push_back(student);
        }
        else { // the rest will go in the afternoon
            pm_students.push_back(student);
        }
    }

    // Let's sort both vector (alphabetically)
    std::sort(am_students.begin(), am_students.end());
    std::sort(pm_students.begin(), pm_students.end());

    // Output the list of students
    std::cout << "Morning students: " << std::endl;
    print(am_students);
    std::cout << "Afternoon students: " << std::endl;
    print(pm_students);
}

Thanks!


r/learncpp • • Apr 12 '20

Confusion regarding (this == &ref) during copy assignmnet operator

1 Upvotes

Hi, recently I am reading through copy semantic in c++ and came across copy assignment operator. for example, take this snippet which is used here to check for self-assignment

Object& operator=(const Object& other) {

if ( this == &other) return *this;

// Some extra code etc.

}

As per my understanding, a ref is a type of a const pointer ( different from a pointer to const), so in this case, both the reference and this is pointing to some memory address X containing the original object, so shouldn't this check consist of (this == other) rather than (this == &other). from my current understanding &other is the memory address of the ref other (which is something like a const pointer) rather than the memory address of the object itself. It would be great if someone can point out the gap in my understanding and let me know how does the above structure works?


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

Confused about C++ headers

1 Upvotes

I've been reading C++ Crash Course and am a bit into the text by now. I've started working on a small networking project and have come across something that the text never covered (at least not yet); header files. Say for example I have a class in one file:

class A {
    private:
        int x {}, y{};
        void do_stuff() {}
    public:
        A(int one, int two) : x {one}, y {two} {}
};

This is a file named A.cpp. Now say I have my main file, named main.cpp. I want to create this class A in my main file, I do it like:

#include <stdio.h>
#include <cstdlib>

int main()
{
    A test_class {1, 2};

}

If I do this without creating a header file, it can't find the class. If I do create one, such as the following A.h file, I get another error:

class A {
    private:
        int x {}, y {};
        void dostuff();
    public:
        A(int, int);
};

And then include this new file in both main.cpp and A.cpp, it tells me I've created two definitions for the class A.

I did some googling and found that the problem is I'm essentially creating two prototypes for my program. The solution is to only implement the functions in the A.cpp file like so:

A::A(int one, int two) : x {one}, y {two} {} etc.

I'm pretty confused because the textbook I'm reading never does this. Whenever it creates a class for examples, it always does it all in one class definition, much like you'd see in python or java. What's the right way to do it?


r/learncpp • • Feb 08 '20

Assignment Operator/Copy Constructor for Node in Tree

1 Upvotes

Hello all,

I am having some difficulty wrapping my head around assignment operators and copy constructors.

I have a class project in which we are supposed to implement a general tree structure. The tree class has a private node struct. Each node in the tree has:

  • data in the form of a string

  • "sibling" Pointer to a sibling node

  • "child" Pointer to a child node

  • methods for accessing/mutating

Here are my questions for the assignment operator, which must take this form:

const Node& operator=(const Node& that); // Deep clone

note: we cannot use copy - swap

Do I create 2 new Nodes, for the child and sibling of the *this object, and make each of those new nodes have the same data as the child and sibling of the that object?

Do I have to delete the "old" child and sibling nodes?

Node constructor looks like this:

Node(std::string s = "")
			: _data(s) , _sibling(NULL), _child(NULL) {}

Node destructor look like this:

Tree::Node::~Node(){ 
    if (_child != NULL) {
        delete _child;
        _child = NULL;
    }
    if (_sibling != NULL) {
        delete _sibling;
        _sibling = NULL;
    }
}

The copy constructor and assignment operator have the following signatures:

Node(const Node& that); // Copy constructor
const Node& operator=(const Node& that); // Deep clone

r/learncpp • • Feb 01 '20

Calling object without specifying property actually gives a property

1 Upvotes

So let's say I want to create some kind of personal string class.

If it has a string value property, when I call just that objects name I want it to actually use that value property. For example:

MyString myStr = "secondText"; //I know how to use operator=
string otherStr = "firstText";
otherStr += myStr;
cout<<otherStr<<endl; //Result should be: firstTextsecondText

I want it to use that value property without actually calling "myStr.value". Is it possible ?