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
Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

code:
guess = rand() % (high - low) + low; // guess based on new max value
Are you sure about this line?

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
high seems to be an exclusive upper bound, so I think that line is correct but its analogue in the other case is wrong. mixit, this bug would have been easily avoided if you'd followed the principle of avoiding duplicate code. This would have been sufficient:

code:
int min = 1;
int max = 100;
int guesses = 0;

while (1) {
  int guess = min + (rand() % (max - min));
  guesses++;

  int input;
  do {
    cout << "I guess " << guess << "; enter 1 for too high, 2 for too low, or 3 for exactly right." << endl;
    cin >> input;
  } while (input < 1 || input > 3);

  switch (input) {
  case 1: // too high
    max = guess;
    break;

  case 2: // too low
    min = guess + 1;
    break;

  case 3: // exactly right
    cout << "I guessed it in " << guesses << " tries." << endl;
    return 0;
  }

  if (min >= max) {
    cout << "Liar!" << endl;
    return 0;
  }
}

mixitwithblop
Feb 4, 2009

by elpintogrande
Thanks a bunch. Your code really helps. There's definitely an art to logic solving... its so easy to spin donuts in a parking lot and sort of get somewhere, despite just needing to cross the street.

agscala
Jul 12, 2008

code:
string line = "int main(void, null) {";
static const boost::regex re(".*\\w+\\s+(\\w*)\\(.*");
boost::match_results<string::const_iterator> results;
	
boost::regex_match(line, results, re, boost::match_default | boost::match_partial);

I'm writing a program that will take a line of code and check if it is a function declaration and pull out the function name. This is my first time using regexs and boost.

I've written this super simple regex-- it works on the websites that let me "test" regexs against sample code to make sure they work and they all say that this regex should return true when compared with the string. The regex returns false when I compile it and I'm about at my wits end with this.

It's pretty much the same as the sample code in the boost docs...

Any suggestions?

e: also I realize that the regex could be much better and there might be other ways to accomplish the same task, but all I want to do is be able to use a regex to grab the string "main" from the original string...


Going through an online o'reilly tutorial explained some things nicely for me

agscala fucked around with this message at 05:50 on Jun 3, 2009

Fecotourist
Nov 1, 2008
What's a graceful way to gate the availability of different constructors (in a class template) based on the values of template parameters. Specifically, in a vector-like class templated on the number of dimensions.

code:
template <int N> class A {
public:
    A(float c0) { _comp[0] = c0; }
    A(float c0, float c1) { _comp[0] = c0; _comp[1] = c1; }
    A(float c0, float c1, float c2) { _comp[0] = c0; _comp[1] = c1; _comp[2] = c2;}

    float operator[](int i) const { return _comp[i]; }

private:
    float _comp[N];
};
If N is 2, I'd like only the 2-argument constructor available, etc. N ranges up to 8 or so. At the very least, I want a compile failure if somebody uses the 3-arg constructor with an A<2>.
I tried using boost::enable_if to add a dummy argument to each constructor, but I got as far as discovering that the constructor then needs to be a template member function, and I can't find a detailed (enough for me) example of how to make that work. Alternatives to enable_if would also be eagerly accepted.
[Wouldn't it be great to have an #ifdef that worked during template instantiation?]
I have a cute solution inspired by boost::list_of, overloading operator,() on a nested A::ValueInserter class and testing the value count at compile time, but that syntax is a little too exotic for my users.
Any pretty idioms for this out there?

Vanadium
Jan 8, 2005

BOOST_STATIC_ASSERT(N == 1); etc. seems to work well enough :shobon:

Fecotourist
Nov 1, 2008
Yeah, that's perfect. I use B_S_A elsewhere, but it didn't occur to me that it would never trip in an unused member function.

Edit: my mental block was from having just tried enable_if to add dummy args to non-template constructors (of the template class). That fired off errors regardless of which ones were actually used. In retrospect it's obvious that BOOST_STATIC_ASSERT in the function body is softer/lazier/more-delayed than polluting a function signature with an argument of a substitution-failed nonsense type.


Fecotourist fucked around with this message at 02:58 on Jun 4, 2009

DoctorTristan
Mar 11, 2006

I would look up into your lifeless eyes and wave, like this. Can you and your associates arrange that for me, Mr. Morden?
A Monte Carlo algorithm I'm implementing involves a bunch of objects of class Container, these all contain a sequence of pointers to objects of class Segment. Two objects of class Container are considered equal if they point to the same Segment objects. All Containers are of equal length. The attachment hopefully illustrates what I'm going on about.

At one point in my algorithm I have a whole bunch (tens of thousands at least) of these Containers and I have to eliminate all the duplicates. I was considering doing this by implementing an operator<(...) for the class and inserting all the containers into a an set to remove duplicates, but I'm slightly worried about ownership problems.

Currently the containers are all kept in a deque and are created in such a way that the first container in the deque that points to a segment owns that segment (ownership is implemented with a bool vector - I've tried to show all this on the diagram). I *think* that inserting them into a set won't cause problems so long as the copy constructor creates a copy without ownership: insertion creates a non-owning copy inside the set, and the Segments will be destroyed when I purge the original deque from the back (the MC algorithm is such that the set will never outlast the deque).

Will this approach work? Computational time is also something of an issue here, so if anyone knows an alternative method that is/might be faster, please put me right.

Only registered members can see post attachments!

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Why would you make copies of the Segments instead of just inserting pointers to them in the set?

Also lol at vector<bool>.

DoctorTristan
Mar 11, 2006

I would look up into your lifeless eyes and wave, like this. Can you and your associates arrange that for me, Mr. Morden?

Avenging Dentist posted:

Why would you make copies of the Segments instead of just inserting pointers to them in the set?

Sorry, that wasn't clear. I'm not copying the Segments - I'm (thinking of) inserting the Containers into the set. I was unsure whether having a copy-constructor for Container that kept ownership with the original would prevent the ownership getting confused.

Maybe I should provide a bit more detail. At a particular point I have a whole bunch of pointers to Containers in a deque, these containers in turn point to a (bigger) bunch of Segments floating around on the heap. Multiple containers may point to the same Segment. The ownership is set up so that if I delete the Containers by from the back of the deque to the front then everything gets cleaned up properly.

What I'm trying to do is eliminate all duplicate Containers, apply a particular function exactly once to each Container, then clean up every Container and Segment and move onto the next iteration. I wanted to make sure that I've correctly understood how insertion into a set works - I thought it called the copy-constructor to create a copy of the object inside the set.

Edit: by `duplicate containers' I mean `two different containers that point to the same ordered sequence of Segments'.

Edit2: If you can follow all of this, you're doing a lot better than I did. This algorithm took two full papers to describe properly. The reason I'm being vague about some of the details is because the details loving hurt.

Avenging Dentist posted:

Also lol at vector<bool>.

...yeah. That bit was one of the first things I implemented, before I found out how hosed-up vector<bool> actually is. Changing it is on the to-do list. Coding this algorithm has been quite the learning curve.

DoctorTristan fucked around with this message at 20:09 on Jun 4, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

DoctorTristan posted:

Sorry, that wasn't clear. I'm not copying the Segments - I'm inserting the Containers into the set. I was unsure whether having a copy-constructor for Container that kept ownership with the original would prevent the ownership getting confused.

Ok, so $AvengingDentist->last() =~ s/Segment/Container/;

(Quiz: How would you know which of the original Containers the ones in your set referred to if the set only contained copies of them?)

DoctorTristan
Mar 11, 2006

I would look up into your lifeless eyes and wave, like this. Can you and your associates arrange that for me, Mr. Morden?

Avenging Dentist posted:

Ok, so $AvengingDentist->last() =~ s/Segment/Container/;

I am a stupid noob - please explain?

Avenging Dentist posted:

(Quiz: How would you know which of the original Containers the ones in your set referred to if the set only contained copies of them?)

Wouldn't know, wouldn't care. As long as the copy points to the same Segments as the original, it's identical so far as the algorithm is concerned.

What the algorithm wants to do is apply a particular function exactly once to each unique Container in the original collection. i.e. if there are two Container objects pointing to the same Segments, I want to apply the function to only one of them (and since the algorithm considers them identical it doesn't matter which). Once it's done this it has no further use for any of the Segments or Containers, so I then have to clean all those up.

Creating an appropriate operator<(...) for Container and inserting the Containers into a set to create a set of copies without duplicates seemed like the most convenient way to achieve that. Since I have a history of shafting myself with C++, I wanted to check that I hadn't misunderstood how a set works, or overlooked an easier or faster way, or done something that would gently caress up the ownership and prevent proper cleanup.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

DoctorTristan posted:

I am a stupid noob - please explain?

Given my last post, execute a regular expression to find the first instance of "Segments" and replace with "Containers".


DoctorTristan posted:

Wouldn't know, wouldn't care. As long as the copy points to the same Segments as the original, it's identical so far as the algorithm is concerned.

If you're deleting everything when you're done, what I said was irrelevant, but it's still a waste to make a copy of the container when you could store a pointer to it. Pointers are much easier to copy than large objects.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


Threw this into codepad just now
code:
#include <iostream>
using std::cout;
using std::endl;

union UPants
{
  int i32;
  short i16;
} pants;

int main()
{
  pants.i32 = 2000000000; // set some of the upper 16 bits
  pants.i16 = 200;
  cout << pants.i32 << endl;  

  return 0;
}
The output was some large number, which I guess means it didn't zero out the upper 16 bits of the union when I assigned to the lower 16. Can I expect this behavior to be consistent across compilers, or will some compilers zero out those bits?

POKEMAN SAM
Jul 8, 2004

Ledneh posted:

Threw this into codepad just now
code:
#include <iostream>
using std::cout;
using std::endl;

union UPants
{
  int i32;
  short i16;
} pants;

int main()
{
  pants.i32 = 2000000000; // set some of the upper 16 bits
  pants.i16 = 200;
  cout << pants.i32 << endl;  

  return 0;
}
The output was some large number, which I guess means it didn't zero out the upper 16 bits of the union when I assigned to the lower 16. Can I expect this behavior to be consistent across compilers, or will some compilers zero out those bits?

What would be the point of the union if it did zero out the upper bits?

Vanadium
Jan 8, 2005

Ugg boots posted:

What would be the point of the union if it did zero out the upper bits?

I am pretty sure accessing the upper bits after writing to the lower bits is undefined behaviour in this case anyway. :colbert:

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Ledneh posted:

The output was some large number, which I guess means it didn't zero out the upper 16 bits of the union when I assigned to the lower 16. Can I expect this behavior to be consistent across compilers, or will some compilers zero out those bits?

You can reasonably expect this behavior to be consistent on compilers on a single platform that respect a common ABI. You can not expect this behavior to be consistent across platforms, primarily because of integer endianness differences.

ctz
Feb 6, 2003

Ledneh posted:

Can I expect this behavior to be consistent across compilers, or will some compilers zero out those bits?
Your read of i32 after writing i16 is, strictly speaking, undefined. It could yield any value, trash unrelated storage or crash. Don't do that then.

The actual behaviour you'll see will be much more dependent on architecture than compiler.

DoctorTristan
Mar 11, 2006

I would look up into your lifeless eyes and wave, like this. Can you and your associates arrange that for me, Mr. Morden?

Avenging Dentist posted:

If you're deleting everything when you're done, what I said was irrelevant, but it's still a waste to make a copy of the container when you could store a pointer to it. Pointers are much easier to copy than large objects.

:doh: Of course. So instead of an overloaded operator<(...) in Container I just create a comparison class that takes two pointers to Container and the whole thing works with less overhead. Thanks.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


ctz posted:

Your read of i32 after writing i16 is, strictly speaking, undefined. It could yield any value, trash unrelated storage or crash. Don't do that then.

The actual behaviour you'll see will be much more dependent on architecture than compiler.

Works for me, thanks.

Kerris
Jul 12, 2006
Don't you fucking dare compliment a woman's voice on the forums, you fucking creepy stalker.

BoingBoing posted:

Here's a treasure-map showing the relationships of C++ and its many offshoots, proponents, clones and pretenders.


click pic for link to full image, be warned that image is 14 mb

That Turkey Story
Mar 30, 2003

Kerris posted:



click pic for link to full image, be warned that image is 14 mb

A girl made this.

Stephen Smith
Nov 8, 2004

«The Grimace Reaper»
edit: Got it using !cin.

Stephen Smith fucked around with this message at 18:25 on Jun 7, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Stephen Smith posted:

super double edit: How would I go about confirming that a variable inputted by the user is an integer? Said variable is declared as an int; I want to produce an error message when the user types in a character or something. I'm trying:

...

With no luck. Any help would be greatly appreciated.

It scares me a little that you would think isdigit would give you a useful answer. (At no point could an integer not be an integer, and isdigit doesn't even operate on integers*). Look at ios::good.

* Ok, technically it does but it's expecting a promoted char.

RussianManiac
Dec 27, 2005

by Ozmaugh

Stephen Smith posted:

super double edit: How would I go about confirming that a variable inputted by the user is an integer? Said variable is declared as an int; I want to produce an error message when the user types in a character or something. I'm trying:

...

With no luck. Any help would be greatly appreciated.

You can use atoi and it will return 0 if it fails to parse the c string, so you can tell that way.

Or you can make a function to check each character and see if it is in the ASCII range for numbers - http://www.asciitable.com/

code:
bool isDigit( std::string & s )
{
   for( int i = 0; i < s.size(); ++i )
   {
      if( s[i] < 48 || s[i] > 57 ) return false;
   }
   return true;
}

of course this only checks for integers, and doesn't do scientific notation or decimals.

RussianManiac fucked around with this message at 18:32 on Jun 7, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

RussianManiac posted:

code:
      if( s[i] < 48 || s[i] > 57 ) return false;

This is just a less portable version of isdigit from the C standard.

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

RussianManiac posted:

code:
      if( s[i] < 48 || s[i] > 57 ) return false;
pre:
kaesees@sturmgewehr:~$ whatis isdigit
isdigit (3)          - character classification routines
isdigit (3posix)     - test for a decimal digit
e: :argh:AvengingDentist:argh:

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum
I have a stupid question I can't seem to find the answer too. Why do people use "#pragma once"? Why not just use #ifndef #define #endif?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Sweeper posted:

I have a stupid question I can't seem to find the answer too. Why do people use "#pragma once"? Why not just use #ifndef #define #endif?

The former is one line versus the latter's three. Also you don't have to worry about picking a non-colliding symbol to #define.

Also also, mediocre compilers that support #pragma once may perform faster than the #ifdef guard since it will generally stop loading the file immediately when it sees that and knows the file has been included. It takes slightly more work to do the same with #ifdefs (but I'm reasonably sure GCC and MSVC do that too).

csammis
Aug 26, 2003

Mental Institution
Is #pragma once universally supported? My company's coding standard says to not use it because we compile on a whole mess of platforms and compilers, though it's entirely possible that that's out of date.

That Turkey Story
Mar 30, 2003

It's not standard, but it's supported on most compilers. I wouldn't use it, but that's just me.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
I seem to recall a Boost discussion where they mentioned using both at the same time to help compilation performance in the above case I mentioned.

RekrulL
Jun 2, 2005
!
This is kind of a noob question but I've been searching for an answer everywhere but haven't found one. I'm using <ctime> and was wondering what the maximum value the clock() function spits out before it resets. Is it safe assume that it is the maximum value for a long int? That is what the clock_t type that it returns basically is. I just don't want to run a script for a month to confirm this.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender
clock shouldn't wrap any earlier than its datatype implies, as POSIX does not provide a constant to specify some lower bound. Non-POSIX systems (everything) may behave differently, but they'll document that. Note that on a 32-bit POSIX machine, clock will wrap after about 72 minutes. On a 64-bit POSIX machine, you've got about 585 thousand years.

Edit: Also, clock_t is signed, and -1 may be either one clock before wrapping, or an error.

Edit: What I'm trying to say is, you really shouldn't depend on this kind of thing.

ShoulderDaemon fucked around with this message at 21:12 on Jun 8, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

RekrulL posted:

This is kind of a noob question but I've been searching for an answer everywhere but haven't found one. I'm using <ctime> and was wondering what the maximum value the clock() function spits out before it resets.

Undefined.

agscala
Jul 12, 2008

e: nvm

agscala fucked around with this message at 09:16 on Jun 10, 2009

Fecotourist
Nov 1, 2008
Hopefully another dumb one. I don't understand why

code:
#include <cstdio>

class Outer {
public:
    class Inner {
    public:
        template <bool md> void Apply(float x) {
            printf("%d %f\n", int(md), x);
        }
    };

    template <class Engine> void OnePass(Engine &eng) {
        eng.Apply<true>(0.23);    // line 13
        eng.Apply<false>(0.67);   // line 14
    }
};

int main(int argc, char **argv) {
    Outer o;
    Outer::Inner oi;
    o.OnePass(oi);
}
yields (with gcc 4.1.2)

code:
mft.cpp: In member function ‘void Outer::OnePass(Engine&) [with Engine = Outer::Inner]’:
mft.cpp:21:   instantiated from here
mft.cpp:13: error: invalid use of member (did you forget the ‘&’ ?)
mft.cpp:14: error: invalid use of member (did you forget the ‘&’ ?)

That Turkey Story
Mar 30, 2003

Fecotourist posted:

Hopefully another dumb one. I don't understand why

...

yields (with gcc 4.1.2)

code:
mft.cpp: In member function ‘void Outer::OnePass(Engine&) [with Engine = Outer::Inner]’:
mft.cpp:21:   instantiated from here
mft.cpp:13: error: invalid use of member (did you forget the ‘&’ ?)
mft.cpp:14: error: invalid use of member (did you forget the ‘&’ ?)

You have to inform the compiler that Apply will be a template when OnePass is instantiated.

code:
eng.template Apply<true>(0.23);
end.template Apply<false>(0.67);

Fecotourist
Nov 1, 2008

That Turkey Story posted:

You have to inform the compiler that Apply will be a template when OnePass is instantiated.

code:
eng.template Apply<true>(0.23);
end.template Apply<false>(0.67);

Holy crap, that's a strange syntax. Thanks!

Adbot
ADBOT LOVES YOU

Senator Wang
Nov 23, 2007
Pretty good, for a land lover
When using fscanf within a loop, it should go to the next section of the file right? like during the loop it wont just jump back to the top of the same file it has been pointing to?

so
code:
	while (i <= 9) {
	fscanf(fpIn,"%d%f%d", &id, &cmmhr, &age);
	while (n <= 6) {
	fscanf(fpIn, "%f%f%f", &achr, &mchr, &echr);
should land the next run for fscanf starting on line 7 of the file the program is looking at?
EDIT: Its totally not,

Senator Wang fucked around with this message at 10:02 on Jun 11, 2009

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