« first day (669 days earlier)      last day (2167 days later) » 

2:00 AM
So.
I'm defining a level using a 1D array.
For example:
  const int level[] =
    {
        0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0,
        1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3,
        0, 1, 0, 0, 2, 0, 3, 3, 3, 0, 1, 1, 1, 0, 0, 0,
        0, 1, 1, 0, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 0, 0,
        0, 0, 1, 0, 3, 0, 2, 2, 0, 0, 1, 1, 1, 1, 2, 0,
        2, 0, 1, 0, 3, 0, 2, 2, 2, 0, 1, 1, 1, 1, 1, 1,
        0, 0, 1, 0, 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1,
    };
If I want to make a function create the array/return it.
How would I define it in my class?
Would it just be:
int *level;
And then have a function return an array?
I think it would... I'll try/test.
 
 
3 hours later…
5:34 AM
Is there a library function to compare two ASCII strings which are stored in an integer array?
 
5:46 AM
@Yashas Use the std algorithms (en.cppreference.com/w/cpp/algorithm) plus any predicate you like to compare the integers.
 
Ron
6:15 AM
@Justin Eeer, I meant where to keep those? In a separate file or scatter them around in other files depending on their use?
 
@Ron What was your question again? I can't find it.
 
@Ron @nobism
 
Ron
@nobism If you click on the left pointing arrow it will take you to the question.
 
Maybe this works:
16 hours ago, by Ron
Where to keep freestanding functions in terms of working with multiple headers and source files?
16 hours ago, by Ron
Put the entire definition inside some namespace in a separate source file or be normal and separate into declarations and definitions?
@Ron I frequently have a utils directory with commonly used functions, if that's what you mean
 
@Ron Be normal and separate declarations from definitions. But I'm also struggling with the same issue; where exactly to put functions to prevent having complicated private functions which can't be tested.
 
6:24 AM
If I start getting multiple related utils, and I'm allowed to add libraries at will, I'd go look for a library that does it.
@nobism Depending on how I want my project to be consumed, I layout my project differently. If it's a library, there's an include directory and a src directory. Headers in the include directory are what the user of the library can use, headers in the src directory are visible only to me. So where to put private functions that I want to be testable: extract them into their own headers under the src directory.
You can also make an internal folder or detail folder, similar to the whole namespace detail that people use
 
Ron
7:05 AM
Thanks. Appreciate it.
 
7:30 AM
@Justin Private functions can't be made testable just by putting them in a different directory.
 
Ron
7:45 AM
Why would I want to have a member inspector function of type const T&? As in this faq.
Why not simply make it T. I guess string is not a simple built in type.
 
8:04 AM
The linked part mentions "const reference or value"
On one hand, less copies, on other, less elastic, because with values you can produce a value on demand
But with cref return you're limited to returning something that exists and has lifetime managed by the receiver object
 
 
2 hours later…
Ron
10:03 AM
@milleniumbug All clear. Thanks.
 
10:29 AM
Regarding to make preparations for a boolean operation on a couple of 3d objects. I thought, to cache all objectinteractions(changing in their location) in an stack. Then i process the current/top one of the stack based on the operation the user choosed and clear the stack. When there was problem or the user choosed back, i undo all interactions in the stack.
hard to find the right approach
 
11:09 AM
@FerencRozsa I don't know what your question is, but have a look at the Command Pattern for undoing user actions (en.wikipedia.org/wiki/Command_pattern).
 
@nobism its not the undo itself its more whole approach
my approach
 
That's not a very complete program, but your Interaction object looks a bit like a command object which encapsulates actions.
 
11:32 AM
yes its just rapid typed to show the intention.
like i said, the undo itself is not the problem. its more the approach to cache all completed interactions when the user choosed to do a boolean operation...so iam able to undo all when the operation fails or the user choose back, which also goes into an undo.
 
you don't need to cache at every undo operation
 
i do it only, when user choosed "boolean operation" from menu.
from there i cache all grab/move interactions in the stack
so i can undo all location changes when possible
@ratchetfreak can you explain it ratchet
 
 
1 hour later…
1:02 PM
hello, i got this question after i had annother question of c# and now im curious, in c++ i can make for example a void func() and inside i can do return; to leave the function. my question is, can i use that that function returns in anny way? even tho its a void? idk about how usefull this question is, im just curious about it
and another question, how do i return null from a function? is null even a type? something like bool?
 
@jeyejow nullptr is not a type per se.. but there is std::nullptr_t which is used for overload disambiguation
 
so if i wanted to return a null in a function it wouldnt matter the type? i just do return null?
 
@jeyejow why would you just return nullptr?
how does that differ from having int and returning 0?
 
the same as 0 returning null?
 
@jeyejow no, but I'm not sure why you would return nullptr anyway since that doesn't have a type
C++ is a strongly typed language
 
1:17 PM
hmmm
what does strongly typed mean?
 
In computer programming, programming languages are often colloquially classified as to whether the language's type system makes it strongly typed or weakly typed (loosely typed). Generally, a strongly typed language has stricter typing rules at compile time, which imply that errors and exceptions are more likely to happen during compilation. Most of these rules affect variable assignment, return values and function calling. On the other hand, a weakly typed language has looser typing rules and may produce unpredictable results or may perform implicit type conversion at runtime. A different but...
 
1:30 PM
ohhh ok
thanks!
 
2:21 PM
What does
error: initializer for flexible array member 'const int Level::level []'
     };
This error mean?
Trying to do this:
class Level {
private:
	// Tilemap.
	Tilemap map;
	// This pointer is for the gameWindow. It's useful when drawing the window.
	sf::RenderWindow *gameWindow;
	const int level[] =
    {
        0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0,
        1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3,
        0, 1, 0, 0, 2, 0, 3, 3, 3, 0, 1, 1, 1, 0, 0, 0,
        0, 1, 1, 0, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 0, 0,
        0, 0, 1, 0, 3, 0, 2, 2, 0, 0, 1, 1, 1, 1, 2, 0,
oh...
last comma
Nope
Doesn't fix it
 
@Annabelle make it constexpr and static
 
Why does that work?
But not const?
 
because it's compile time constant and the compiler doesn't have to emit code for it
 
because array size type deduction doesn't work for non-static data members
 
Okay
 
2:32 PM
also, obligatory "lol C arrays"
 
Oh I'm just testing the code out right now
I'll change it to a vector when I generate my map
Hmm I get an undefined reference to the array
When I try and use it in the constructor
 
@Annabelle it's static now, you need to reference it by Level::level
 
Even within the class?
o.O
 
@Annabelle you made it const, which means you shouldn't be modifying it
so static is fine
and yes
 
Mhm ok
Level.cpp:(.rdata$.refptr._ZN5Level5levelE[.refptr._ZN5Level5levelE]+0x0): undefined reference to `Level::level'
collect2.exe: error: ld returned 1 exit status
Even if I call it using Level::level
 
2:47 PM
387
Q: How to initialize private static members in C++?

Jason BakerWhat is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors: class foo { private: static int i; }; int foo::i = 0; I'm guessing this is because I can't initialize a private member from outside the cl...

 
Oh hmm..
OK
When I initalize in .cpp file
do I do it in any function
or outside everything?
Got it!
thanks
and I learned something new
 
3:53 PM
@Annabelle you can initalize only ones...in combination with/part of the definition. Further it is just a assignment.
 
 
1 hour later…
5:03 PM
@nobism Not if they literally are private member functions, but if they are "private" implementation-detail functions, then yes. Refactor the private member functions to mostly call an implementation-detail free function, put that free function in a private directory. Then you can test it
 
5:44 PM
Initialization order of class members is the order in which they are declared. However, isn't relying on this brittle? Is there a non-brittle way to ensure that one "member" outlives another?
 
"first first member is created before the second, and dies after the second" is guaranteed
 
Yes, but I'm worried that would be brittle
 
I guess you could enforce that A is created before B, by making B accept a reference to A in the constructor
well, ok, not really
not in a struct
but this would work if these were two local variables
 
Yeah. I could try something like move the member that needs to outlive into a private base-class, since those are initialized first, but I'm not convinced that's a good solution
 
6:09 PM
I think it's best to just rely on it, but put a prominent comment saying that A must outlive B
*wishful thinking* If only: static_assert(A outlives B);
 
http://en.cppreference.com/w/cpp/language/overload_resolution
I've been reading the 'Ranking of implicit conversion sequences' and don't understand why they need 2 separate lists there
1-6 and 1-4
Aren't all those point just a single (ordered) list?
 
6:38 PM
@ledonter I'd guess it's written that way because that's how it's written in the standard. ([over.ics.rank]/2: "Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies:"). Pretty sure it ended up that way in the standard for hysterical historical reasons. They wanted to add more distinguishing points, but the first list took so much work to get right, nobody wanted to touch it for fear of breaking something.
So, they did like software developers for time immemorial: instead of modifying a function that was already too complex, they wrote a wrapper around it.
 
heh, lazy lazy committee
ok
 
@ledonter Look through the history. Leaving that alone isn't laziness, just maintaining some degree of sanity (seriously: this resulted from years of work and many modifications to get it "just right").
 
7:00 PM
@JerryCoffin well of course I don't seriously think that the committee is a bunch of deadbeat junkies :D
On the same page: If the parameter type is std::initializer_list<X>, and there is an non-narrowing implicit conversion from every element of the initializer list to X, the implicit conversion sequence for the purpose of overload resolution is the worst conversion necessary.

Why the worst necessary? not the best one
 
I notice that it doesn't say "worst conversion possible" but "worst conversion necessary". I'm not sure what that means, though
 
i have a question about good code writing
 
Oh I think it's saying this: "the rank of the conversion sequence involving a std::initializer_list<X> is the worst rank of the conversion sequences of the elements"
 
bool func(int *i, int tam)
{
    for(int k = 0; k < tam; k++)
    {
        if(k[i] == 5)
        {
            return true;
        }

    }

    return false;
}


int main()
{
    int arr[10] = {1,2,3,4,5,6,7,8,9};
    int tam = 10;
    bool f = func(arr, tam);
    return 0;
}
does that function look good? should i code it in another way?
i know i dont use the value it returns for nothing, its just an example
i was wondering if that is the correct way to do that function
to just return a thing in the middle of the for cicle if it finds it
 
It looks decent, but there's a better way: std::any_of
 
7:08 PM
so it is ok in terms of memory to do what i did?
do a return inside a for cicle?
 
What does "in terms of memory" mean? You use a constant amount of memory in that function.
bool func(int *i, int tam)
{
    return std::any_of(i, i + tam, [](int val) { return val == 5; });
}
 
hm, is it bad practise to do return inside a for cicle?
 
@Justin cool, didn't think of that
 
@jeyejow No. Returning inside a for loop is completely natural, and the "obvious" alternative would be slower.
 
@Justin oh ok, thanks! i was wondering that
 
7:11 PM
Why slower?
 
This is the "obvious" alternative:
bool func(int *i, int tam)
{
    bool found = false;

    for(int k = 0; k < tam; k++)
    {
        if(k[i] == 5)
        {
            found = true;
        }
    }

    return found;
}
It loops over the entire array whether the element is in the array or not. The prior solution exits early if the element is in the array
 
Oh, I thought you're saying about any_of case
ok
 
 
2 hours later…
8:51 PM
What is the better way to do this:
enum class AnimalType
{
DogAnimal,
CatAnimal
}

class Animal {}

class Dog : public Animal {}
class Cat : public Animal {}
Animal* getAnimalFromEnum(AnimalType type)
{
   switch (type)
   {
        case (AnimalType::DogType):
            return new Dog()
            break;
        case (AnimalType::CatType):
            return new Cat()
            break;
   }
}
 
Why do you need AnimalType at all?
Why is getAnimalFromEnum(AnimalType::DogAnimal) something you'd write instead of new Dog();?
 
Oh I want to basically get a new animal.. object based on user input
I'm probably overthinking the fuck out of this
 
So, first you're parsing the user input into the AnimalType, then using that to create the appropriate Animal. If there is no other reason for AnimalType, just skip that intermediate step, and produce an Animal once you can tell which type you want.
You could use something like std::unordered_map<std::string, std::function<Animal*()>>
 
it's a factory that does ownership transfer, so return a std::unique_ptr<Animal> instead
 
(of course, strongly prefer std::unique_ptr<Animal> instead of Animal*)
 
9:01 PM
so I return a unique_ptr<Animal>
and by unordered map. you mean basically map the string input into
wait
How does that map work?
Passing it a function?
Okay I think I get it
 
Will people answer c questions here?
 
It's in the tags
 
There is a c in the tags...
 
awesome
 
Is it possible to extract edge weights while performing a depth first search using boosts graph library?
 
9:06 PM
@Annabelle Whether you want to have a Map<String, AnimalCreator> like what I suggested or do roughly like what you did (encoding the map in code), is not clear-cut. It depends on how extensible you want it to be (e.g. do you want to be able to add new "types" at runtime), and other things as well. It may well be simpler to just have if (value == "dog") return std::make_unique<Dog>(); else if (value == "cat") return std::make_unique<Cat>(); ...
 
Well I'd like to be able to include more animals
later on basically
Not adding at runtime
but at compile time
 
structs can be initialized using curly braces, like struct blah blahblah = { .x =1, .y = 1};, can you use funtions that return values in that list like struct blah blahblah = { .x =getInt(), .y = 1};
 
@Annabelle TBH I'd probably go for your approach at the start (I'd probably not even use an enum, but just check the contents of the string directly), and if it starts to become a problem, then consider alternatives
 
Well how would I be able to extend this
so I can handle a larger amount?
That's more so the point I feel
 
@chewbapoclypse Yes: godbolt.org/g/d3NVut
@Annabelle My suggestion is to start with what you have there (it's simple code), adding types by expanding the switch, and if you feel that it's not nice, or that it's causing problems, then consider alternatives, such as what I mentioned with something like std::unordered_map<AnimalType, std::function<std::unique_ptr<Animal>()>>. I don't think there's a clear answer. It's situational what the right approach is, and I personally think it's good to start with simple code
 
9:16 PM
I guess what I'm just not understanding is, how does the map work exactly.
I would map a given animal type to.... what exactly?
 
@Justin wow I have never see return val; used like that
 
mymap.insert(std::make_pair<AnimalType, std::function<std::unique_ptr<Animal>()>>( , ));

(What goes inside maybe...?)
 
@Annabelle Something like this:
#include <functional> // for std::function
#include <unordered_map>
#include <memory>

using AnimalCreator = std::function<std::unique_ptr<Animal>()>;

namespace {
    std::unordered_map<AnimalType, AnimalCreator> const animalCreators{
        { AnimalType::DogAnimal, []{ return std::make_unique<Dog>(); } },
        { AnimalType::CatAnimal, []{ return std::make_unique<Cat>(); } },
    };
}

std::unique_ptr<Animal> getAnimalFromEnum(AnimalType type) {
    return animalCreators.at(type)();
}
@chewbapoclypse You mean returning the struct by value?
 
Why do we have a namespace?
 
9:21 PM
@Annabelle It's an anonymous namespace. animalCreators is a global in that example. If you've heard of static globals, this is the same thing; it prevents linker errors for name collisions of globals.
 
Oh um...
So if I have that inside a function/my main..
I don't need the namespace?
 
Yes. But if you just put it directly inside of the getAnimalFromEnum function, you'd be constructing the same map every time you call the function, which is expensive.
You don't want to keep constructing the map if it's always going to be the same value, that is.
 
Okay I see.
Um
 
@chewbapoclypse Weird. I would've thought that simple structs would normally be returned by value in normal C code. You can even return directly: godbolt.org/g/BGXABk
 
Why don't we give the namespace a name..?
What does making it anonymous do?
 
9:25 PM
The compiler automatically gives it a "unique name"
If you didn't do this, if any other file also doesn't do it and has something with the name animalCreators, you can get linker errors.
 
Okay
 
@Justin I can't say I'm very excited about this. I'd at least consider something more like this:
class animalFromEnum {
    static const std::unordered_map<AnimalType, AnimalCreator> animalCreators{
        { AnimalType::DogAnimal, []{ return std::make_unique<Dog>(); } },
        { AnimalType::CatAnimal, []{ return std::make_unique<Cat>(); } },
    };
public:
    static animal operator()(AnimalType type) {
        return animalCreators.at(type)();
    }
};
 
If everything is going to be static anyway, I don't see the point of putting it in a class.
But I do like putting it in a class and making things non-static
 
@Justin IMO, almost any time you depend on the namespace implied by a translation unit, it's at least mildly suspect.
 
What does this mean:
static animal operator()
 
9:32 PM
@Justin Yes--this should probably be a ctor for animal.
 
Does anyone know of any graph algorithms that work on undirected graphs with weighted edges?
 
@Annabelle it's an operator that can be used without an instance of the class. You pretty much have to use a using animalFromEnum to make use of it.
 
@JerryCoffin I don't think it compiles, though godbolt.org/g/54yHDT
 
Man this is complicated.
 
@Sailanarmo Usually you start from something you want to accomplish, then figure out how to accomplish that...
 
9:36 PM
@JerryCoffin I know what it is I want to accomplish. I just need to apply the right algorithm to it. I'm trying to traverse a graph with weighted edges. The starting vertex will have a string "Hello" or something like that. I will then visit the next vertex in the graph and I will mutate the string in that vertex, based on the weight of edge connecting vertex1 and vertex2.
However, I am not exactly sure on how to do that given Boost's depth_first_search algorithm
 
@Annabelle Yeah. This is something that has a large amount of variations of ways of doing it. Each one alone isn't too complicated, but considering all of them can be overwhelming.
 
@Justin Yeah, after some thought, this direction is probably wrong.
 
So uh probably a dumb question but how do I use the
unordered map in the namespace
my intuition was something like this:
namespace {
    std::unordered_map<AnimalType, std::function<std::unique_ptr<Animal>()>> const animalCreators{
        { AnimalType::DogAnimal, []{ return std::make_unique<Dog>(); } },
        { AnimalType::CatAnimal, []{ return std::make_unique<Cat>(); } },
    };
}

std::unique_ptr<Animal> getAnimalFromEnum(AnimalType type) {
    return animalCreators.at(type)();
}

int main(int argc, char const *argv[]) {
	std::unique_ptr<Animal> myPet;
	myPet.getAnimalFromEnum(DogAnimal);
	myPet->myType();
	return 0;
 
@Sailanarmo Hmm...yeah, it's been a long time since I used BGL, and it's one of those that (at least to me) takes a while to get accustomed to its way of doing things.
 
But this is obviously incorrect.
 
9:42 PM
std::unique_ptr<Animal> myPet = getAnimalFromEnum(DogAnimal);
 
Damn it okay
 
Except it would be AnimalType::DogAnimal, as AnimalType is an enum class
 
for some reason I assumed pointer
meant the . or ->
Not an assignment
Why is it an assignment exactly?
 
@JerryCoffin the problem is getting depth first search to report the edge weight, there is a a handy source and target function that can return the vertices of an edge. But I need the opposite, two vertices that will return an edge weight
 
@Annabelle getAnimalFromEnum is a free function which returns a std::unique_ptr<Animal>. We are storing the result of the function in a variable.
myPet.getAnimalFromEnum(...) would only work if getAnimalFromEnum was a member function of std::unique_ptr<Animal>
 
9:45 PM
Okay.
That makes sense
 
@Annabelle getAnimalFromEnum is a function that returns a pointer. We then save that pointer. To do something, we'd then do something like myPet->rollOver();
 
Right! That makes sense. :)
Thanks.
Lots more reading for me to do.
 
nwp
10:36 PM
Why does std::list::remove exist? Isn't it covered by std::remove already?
 
my best guess so far is "to accomodate brick types" (nonmoveable)
 
11:36 PM
@nwp list::remove isn't equivalent to std::remove. It's more like the erase-remove idiom--it actually erases nodes from the sequence.
So, when you do an erase(remove...) from a vector, the remove moves the items being kept toward the beginning, then the erase just reduces the count of items, so you get exactly on traversal of the vector. With a list, it could rearrange nodes, then require an erase to actually erase the nodes being removed--but if you did, it would require a second trip through the erased nodes to actually delete that node's memory. In a fit of insanity, they decided to optimize that particular operation...
at the expense of making it inconsistent with remove everywhere else (and it's hardly as if anybody would be using list if they cared a lot about the speed of traversing some nodes).
 

« first day (669 days earlier)      last day (2167 days later) »