/dpt/ - Daily Programming Thread

old thread: What are you working on, Sup Forums?

Other urls found in this thread:

stackoverflow.com/questions/3044690/operator-stdstring-const
en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2
en.cppreference.com/w/cpp/language/copy_constructor
twitter.com/NSFWRedditVideo

Ever open up a project, look at it, sigh, then close it?

feelio when no felix gf

catfag pls go

Cute Felix

Does Sup Forums like nested C macros?

using namespace std;
using namespace boost;

Top of all my programs.

...

>look at me im an absolute brainlet
good for you

Was being facetious. Those two lines of code don’t belong anywhere.

>the perfect girl doesn't exi--

>social media
>smartphones
>obnoxious normalfaggotry
will it ever end?

job application wants me to attach a code sample. should l put a snippet of my c compiler or an entire react app? (it's an internship position)

*blocks your path*

If I was asked for a code sample, I'd just print out the line-numbered source code for one of my projects in it's entirety.

Be honest with me Sup Forums, is Java a meme?

nope, it's easy to get into and it just werks.
also less struggles getting employed

I kind of assumed it was garbage since nobody here talks about it.

Code in c++.

So doing some dumb asynch socket programming in C.

I have a thread handling recieves in an infinite loop.
Anyone have an idea how I'd close the thread once it stops recieving data?

It should stop relatively quickly, so I was just going to call a sleep in my main function then close the thread, but I've heard just killing the thread randomly is bad practice, is there a "good" way of doing this?

if (stream->done)
break;

>not declaring what you're using the headers for

#include
using std::cout;
using std::cin;
using std::endl;
#include
using std::swap;
using std::sort;
#include
using boost::multiprecision::cpp_int;

Well, not many employed people have time to waste on an online meme discussion board

...

the dasgupta book is unironically good though

dafuq

I always do using std::string and using std::vector

What is the best online platform for competetive programming? i want to improve my algorithms knowledge

This.

Ah sorry, forgot to say using UDP.
I don't really have a solid way of telling when its done other than that I stop recieving stuff.

>"Hurr durr all search problems are NP"

Dasgupta is a retarded pajeet.

stackoverflow.com/questions/3044690/operator-stdstring-const
>It is a cast operator. Any class that defines this type can be used anywhere a std::string is required.

en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2
>no std::string type

Wew lad. Here's what I think is going on. std::cout takes one of your Foos, never casts it to a std:string. Normally cout takes a std::string and casts it to a c_string and it just werks. So it tries to find an overload for a Foo type and fails, spitting out a cryptic error message for the last overload (basic_ostream&&). If cout casted to a std::string it would've werk'd.

This works:
#include
#include
class Foo
{
std::string name;
public:
operator std::string() const{
return name;
}
Foo(){
name = "Test";
}
};

int main(){
std::string foo = Foo();
std::cout class Foo
>constructor named Stuff
>defining a constructor with a parameter then saying
std::cout C++

Well you're using UDP.
You shouldn't care if stuff never gets received or it cuts off half-way through.
You should have a functional understanding of the UDP data you're receiving so as to know how to interpret incomplete data.

Just detach the thread and let the thread kill itself after it sleep-waits long enough for more data and never gets it.

Also use std::thread and get with the 21st century already.

B+Trees and Fibonacci Heaps... in "C". Every programming should code one or both of these everyday.

:)

Well my care isn't about the data. Its how to close the thread after a set amount of time.
i.e.
I'd have something

>sending stuff
>thread is recieving stuff in return
>all stuff sent
>wait 5 seconds for returns to be sent back
>kill recieving thread
if shit doesn't all come back I don't really care, but I do need to care about at least some of the stuff.
Just don't know how to kill that thread.

>even though in the string header there is an overloaded operator

>girl

optimizing a 2d software renderer in C

void draw_sprite(struct sprite *sprite, Screen screen, Pixel mask)
{
Pixel *i = sprite->gfx;
Pixel *o = &screen[sprite->y][sprite->x];
for (Pixel y = 0; y < sprite->height; ++y) {
for (Pixel x = 0; x < sprite->width; ++x) {
if (*i != mask) {
*o = *i;
}
++i;
++o;
}
o += GAME_WIDTH - sprite->width;
}
}


I wonder if there's anything else I could do to speed this up.

long struct names are fine, if you're gonna be using them as context handles, just shorten their variable names to spr or something.

What type is pixel ?

why have two loops when you could just do one at width * height

whatever

unsigned int

how? I think it's more math per pixel

multiplication is one processor cycle
you're running a nested loop on an essential drawing function

it's more than just multiplication. If I only keep track of one variable, I have to do a bunch of stuff to "get back" the implied X and Y positions.

>>hurr durr all search problems are np
he gave an effecient way to prove them -- the line by line check.

wikipedia:
>In computational complexity theory, NP (for nondeterministic polynomial time) is a complexity class used to describe certain types of decision problems. Informally, NP is the set of all decision problems for which the instances where the answer is "yes" have efficiently verifiable proofs

Hi guys, dumb question coming through. I am new to C pointers, so I am trying understand this.
Is this:
int **seqList;
int *seqCount;

seqList = malloc(N*sizeof(int *));
seqCount = malloc(N*sizeof(int));

The same as this?

int seqList[N][N];
int seqCount[N];

If not, could you please explain what they are, or what would be their equivalent? Hopefully my question makes sense. Thanks in advance.

No. The seqList is a matrix in the second code. In the first its a array of int pointers.

>she implements her own ghetto function inlining using macros
Now that, my friend, is pretty fucking stupid. I'll tell you what I do, though, which isn't quite as stupid: have a library of matrix math macros that do symbolic computation at compile time, so that if, for instance, you multiply a matrix of some runtime values by a matrix full of values known at compile time (especially ones and zeros), some of the otherwise runtime computations get optimized away.

int seqList[N][N];
// int *seqList = malloc(sizeof(int) * (N * N));
int seqCount[N];
// int *seqCount = malloc(sizeof(int) * N);

To dynamically make a multi-dimensional array, you can allocate it as a flat array and access any array member using multiplication
eg.
seqlist[(N * i) + j]
// equivalent to seqList[i][j]

Thanks for the replies. I was making that question because of this piece of code that I found:

#include
#include
#include
#include

int main() {
int N;
int Q;
int t, x, y;
int seq;
int lastAnswer = 0;
int **seqList;
int * seqCount;
int index;
scanf("%i", &N);
seqList = malloc(N*sizeof(int *));
seqCount = malloc(N*sizeof(int));
for(int i = 0; i < N; i++)
seqCount[i] = 1;
scanf("%i", &Q);
for(int i = 0; i < Q; i++){
scanf("%i %i %i", &t, &x, &y);
if(t==1){
seq = ((x^lastAnswer)%N);
seqList[seq] = realloc(seqList[seq],seqCount[seq]*sizeof(int));
seqList[seq][seqCount[seq]-1] = y;
seqCount[seq]++;
}else
{ seq = ((x^lastAnswer)%N);
index = y%(seqCount[seq]-1);
lastAnswer = seqList[seq][index];
printf("%i\n", lastAnswer);
}
}
for(int i = 0; i < N; i++)
free(seqList[i]);
free(seqList);
free(seqCount);


Here is where my confusion starts:
if(t==1){
seq = ((x^lastAnswer)%N);
seqList[seq] = realloc(seqList[seq],seqCount[seq]*sizeof(int));
seqList[seq][seqCount[seq]-1] = y;
seqCount[seq]++;
}else
{ seq = ((x^lastAnswer)%N);
index = y%(seqCount[seq]-1);
lastAnswer = seqList[seq][index];
printf("%i\n", lastAnswer);


Why are you able to call seqList[seq][seqCount[seq] -1] = y this way? Is it because earlier we reallocated memory on seqList[seq] = realloc(seqList[seq], seqCount[seq]*sizeof(int)); that we are able to call it like a 2D array? Any help is greatly appreciated it. I know this may seem like a dumb question, but I gotta clear this doubt before moving on.

Yes, it's because the reallocation.

See, the original array was only able to point to one int pointer. After the reallocation, its now able to point to an entire int array of seqCount[seq] size. That means its an array of int arrays with variable sizes, and that calling is tottaly possible thanks to this.

>seqList = malloc(N*sizeof(int *));

You want:
seqList = malloc(N*sizeof(int *));
seqList[0] = malloc(N*N*sizeof(int));
for(int i=1; i

guys I just learned macros...
The hard way :
#define foo(m) bar(m); exit(0)

if(something)
foo("just fuck my shit up");

Awesome! Memory allocation is extremely fascinating, I must say. Now this code makes complete sense to me. Thanks a lot, mate!

making "fake" multidimensional arrays by allocating an array of pointers and then allocating memory at every single pointer is insanely wasteful and it's time complexity scales exponentially with any non-trivial size or even if you add another dimension.

>she uses dynamic memory allocation
When will they learn?

That looks pretty neat, thanks user.

Retard.
#define DIE(fmt, ...) do { \
char buf[LOG_MAX]; \
snprintf(buf, LOG_MAX, "FATAL ERROR: %s:%d %s\t" fmt "\n", __FILE__, __LINE__, __func__ ##__VA_ARGS__); \
log_function(buf); \
exit(-1); \
} while(0)

>making "fake" multidimensional arrays by allocating an array of pointers and then allocating memory at every single pointer is insanely wasteful
That's not what he's doing. He just allocates a big chunk of memory and points into the start of each row.

>he allocates a bunch of extra memory "just in case" and then his program panics when it inevitably hits limits

Are you retarded? The only other way to allocate a multidimensional array (int**) is

seqList = malloc(N*sizeof(int *));
for(int i=0; i

>The only other way to allocate a multidimensional array
Not him, and I understand what you did there, but it may well be faster to just allocate a 1D array and index it with row*cols+col if you're doing random access, or (if you're doing sequential access) to compute the start of the row before the loop instead of looking it up in a dynamically allocated array.

What's the reason for using the do while(0) ?

>What's the reason for using the do while(0) ?
To prevent the buf variable in the macro from polluting the caller's scope, and also because it allows you to finish the DIE "call" with a semicolon as if it were a normal function.

the only reason to allocate an array with double pointers is if it's jagged, i.e.
[0] = "AA"
[1] = "AAAAA"
[2] = "A"
[3] = "AAA"
Even then, you could be better off storing a list of offsets than pointers to the data itself. It's usage-dependant.

get new {} scope.

dude you don't need the "while" there. Every C compiler just werx with while-less arbitrary brace scopes.

I see thanks.
Is there a reason why we can't just use {} for scoping ?

not knowing that you can omit the while

You can include arbitrary { } blocks anywhere, it lets you bypass ANSI C89's limitation on not mixing declarations and code.
The compiler interprets this as making another
stack frame, and anything declared inside of the { } block will go out of scope once it ends.

As I said, it's to allow you to put a semicolon after the DIE() without breaking anything. For instance, if you just use {} and use the thing in an if-else with a semicolon:
if(1 != 1)
DIE();
else
printf("whew");

It will expand into this:
if(1 != 1) {
// the crap inside the macro
};
else
printf("whew");

Which will error, because the ; prevents the thing from being parsed as an if-else pair. do-while with a semicolon is just a normal statement, so it would work.

>these creatures are giving beginners "advice"
I hate this place more with every day...

>gatekeeping

why don't you screencap the thread, it'll last longer on reddit

Hello guys, Im learning C++ for a month now and trying to write a program which would sort random numbers by not using operating memory (except for a few variables).
Here is my code -> pastebin dot com slash r3hCYpKw
I get this error -> use of deleted function ‘MyArray::MyArray(const MyArray&)’
selectionSort(arr, n);
Also this error -> MyArray::MyArray(const MyArray&)’ is implicitly deleted because the default definition would be ill-formed:
class MyArray{
And this -> use of deleted function ‘std::basic_fstream::basic_fstream(const std::basic_fstream&) [with _CharT = char; _Traits = std::char_traits]’
In file included from /home/....

What does these error mean?
I haven't used deleted anywhere in my code, why does my function get deleted?

>hurrr y-y-you're gatekeeping
I actually just explained to this guy the real reason why do{}while(0) is used instead of {}, you mongoloid. Fuck off back to Sup Forums, dirty nigger.

And you know, user, the reason I know it and you don't is that you, as a fucking Dunning-Kruger sufferer, when you see something you don't understand, you assume whoever wrote it doesn't know basic C.

pls don't fight.

I'm used to retardation ITT, but there's really nothing worse than people who learned C yesterday thinking they're experts now and that code they don't understand must be the result of incompetence on the part of others. For example:

>he has brainlet wojaks saved on his computer unironically
don't reply to my posts again

>why do you have photos of me and my friends on your computer?
Because I'm a big fan of the /dpt/ clown cart.

At its peak popularity, the brainlet wojak was /dpt/'s only way to communicate.
Just saying.

lol wtf so angry

the real solution is don't use big dumb macros anyway

this is why i don't come here anymore
anyone who gains any amount of skill outgrows this general almost immediately

>this is why i don't come here anymore
And yet you're here.
>anyone who gains any amount of skill outgrows this general almost immediately
Are you mentally a paraplegic? Because you just shot yourself in the foot and you didn't even feel it.

why are you so angry?

or, you know, use a real language where the compiler does that for you

>use a real language where the compiler does that for you
Looks like you didn't understand anything I said, because the compiler doesn't do it for you in any "real language".

>coming here for anything more than shilling your [insert favourite language]
>thinking this is anything more than a place to freely mock rustlets

>thinking the post he's replying to says anything about why anyone comes here
That reading comprehension ability...

oops meant for

A hobby mmo rpg project and finding employees to write scala. These are not related.

use c99 nigger
int (*mat)[m] = malloc(n * sizeof *mat);

It is because of arcane rules on which constructors you get by default, depending on how your class is implemented. In your case, the copy constructor is the one that the missing one.
en.cppreference.com/w/cpp/language/copy_constructor
The copy constructor is being invoked since you are passing a MyArray to selectionSort by value. You could pass it by reference instead:
void selectionSort(MyArray &arr, int n)

Thank you

Because #defines are cancer

>pastebin dot com slash r3hCYpKw
pastebin.com/r3hCYpKw

To expand on this:
#include

struct A {
std::ifstream fs;
};

void foo(A a) {}

auto main() -> int {
A a;
foo(a);
}


This fails to compile like this:
:3:8: error: use of deleted function (...): note: declared here
basic_ifstream(const basic_ifstream&) = delete;


Meaning that your class default constructor will get deleted if one of its members deletes its default constructor.

>#defines are cancer
You have no idea how many times I wished it at least had that cancer when programming in shitlangs like Java and C#. Text macros are primitive, but you can get a surprising number of things done with them if you're a non-retard.

>int getRandomNumber(int min, int max) {
static const double fraction = 1.0 / (static_cast(RAND_MAX) + 1.0);
return min + static_cast((max - min + 1) * (rand() * fraction));
}


Fuck no. Do this

#include
#include
int getRandomNumber(int min, int max) {
thread_local static std::random_device rd;
thread_local static std::seed_seq seeds{
static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()),
rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()
};
thread_local static std::mt19937 mt{seeds};
return std::uniform_int_distribution{min, max}(mt);
}


>void selectionSort(MyArray arr, int n){
>int n

MyArray already stores its length. You don't need to pass it externally.