Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Adahn the nameless
Jul 12, 2006

HFX posted:

Yes and Yes.

I'm trying to remember what books I used to recommend for C++. I think Ivor Hortons Visual C++ 6 was pretty good for learning the basics of C++ and Object Orientation (ignore second half of the book which is about MFC programming). I think there was an even better one, but it too would be done by Wrox. Once you have the basics, Professional C++ and the Bjarne Stroustrup book are worth reading. I think the Dietel & Dietel C and C++ book are good too (ignore the rest of their stuff).

Anyway, what you want to learn to do with an object oriented language like C++ is to hide details that are uninteresting to client code. Learn to have single responsibility principles. Example: Your node class for a linked list only needs to know its neighbor(s) and what it is storing. Your list class needs to know how to store nodes to ensure correct placement and retrieve items out of those nodes when asked.

Thanks for the help.

I read Accelerated C++ a while back, and I'm using this as a kind of refresher because it's much easier to stay motivated if I'm doing a self-directed project than if I'm doing exercises out of a book.

Adbot
ADBOT LOVES YOU

Toanek
Feb 21, 2008

It's a fiesta of personal triumph!
For whatever reason I keep getting little black boxes popping up when I try to blur my fractal flames. :( Don't know a whole lot about C++ or math so it's probably something simple and obvious. Lowering blur and sampling more flames makes em show up less.

Blur function

General quickie render:

Click here for the full 900x900 image.


More sample, less blur:

Click here for the full 900x900 image.

OddObserver
Apr 3, 2009
Aren't you changing the image as you're blurring it? If so, then the computation for the subsequent pixels may get badly screwed up as they'll refer to new values other than old ones.

Edit: might also need to clamp your output to make sure it's in range. Not sure w/o looking at the math really carefully (and even then I personally probably won't know).
Edit #2: you also seem to be running off the edges there.

OddObserver fucked around with this message at 16:29 on Aug 5, 2010

Yakattak
Dec 17, 2009

I am Grumpypuss
>:3

Quick question about books/tutorials. I have a lot of experience in Objective-C and C#, and some C, but I want to learn C++. Anyone know any books that doesn't teach you what an int is, but teaches you the C++ fundamentals, making classes and all that?

Yakattak fucked around with this message at 16:34 on Aug 5, 2010

Toanek
Feb 21, 2008

It's a fiesta of personal triumph!

quote:

Edit: might also need to clamp your output to make sure it's in range. Not sure w/o looking at the math really carefully (and even then I personally probably won't know).

Whoops! I'd tried a check to see if stuff was goin over the limit but it turned out I've got some negative numbers kicking around. You rock!

Sneftel
Jan 28, 2009

Yakattak posted:

Quick question about books/tutorials. I have a lot of experience in Objective-C and C#, and some C, but I want to learn C++. Anyone know any books that doesn't teach you what an int is, but teaches you the C++ fundamentals, making classes and all that?
Thinking in C++ is a great guide to C++ for people who are already C programmers. And you can't beat the price.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

Yakattak posted:

Quick question about books/tutorials. I have a lot of experience in Objective-C and C#, and some C, but I want to learn C++. Anyone know any books that doesn't teach you what an int is, but teaches you the C++ fundamentals, making classes and all that?

Koenig & Moo ("Accelerated C++") is still the best

MrMoo
Sep 14, 2000

In a single threaded application how can MSVC 2008 and 2010 show different values for LHS & RHS of a simple assignment?

OddObserver
Apr 3, 2009
Uninitialized field, perhaps? ...Maybe the pgm_getaddrinfo call returns 0 addresses but doesn't fail? (I am not familiar with those APIs at all)

Edit:
VVVVVVVVVVVVVVVVVVVVVVVVVVVV
Sorry. I completely misread the question. Very weird indeed. Did you try ultra-clean builds cleaning out PCHes and stuff like that?

Edit #2:
What it seems to say is that what the debugger things of the layout of structure is different from what the compiler thinks.
32/64-bit mismatch, maybe?

OddObserver fucked around with this message at 04:59 on Aug 6, 2010

MrMoo
Sep 14, 2000

I have no idea how to debug it, the function is in a static C library, the application is a trivial C++ one filer. Performing the same assignment inside the end of the pgm_getaddrinfo() call returns the expected value (2).

The code works fine under everything else, Linux, FreeBSD, OSX, Solaris, even Wine, and Windows with MinGW and MinGW-w64 builds.

http://code.google.com/p/openpgm/

:negative:

It's not a stray #pragma pack, it's not differences of ADDRESS_FAMILY, I can try forcing NT version in the build as for MinGW I used 0x501.

MrMoo fucked around with this message at 04:57 on Aug 6, 2010

MrMoo
Sep 14, 2000

Changing all the code from C89 to C++2003 didn't help either apart from time wasting.

Moving all the static library code into the application project did resolve the issue. Something fruity with MSVC static libraries?

MrMoo
Sep 14, 2000

Magic from the WIN32 definition apparently. MSVC adds it to console applications but not static library projects. Winsock2 stuff compiles without it but apparently is broken.

What a fantastic platform.

:negative:

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I wondered if anybody here has done serious development using CEDIT on emacs. I just installed it in the hopes of screwing with it this weekend.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


While I'm screwing around with floating point precision stuff in the general thread, a curiosity that google isn't helping with: is there a standard/accepted implementation of fixed-point decimals (in the standard or boost or whatever) or is that a roll-your-own/varies-between-compilers sort of thing?

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender
Integer arithmetic?

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Ledneh posted:

While I'm screwing around with floating point precision stuff in the general thread, a curiosity that google isn't helping with: is there a standard/accepted implementation of fixed-point decimals (in the standard or boost or whatever) or is that a roll-your-own/varies-between-compilers sort of thing?

I'm sure there are packages out there, but basic fixed point arithmetic is pretty easy to implement on your own.

Let's say that you take a 32-bit integer and use the low 8 bits for the fractional part. To add or subtract two FP values, you just add or subtract the corresponding integer representation.

Multiplication and division require slightly more care because you have to correct for the extra/lost bitshifting. To multiply, multiply the two integer reps and then right-shift by the number of fractional bits. For division, left-shift the dividend by the number of fractional bits and then divide. (There are some overflow/underflow issues here -- fixing those is an exercise for the reader [I'm lazy].)

For bonus points, make a template class that takes parameters for the base type and the number of bits to use for the fractional part, and overload all the operators.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

Ledneh posted:

While I'm screwing around with floating point precision stuff in the general thread, a curiosity that google isn't helping with: is there a standard/accepted implementation of fixed-point decimals (in the standard or boost or whatever) or is that a roll-your-own/varies-between-compilers sort of thing?
Do you mean arbitrary-precision? I was looking that up before and found that neither in the standard library nor in boost will you find anything, and it looks like it's a good place to get into a nerd bitchfight if you start getting into implementation details.

Actually in the case of using integer types to represent floating point values I don't think there's anything for that either in Boost or the standard library.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


I guess I meant arbitrary precision numbers, yeah. Terminology frequently escapes me. I mean whichever one translates to "I want X digits on the left and Y digits to the right of the radix, perfectly accurate. Go." :v:

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
Here are two libraries to try

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I'm starting to play with plugins in conjunction with dynamically casting because I am a masochist. I have something in Java that applies various kinds of mathematical functions to some time-series data. Each one of these functions in my Java source comes with some description of what kind of inputs and outputs it generates. It lists the actual data types as well as gives some description for the GUI. So now I'm trying to port that to c++.

Say the Java version goes something like this (paraphrasing this off the top of my head so I may be blowing some syntax):

code:
class Sum implements Plugin {
   String[] in_descriptions() { return String[] { "Parameter X", "Parameter Y" };
   String[] out_descriptions() { return String[] { "X + Y" };
   DataTypes[] in_types() { return DataTypes[] { FLOAT32, FLOAT32 };
   DataTypes[] out_types() { return DataTypes[] { FLOAT32 };
   Object[] go(Object[] inputs, int start, int stop) {
      float[] x = (float[]) inputs[0];
      float[] y = (float[]) inputs[1];
      
      float[] sum = new float[x.length];

      // Sum them up from start to stop
      Object[] out = new Object[1];
      out[0] = sum;

      return out
   }
}
That's basically the idea, though I'm doing something more elaborate with the data types that I'm not sure I really want to do in the original code. I was originally intending to just toss around void* in place of the Object arrays but I wonder if there's a more mature mechanism--say, something in Boost--to bind this all up more elegantly. Consider that another implementation of the same interface may have a completely different parameter bindings. Some stuff might not be an array.

In the end I will probably migrate out all the calls for data types and descriptions to an XML file because I find it cumbersome to describe everything in actual code, and rather leave source files for doing the actual work. I also like the idea of being able to loads the code in as a plugin that I can keep at arms reach, so in case it tries to segfault it hopefully doesn't knock out my main program. I spend a lot of my time in coding these up, and it gets cumbersome to get everything back up again after finding I want to adjust the code. I know Boost has some stuff for doing that, which I'm intending to follow.

Anyways I'm spitting this all out because I know a bad design decision here will be a huge pain in the rear end later when I have more than just a few handful of plugins to refactor, so I wanted to ask for any suggestions on the smoothest way of implementing this.

Rocko Bonaparte fucked around with this message at 19:08 on Aug 8, 2010

functional
Feb 12, 2008

I'm using recv in a select loop. If I know the client is using send to send at minimum n bytes all at once (for the cases where n is 8, 16, and 64) as the first thing after making the connection, what assumptions can I make about my first call to recv once select has marked that socket ready for reading? Specifically, may I assume the buffer has at least 8 (16, 64) bytes available for reading? The reason I am doing this is I would like to avoid using peek type operations and managing unnecessary connection info. I am concerned with compatibility only for *NIX/Windows.

Edit: This is all TCP

functional fucked around with this message at 05:01 on Aug 11, 2010

litghost
May 26, 2004
Builder

functional posted:

I'm using recv in a select loop. If I know the client is using send to send at minimum n bytes all at once (for the cases where n is 8, 16, and 64), what assumptions can I make about my first call to recv once select has marked that socket ready for reading? Specifically, may I assume the buffer has at least 8 (16, 64) bytes available for reading? The reason I am doing this is I would like to avoid using peek type operations and managing unnecessary connection info. I am concerned with compatibility only for *NIX/Windows.

Depends on many things, but mostly whether its UDP or TCP. UDP is defined at the recv level to be a datagram, ie they send 5 bytes, you get 5 bytes. TCP is a stream, so when they send 5 bytes, it may sit in a buffer and wait for more data, or might be broken into smaller packets. As soon as any in-order data arrives, your select will say data is ready.

In terms of how big your buffer is, recv takes the buffer size, so you don't need to worry about overflow.

:Edit:

Of course all this is made clear in the documentation for recv:

"recv" posted:

The recv() function shall return the length of the message written to the buffer pointed to by the buffer argument. For message-based sockets, such as SOCK_DGRAM and SOCK_SEQPACKET, the entire message shall be read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument, the excess bytes shall be discarded. For stream-based sockets, such as SOCK_STREAM, message boundaries shall be ignored. In this case, data shall be returned to the user as soon as it becomes available, and no data shall be discarded.

litghost fucked around with this message at 04:07 on Aug 11, 2010

functional
Feb 12, 2008

I've edited the question to indicate the connection is TCP.

Specifically, I'm asking whether there is a potentially unspecified property of recv for the indicated platforms where once the descriptor is marked as ready to read that the corresponding buffer contains some minimum number of bytes given our assumptions. My intuition tells me this is a reasonable question to ask since the available payload space on a TCP packet is much larger than 8, 16, or 64 bytes.

pseudorandom name
May 6, 2007

The minimum number of bytes is 1.

kes
Jan 4, 2006

functional posted:

I've edited the question to indicate the connection is TCP.

Specifically, I'm asking whether there is a potentially unspecified property of recv for the indicated platforms where once the descriptor is marked as ready to read that the corresponding buffer contains some minimum number of bytes given our assumptions. My intuition tells me this is a reasonable question to ask since the available payload space on a TCP packet is much larger than 8, 16, or 64 bytes.

nope, welcome to the enormous pain in the rear end that is the berkeley sockets design

you must loop and potentially reallocate until the socket has no data remaining. in almost all cases you will get data in the chunks you expect but it's not technically correct unless you account for that possible case of 1 byte

kes fucked around with this message at 04:58 on Aug 11, 2010

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

pseudorandom name posted:

The minimum number of bytes is 1.

I thought the urgent flag could result in a select indicating data available while there are zero bytes available for a normal read.

pseudorandom name
May 6, 2007

ShoulderDaemon posted:

I thought the urgent flag could result in a select indicating data available while there are zero bytes available for a normal read.

That may be possible, but I have no idea how urgent/OOB works and I doubt anybody sensible would be using it in new code.

edit: Also, Linux has a SO_RCVLOWAT, but that only influences select/poll/epoll/etc. since 2.6.28 or so, before that it'll just make read/recv/etc. block until the low water mark is not met (and select/etc. will return readable for any amount of data).

I think Solaris also has a working SO_RCVLOWAT, but everybody else (including Windows) just ignore that socket option.

pseudorandom name fucked around with this message at 05:01 on Aug 11, 2010

kes
Jan 4, 2006

pseudorandom name posted:

That may be possible, but I have no idea how urgent/OOB works and I doubt anybody sensible would be using it in new code.

remember winnuke? that was caused by the urgent pointer. that should tell you how reliable that poo poo is

pseudorandom name
May 6, 2007

That just tells me how reliable network-facing Microsoft products from the late '90s are.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


Going back to a case-insensitive string comparison question I had earlier in the thread.

Right now we do comparisons based on the example presented here, inheriting from char_traits<char> and overriding the comparison functions, then typedeffing ci_string as std::basic_string<char, ci_char_traits> or whatever you want to call them.

It WORKS, but (as I believe someone here said) it would be a shitload faster in our case to just have strings lowercased automatically as they're stored in this ci_string, rather than lowercasing them every compare. Is there any way to do this within the method presented, or will I have to do something else (such as inherit from std::string and change storage behavior... somehow)?

Ciaphas fucked around with this message at 18:43 on Aug 11, 2010

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Don't inherit from std::string. It doesn't have a virtual destructor and you can't safely use a lowercase_string as a string (e.g. static_cast<std::string&>(str) += "A" would break the invariant that all letters in the lowercase_string are lowercase).

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


I knew the first part of that--and since I wouldn't be storing any extra data members, that would be okay--but didn't consider the second. And overriding both char_traits::assign functions didn't work either. drat it.

I guess I could just go through all the code and make damned sure that any time a string is set it is being lowercased first, but I would very much rather pin it down in one place so no one else has the chance to goof it all up. :smith:

Ciaphas fucked around with this message at 20:31 on Aug 11, 2010

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
The simplest answer is to just lowercase the strings right after you read them in or write a function that does both steps. If you need the type safety or there are places where these strings could accidentally get an uppercase letter in them, write a class that is implemented with a string and has only the functions that you use.
code:
namespace ledneh{
std::string lowercase(const std::string &s);

class ci_string{
  std::string str;
public:
  ci_string(const std::string &s) : str(lowercase(s)) {}

  std::string::const_iterator begin() const{
    return str.begin();
  }

  std::string::const_iterator end() const{
    return str.end();
  }

  ci_string &operator += (const ci_string &that){
    str += that.str;
    return *this;
  }

  const char *c_str() const{
    return str.c_str();
  }

  std::size_t hash_value() const{
    boost::hash<std::string> hasher;
    return hasher(str);
  }

  //...
};

ci_string operator + (ci_string l, const ci_string &r){
  l += r;
  return l;
}

std::size_t hash_value(const ci_string &s){
  return s.hash_value();
}
}
blah blah blah

Perhaps as a side effect for your other problem (and depending on how else you use these strings), you could not implement the mutator functions like +=, and then you could calculate the hash_value once, at construction. That would give you some efficiency and productivity gain.

Mustach fucked around with this message at 23:38 on Aug 11, 2010

CapnBry
Jul 15, 2002

I got this goin'
Grimey Drawer
Speaking of templates, let's talk non-type template parameters. I know this example doesn't make much sense in the "Why would you want to do that?" manner, but just assume you had a good reason to do it. I don't, but I am still curious why this won't link. 3 Files:
code:
//intbox.h
#ifndef __INTBOX_H__
#define __INTBOX_H__
template <const int A> class Halfer
{
public:
  const int half(void) const;
};
#endif /* __INTBOX_H__ */
code:
// intbox.cpp
#include "intbox.h"
template<const int A> const int Halfer<A>::half(void) const
{
  return A * 0.5f;
}
code:
// main.cpp
#include <stdio.h>
#include <stdlib.h>
#include "intbox.h"

int main(void)
{
  Halfer<5> h;
  printf("%d\n", h.half());
  return 0;
}
`g++ -o template template.cpp intbox.cpp` complains
main.cpp:(.text+0x11): undefined reference to `Halfer<5>::half() const'

If I move the implementation from the intbox.cpp to the header file it works fine. I assume there is something syntactically I am missing here but I've stared at this for an hour now and am approaching the stumped state.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


Mustach posted:

:words:

Damnit why do the simplest solutions always elude me? :argh:

I'm sure the final solution will be more complicated than this, but this is the best jumping-off point I've seen. Thanks a lot Mustach (and everyone else) :)

Mr.Radar
Nov 5, 2005

You guys aren't going to believe this, but that guy is our games teacher.

CapnBry posted:

If I move the implementation from the intbox.cpp to the header file it works fine. I assume there is something syntactically I am missing here but I've stared at this for an hour now and am approaching the stumped state.

The compiler needs to instantiate templates at the point where they are used, which means the definition of a template (or template member function, etc.) must be known at the point of use. Alternatively, you could instantiate the template member in another compilation unit and rely on it being linked implicitly, but nobody does this because it's overly restrictive. In your case, the compiler is assuming the latter because it can't do the former.

Mr.Radar fucked around with this message at 21:30 on Aug 11, 2010

CapnBry
Jul 15, 2002

I got this goin'
Grimey Drawer

Mr.Radar posted:

The compiler needs to instantiate templates at the point where they are used, which means the definition of a template (or template member function, etc.) must be known at the point of use.
Oh man you're a genius. This completely makes sense. Thank you, I can now stop wondering about this and scrap the original whole stupid experiment I was playing with.

Oakland Martini
Feb 14, 2008

D&D: HASBARA SQUAD
THE APARTHEID ACADEMIC


It's important that institutions never take a stance like "genocide is bad". Now get out there and crack some of my students' skulls.
I've been doing some C coding for work and I'm running into something really bizarre (or at least it appears bizarre, it's probably stupid). I have a function

code:
extern "C" uint diff_evo_gpu
(
	const uint strategy, // evolution strategy
	const uint dim, // dimension of energy function domain
	const uint pop_size, // size of population
	const uint gens, // max generations
	const float CR, // crossover factor
	const float F, // weight factor
	const float TOL, // convergence tolerance
	float* pop_h, // population (initialized however you want, usually random)	
	float* best, // best population member (energy function minimizer)
	float* fbest // cost of best member
)
in a file diff_evo_gpu.cu that I compile with nvcc (Nvidia's CUDA C compiler). I call the function using the following line from main() in test.c (compiled with gcc):

code:
status = diff_evo_gpu(strategy, dim, pop_size, gens, CR, F, TOL, pop, best, &fbest );
The const float arguments are getting hosed up somehow. I'm passing CR = 0.5, F = 0.7 and TOL = 0.00001. I print them out right before the call to diff_evo_gpu with the code

code:
printf("\nParameter readout: strategy = %u, dim = %u, pop_size = %u, CR = %f, F = %f, TOL = %f\n", strategy, dim, pop_size, CR, F, TOL);
and get

code:
Parameter readout: strategy = 3, dim = 2, pop_size = 4096, gens = 1000, CR = 0.500000, F = 0.700000, TOL = 0.000010
However, when I run the same printf on the first line inside of diff_evo_gpu, I get
code:
Parameter readout: strategy = 3, dim = 2, pop_size = 4096, gens = 1000, CR = 0.000000, F = 36893488147419103232.000000, TOL = -0.000000
I've tried a bunch of stuff, like setting CR = 0.5 and 0.5f (and the same for the other floats) through command line options, macros, etc. Nothing works. Any ideas what's going wrong? It's probably something stupid since I'm an economist, not a programmer, but it's vexing me terribly.

Mr.Radar
Nov 5, 2005

You guys aren't going to believe this, but that guy is our games teacher.
Which platform (CPU, bitness (32 or 64), and OS) are you using? It looks like gcc and nvcc are using a different calling convention for passing floating-point parameters to functions.

Adbot
ADBOT LOVES YOU

Oakland Martini
Feb 14, 2008

D&D: HASBARA SQUAD
THE APARTHEID ACADEMIC


It's important that institutions never take a stance like "genocide is bad". Now get out there and crack some of my students' skulls.

Mr.Radar posted:

Which platform (CPU, bitness (32 or 64), and OS) are you using? It looks like gcc and nvcc are using a different calling convention for passing floating-point parameters to functions.

AMD Athlon X2 4400+ (x64) running Ubuntu 10.04. I tried compiling test.c with nvcc and got the same error. This doesn't surprise me since nvcc just uses gcc to compile non-CUDA code.

Oakland Martini fucked around with this message at 22:01 on Aug 12, 2010

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply