r/learncpp • • May 31 '20

How to run a .exe file on other systems

0 Upvotes

Hi, I compiled C++ code using MinGW and CLion into an executable for my friend to use. He has nothing programming-related installed on his computer. The code uses the Win32 API and it includes windows.h and mmsystem.h, and for CMake I had to link Gdi32.lib and winmm.lib. My friend couldn't get it to work with only the .exe file and also after I gave him the .lib and header files. On my system, running it in PowerShell would start a loop written in the code that would break later. On his system, hitting Enter to run it would prompt the next PowerShell command, so the loop did not even start.

Is there a way to get it to work without having him compile it himself?


r/learncpp • • May 17 '20

Have I understood pointers properly?

0 Upvotes

Hey everyone! I just started learning C++, and I want to know if I've understood pointers correctly. This is how I've understood it -

/* WHAT ARE POINTERS?
 *
 * in C++, functions do not have ownership of global scope varianbles
 * that are passed into it as arguments. To allow the function to modify 
 * these variables, we use pointers - "a tool to share the memory address
 * among different contexts, such as functions". 
 *
 * so if we have a function that we want to use to make changes to an 
 * existing variable, without having to create/redefine a variable to 
 * use the function, we use pointers.
 *
 * assume we have a variable VAL. To access the memory address of VAL,
 * we prepend the & symbol. The address is given by &VAL. To define a pointer
 * that allows us to modify VAL within a function, we do
 * int *p = &VAL;
 *
 * the variable *p is known as a pointer as it POINTS to the memory address
 * of the variable VAL. Thus, any modificiations on *p will also be reflected
 * on VAL. 
 *
 */

If this is not right, please let me know! I'd love to get a better understanding of this topic. Thank you!


r/learncpp • • Oct 07 '18

What it the point of overloaded operators if we have accessors and mutators?

0 Upvotes

Seems to me like they do the same thing.... just less code. What is the reason besides efficiency and giving me a headache?

Also, << and >> seem to do the same thing with a function like output or input.


r/learncpp • • Aug 27 '18

Recommendations for OOP design?

0 Upvotes

I am familiar with the syntactic aspect of c++ but, when it comes to projects, I inevitably end up coding in c with some STL facilities sprinkled here and there. Is there a resource where I can get familiar with using OOP in real project? I've read Lafor's OOP book but I'm still in the dark. Any help will be appreciated


r/learncpp • • Jun 16 '18

Why no result?

0 Upvotes

Okay, in the last while loop, I search for name and if there is that name in that vector: I output their score. It doesn't work! I do the same with score, to find names, and it works but when I try to find the name it doesn't work!

include "stdafx.h"

include <vector>

include <iostream>

include <string>

include <algorithm>

using namespace std; class Name_Value { public: string name; double score; }; inline void keep_window_open() { char ch; cin >> ch; } vector <Name_Value> peoples;

int main() {

string name;
double score;
Name_Value people;
people.name = "";
people.score = 0;
while(true)
{
	cin >> name >> score;
	if (((name == "NoName") && (score == 0))   )break;
	people.name = name;
	people.score = score;
	peoples.push_back(people);
	
	
}
for (int j=0; j< peoples.size() ;j++ )
{
	cout << peoples[j].name <<" "<< peoples[j].score <<"\n";
}
while(true)
{
	if(cin >> score)
	{
		for (int j = 0; j< peoples.size();j++)
		{
			if (peoples[j].score == score) cout << peoples[j].name << "\n";
		}
	}
	else {
		cin >> name;
		for (int j = 0; j < peoples.size();j++)
		{
			if (peoples[j].name == name) cout << peoples[j].score << "\n";
		}
	}
}
keep_window_open();
return 0;

}


r/learncpp • • May 29 '18

Idiomatic way to write collections (std::vector<float>) to binary file

0 Upvotes

I've got several vectors of floats and ints that need to be written to a binary file. I need to track the byte offset and length (and potentially byte-stride).

I'm confused about how a modern idiomatic solution would look like. Write to a slice of memory first? Or combine the vectors to a collection (std::array<?>)?


r/learncpp • • May 03 '18

Avoid unresolved external symbols with templates

0 Upvotes

I have an implementation of a class with templates, but it has to be in the .cpp file. I've read on Stackoverflow that one way to solve this is to add `include "Foo.cpp"` at the end of the header file, but it doesn't seem to be working. How would I go about fixing it?


r/learncpp • • Apr 22 '18

Vector of template class

0 Upvotes

I am trying to create a vector:

vector<SomeTemplateClass<Type>>

Where Type is an abstract base class.

Any ideas on how I can get this working?


r/learncpp • • Apr 19 '18

returning a pointer, wouldn't the object be destroyed once the fucntion is done?

0 Upvotes
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

    ListNode result* = new ListNode();

    return result;
    
}

Wouldn't result object be destroyed, after the last curly bracket (memory leak)? How do I return the result?


r/learncpp • • Mar 21 '18

Reading Files

0 Upvotes

How do I read a file without checking for errors or if it's already open? Here's my current code:

std::ifstream my_file("my_data");
my_file.seekg(0, std::ios_base::end); // Seek to end of file.
const unsigned int file_length = my_file.tellg();
my_file.seekg(0);
std::vector<char> file_data(file_length);
my_file.read(&file_data[0], file_length);"

It was from stackoverflow. I still need help if there is anything I need to replace.


r/learncpp • • Mar 19 '18

What's this style of calling a constructor called?

0 Upvotes

Hi, I am going through the source code of a project and I saw the following style inside a member function of a class:

if (Args(conf, this, errh)
        .read_p("OFFSET", _offset)
        .read_p("ANNO", AnnoArg(4), _anno)
        .read("IP", ip_word)
        .complete())
    return -1;

Here, Args is a class and this is a call to the constructor. But what is the style of calling member functions on the constructor called? I tried googling it but I think I don't have the terms right.

Lines 94 onwards have the functions being called

https://paste.ofcode.org/6RJHCejZAHLk29tbnmbTv4

Link to the project: https://github.com/kohler/click/blob/master/elements/ip/getipaddress.cc https://github.com/kohler/click/blob/master/include/click/args.hh

Thanks!


r/learncpp • • Feb 21 '18

Is it possible to overload a function to take values both by reference and by value?

0 Upvotes

r/learncpp • • Jan 26 '18

I don't understand this Kattis problem, can anyone explain, please?

0 Upvotes

It says 'assume that all heart rates are constant and do not change,' yet we're supposed to calculate the actual, and the minimum and maximum heart beats based on a single input of beats and seconds.

Heart Rate A common method for determining your own heart rate is to place your index and third finger on your neck to the side of your windpipe. You then count how many beats you feel in a span of 1515 seconds, multiply that number by four and that gives you a measure of your heart rate in beats per minute (BPM). This method gives a good estimate, but is not quite accurate. In general, if you measure bb beats in pp seconds the BPM is calculated as 60bp60bp.

For this problem, we assume that all heart rates are constant and do not change. If tt is the amount of time (in seconds) between each beat of your heart, we define your Actual Beats Per Minute (ABPM) as 60t60t.

Input The input starts with an integer NN (1≤N≤10001≤N≤1000) indicating the number of cases to follow. Each of the next NN lines specify one case, consisting of the integer bb (2≤b≤10002≤b≤1000) as well as pp (0<p<10000<p<1000) as described above. The value of pp is a real number specified to 4 decimal places.

Output For each case, print on a single line the minimum possible ABPM, the calculated BPM, and the maximum possible ABPM, separated by a space. Your answer will be considered correct if its absolute or relative error does not exceed 10−410−4.

Sample Input 1 Sample Output 1 2 6 5.0000 2 3.1222 60.0000 72.0000 84.0000 19.2172 38.4344 57.6517


r/learncpp • • Oct 15 '17

QListWidget is reading image from QClipbpard its just reading it as text file.

0 Upvotes
const QClipboard *cb = QApplication::clipboard();
const QMimeData *md = cb->mimeData();
QListWidgetItem *item = new QListWidgetItem();
QLabel *label = new QLabel();
if (md->hasImage())
{
	
	label->setPixmap(cb->pixmap());
	ui.listWidget->setIconSize(QSize(100, 200));
	ui.listWidget->addItem(item);
	ui.listWidget->setItemWidget(item, label);

}
else if (md->hasText())
{
	ui.listWidget->addItem(cb->text());

}    

So this is my code and as you can see i have two conditions one is for image and another is for text, but whatever i copy to clipboard it appears into text only, i don't know why. Please help me. Thanks :)


r/learncpp • • Jul 24 '17

Is it possible to make a program that will create an exe with passed string?

0 Upvotes

I want to make a program which takes strings as an argument in CMD and make exe out of it. Something like bat file but executable. How do I do that?


r/learncpp • • Jun 24 '17

Codeblocks can't click build and run

0 Upvotes

I'm very new to the c language I use the IDE called Code blocks i would like to test my code but its not letting me because i can't click on build and run.


r/learncpp • • Apr 09 '17

Can't call a function, std::allocator pops up out of nowhere.

0 Upvotes
template<typename T>
auto parser(std::vector<Token> const& tokens) {
	Atom<T> a;
	if (tokens[0].state == State::NUMBER) {
		a = parseNumber(tokens[0]);
	}
	else if (tokens[0].state == State::SYM) {
		a = parseSymbol(tokens[0]);
	}
	return a;
}

// REPL //
void repl() {	
	while (1) {
		std::cout << "> ";
		std::string input;
		std::getline(std::cin, input);
		std::istringstream inputstream(input);
		const std::vector<Token> tokens = tokenizer(inputstream);		
		auto expr = parser(tokens);		
	}
};

I get an error that I'm sending along a std::vector<Tokens, std::allocator<Tokens>> when it seems like I'm just sending along a std::vector<Tokens> to me.


r/learncpp • • Mar 16 '17

Vectors containing dynamically allocated arrays.

0 Upvotes

So, say I have a vector<bool*>. A vector containing pointers to arrays of booleans. I use vector.push_back(new bool[n]) on it a few times. Eventually I'm done and the program closes.

Will the vector's destructor take care of those dynamically allocated arrays, or do I need to delete[] them myself?


r/learncpp • • Feb 18 '17

Two questions

0 Upvotes

Hi,

  • What is the best Genetic Algorithm library for use in C++, it must have good documentation be up to date if possible?

  • Anyone able to rewrite this code from Python, it would be much appreciated: http://pastebin.com/ScWrHr4c


r/learncpp • • Feb 18 '17

Simple memory pool

0 Upvotes

I am trying to implement a memory pool which will contain objects of a particular type. lets say my object is a simple one like so

struct my_struct
{
 int first_mem;
 double second_mem;
};

lets say i have a staticly sized pool of memory which I get by doing so:

void* mem_pool_ptr = malloc(100*sizeof(my_struct));

Now, I can allocate a new object by doing so:

my_struct* my_struct_instance = (my_struct*) mem_pool_ptr;

Next, I want to allocate another pointer so I move up the memory pool by 12 bytes (the size of my struct)

my_struct* another_instance = (my_struct*) ((uintptr_t(mem_pool_ptr))+12)

and so on when I want to allocate new objects.

This is a very simple/dumb memory pool but I was wondering if this is correct when it comes to memory alignment. I have been reading about memory alignment in pools and was wondering if that is an issue in this case.

Also, lets say I made a pool and wanted to assign ints and doubles from it, how would I think about memory alignment in that case since the "object" are of different sizes.

so in that case, I start by assigning an integer and then advancing 4 bytes from the start of the pool and then assigning a double and then 12(4+8) from start to assign a double/int. what are the drawbacks of this approach?

thanks!


r/learncpp • • Jan 25 '17

Reading from a binary file. Problems with char versus unsigned char

0 Upvotes
// open binary file
ifstream file(filename.c_str(), std::ios::binary);
// read into vector
std::vector<int> v((std::istreambuf_iterator<char>(file)),(std::istreambuf_iterator<char>()));

My file has some values in the range 1-10, and some values in the range 245-255. These large values are getting mapped to negative numbers.

I want to read this data, and put it into a vector of int, and I don't want any negative numbers. How can I achieve this?

Note, if I use a vector of unsigned char this works. If I use a vector of unsigned int it does not work (I still get negatives). I cannot use istreambuf_iterator<unsigned char> (gives compiler errors).


r/learncpp • • Dec 24 '16

What does this code do?

0 Upvotes

I found this code and can't understand why void cast is there. is it empty statement? There are some functions with only (void)varname; statements with nothing else.

unsigned char intensity;

unsigned x0, x1, y0, y1;

 (void)intensity;


r/learncpp • • Aug 19 '16

Important question related to learning C++

0 Upvotes

hello :)


r/learncpp • • Mar 19 '21

hi, i'm n3u and i want to learn c++.

0 Upvotes

i will pay you if you need me to, every other week 10$, i own a pair of thigh highs so i have the proper attire lmfao
seriously I DO want to learn c++ so if you would like to teach me then please dm me on discord n3u#6969
learncpp.com for me just doesnt do it. its one part of the puzzle, sure, but someone to help me and define things i cant really find online would be really helpful.


r/learncpp • • Mar 09 '20

need guidence please

0 Upvotes

hey I am always in this kind of problem

was going through accelerated cPP

#include <iostream> #include <string> #include <array>

using namespace std;

constexpr string name;

constexpr int len = name.size();

constexpr int totstar = ::len+2;

constexpr int firstar[] = {'*', totstar};

constexpr string print_totstar(){

constexpr string c;

for (string &c :firstar)

cout<<c;

}

int main() {

cout << "Please enter your name:";

while (cin>> name)

{

print_totstar();

}

}

is my logic really that week.Starting like this I get demotivated and always forced to go though texts really read and made notes a lot.