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
That Turkey Story
Mar 30, 2003

Avenging Dentist posted:

Well, I mean that, and the inverse: using a variadic template as a template parameters to take non-variadic template types as arguments. i.e.:

code:
template< template<typename ...> class T >
struct foo
{};

foo<std::map> something_cool;

I doubt it. That would imply that from the context of foo, T should be expected to be able to take any number of template arguments, which std::map cannot.

Adbot
ADBOT LOVES YOU

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
I was messing around today and I realized that you can make template unions. :3:

code:
#include <iostream>
using namespace std;

template<typename T,size_t n>
size_t array_len(const T (&)[n])
{
	return n;
}

template <typename T>
union byte_union
{
	T a;
	char b[sizeof(T)];
};

int main()
{
	byte_union<int> x;

	cout << array_len(x.b) << endl;

	return 0;
}

Scaevolus
Apr 16, 2007

Avenging Dentist posted:

I was messing around today and I realized that you can make template unions. :3:

C++: "I can't think of a use case right now, but maybe it will be helpful later. Put it in the standard."

Avenging Dentist
Oct 1, 2005

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

Scaevolus posted:

C++: "I can't think of a use case right now, but maybe it will be helpful later. Put it in the standard."

Use case: variants

Vanadium
Jan 8, 2005

Doing about anything with that union is an aliasing violation. :colbert:

Edit: Well, okay, only in one direction.

floWenoL
Oct 23, 2002

Vanadium posted:

Doing about anything with that union is an aliasing violation. :colbert:

Edit: Well, okay, only in one direction.

No it's not; the whole point of unions is to avoid strict-aliasing (not aliasing) violations. You probably mean it's undefined to write to a union member and to read from another one (mostly).

Whilst farting I
Apr 25, 2006

This function is supposed to take a null-terminated array of characters (c-string). It takes every character added, compares it to a boolean array size 255, and checks if the memory location where the character would be is true or not (ie, to see if the character is not already in the array - if it's false, that character has not been added yet. if it's true, it has).

However, even a simple sentence such as "The quick brown fox jumps over the lazy brown dog." will produce output like this (I added a cout statement in the if loop to see what exactly it was taking in).

T
h
e

q
u
i
c
k
b
r
o
w
n
f
x
j
m
p
s
v
t
l
a
z
y
d
g
.

E
2
"


#
$
(
`
!
ð

How can I get rid of all that extra crap after the period? Shouldn't it stop taking characters after the period? The syntax to get that is just test.insert("The quick brown fox jumps over the lazy dog.");

code:
void insert(const char arr[]) {
                        unsigned char charToInsert;
                        int charLoc = 0;

                        // Goes through loop 255 times
                        for (int i = 0; i < NUM_OF_UNIQUE_CHARS; i++) {

                                 // Sets charToInsert to whatever the current character is
                                charToInsert = arr[i];

                                        // If this new character isn't already marked as having
                                        // been accounted for, make it so that it's marked as true
                                        if (isMember(charToInsert) == false) {

                                                // Converts the character itself to the character's integer
                                                // location from 0-255
                                                charLoc = indexFromChar(charToInsert);
                                                inSet[charLoc] = true;
                                        }
                        }

        }

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender
Short answer: you are looping 255 times, instead of once per character in the string. Consider what would happen if you had a string with 255 'a's followed by every other letter, or if you had a string (as is the case here) with less than 255 characters.

Furthermore, your indentation is mildly headache-inducing, the function calls you're making look like you're inappropriately abstracting in the wrong places, that's obviously not the code you ran to test with because that doesn't have any IO statements in it, and you're doing C string handling with C++. None of these are major problems, but you may want to ask your TA for a "perfect" solution after you hand in this assignment so you can see how they would structure the problem.

Edit: My solution:

code:
void print_unique_chars ( const char *str ) {

  // Initialize an empty set of characters found so far.
  bool found_set[256];
  for ( int i = 0; i < 256; ++i ) found_set[i] = false;

  // Loop through the passed string.
  while ( *str ) {

    // Only consider characters not in the found set so far.
    if ( ! found_set[*str] ) {

      // Add to found set.
      found_set[*str] = true;

      // Print the character.
      fputc( stdout, *str );

    };

    // Advance to next character in the passed string.
    ++str;

  };

}

ShoulderDaemon fucked around with this message at 02:33 on Aug 31, 2008

Whilst farting I
Apr 25, 2006

ShoulderDaemon posted:

Short answer: you are looping 255 times, instead of once per character in the string. Consider what would happen if you had a string with 255 'a's followed by every other letter, or if you had a string (as is the case here) with less than 255 characters.

You're right, I just didn't know how to get the length of a dynamically allocated character array - everywhere I searched online said there was no way to do this if you don't know what it'll be at compile time.

quote:

Furthermore, your indentation is mildly headache-inducing,

Whoa, it looked okay on my screen before I posted it :smith:

quote:

that's obviously not the code you ran to test with because that doesn't have any IO statements in it,

This is part of a class, I mentioned the function call was test.insert("The quick brown fox jumps over the lazy dog."); and that I stuck a cout statement in the if loop to see what exactly it was taking from the input sentence.

I can't change the function parameters, it has to remain a character array. But otherwise, you really have helped me out a bunch. I'm very rusty on C++, so thank you for being patient with my retarded-looking code and vague questions.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Whilst farting I posted:

You're right, I just didn't know how to get the length of a dynamically allocated character array - everywhere I searched online said there was no way to do this if you don't know what it'll be at compile time.

Yep, can't be done. You just loop until you hit a nul character. I use the pointer type so that I can use while ( *str ) { ... ++str }, but if you want an explicit index you'd use something like for ( int i = 0; str[i]; ++i ) { ... }. If you want to find the length of a C-string at runtime, you use strlen(3). Note that all these methods only work under the assumption that this is a well-formed C-string; if you're passed something that doesn't have a terminating nul, the program will crash or have some more subtle bug.

Whilst farting I posted:

Whoa, it looked okay on my screen before I posted it :smith:

The only really terrible bit was the extra layer of indentation after charToInsert = arr[i].

Whilst farting I posted:

This is part of a class, I mentioned the function call was test.insert("The quick brown fox jumps over the lazy dog."); and that I stuck a cout statement in the if loop to see what exactly it was taking from the input sentence.

It's usually considered bad form to post code that isn't exactly the code you're testing, because if you're doing something stupid while inserting the missing debugging code, then no-one will be able to recreate the error you see, and everyone just gets irritated at eachother. In your case, it wasn't a big deal because your problem was elsewhere, but you should get in the habit of not making people guess what you're doing.

Whilst farting I posted:

I can't change the function parameters, it has to remain a character array. But otherwise, you really have helped me out a bunch. I'm very rusty on C++, so thank you for being patient with my retarded-looking code and vague questions.

My function would work with the same parameters yours works with, for what that's worth. Arrays are passed in C and C++ as the address of the first element, so you can treat them as pointers to a single element and explicitly manage the pointer arithmetic. As you're still learning, you shouldn't do this unless you're already comfortable with pointer arithmetic, but at some point during your class there should be a discussion about passing semantics and the array/pointer pseudo-equivalence.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Whilst farting I posted:

Whoa, it looked okay on my screen before I posted it :smith:

You have your tab size set to something small, so every time you hit tab it looks like it indents 2 or 4 or whatever characters. But it actually just put one tab character in, so when it got posted to the board with a tab size of 8 the indentation was huge.

Adhemar
Jan 21, 2004

Kellner, da ist ein scheussliches Biest in meiner Suppe.
Also, instead of

code:
if (isMember(charToInsert) == false)
just write

code:
if (!isMember(charToInsert))

Whilst farting I
Apr 25, 2006

ShoulderDaemon posted:

Yep, can't be done. You just loop until you hit a nul character. I use the pointer type so that I can use while ( *str ) { ... ++str }, but if you want an explicit index you'd use something like for ( int i = 0; str[i]; ++i ) { ... }. If you want to find the length of a C-string at runtime, you use strlen(3). Note that all these methods only work under the assumption that this is a well-formed C-string; if you're passed something that doesn't have a terminating nul, the program will crash or have some more subtle bug.

Thanks for this - it's hard to find really specific information of this nature. Also, I feel like a dope for completely forgetting you could just do something like using arr[i] as a conditional :doh:

quote:

It's usually considered bad form to post code that isn't exactly the code you're testing, because if you're doing something stupid while inserting the missing debugging code, then no-one will be able to recreate the error you see, and everyone just gets irritated at eachother. In your case, it wasn't a big deal because your problem was elsewhere, but you should get in the habit of not making people guess what you're doing.

I had isolated my problem to that function but in the future if I'm having issues I'll post the full code. :nyoron:

quote:

My function would work with the same parameters yours works with, for what that's worth. Arrays are passed in C and C++ as the address of the first element, so you can treat them as pointers to a single element and explicitly manage the pointer arithmetic. As you're still learning, you shouldn't do this unless you're already comfortable with pointer arithmetic, but at some point during your class there should be a discussion about passing semantics and the array/pointer pseudo-equivalence.

I'm used to Java, believe it or not I've taken several courses that involve heavy C++ but pointers are always the things that screw me up, no matter how much reading I do or how many examples I see. This post has really been informative though, so thanks for all your help and patience!

Adhemar posted:

Also, instead of

code:
if (isMember(charToInsert) == false)
just write

code:
if (!isMember(charToInsert))

I wound up tightening my code to this later - I was more concerned with functionality over style when I posted it (obviously). Thanks for the tip!

That Turkey Story
Mar 30, 2003

tyrelhill
Jul 30, 2006

Adhemar posted:

Also, instead of

code:
if (isMember(charToInsert) == false)
just write

code:
if (!isMember(charToInsert))

Does it actually compile differently or?

TSDK
Nov 24, 2003

I got a wooden uploading this one

tyrelhill posted:

Does it actually compile differently or?
Ignoring possible overloads, then it should compile to identical code.

I've worked with people who prefer the '== false' on negative conditions, but omit the '== true' for positive conditions, on the grounds that it's harder to misread compared to the possibility of not spotting a small '!' tacked on to the front.

POKEMAN SAM
Jul 8, 2004

TSDK posted:

Ignoring possible overloads, then it should compile to identical code.

I've worked with people who prefer the '== false' on negative conditions, but omit the '== true' for positive conditions, on the grounds that it's harder to misread compared to the possibility of not spotting a small '!' tacked on to the front.

I'm in this boat. Unless it's obvious that you're going to be checking that something is false, I use == false.

tyrelhill
Jul 30, 2006

Ugg boots posted:

I'm in this boat. Unless it's obvious that you're going to be checking that something is false, I use == false.

Yeah me too, I was worried that maybe it was less efficient.

The Red Baron
Jan 10, 2005

So why is it that Boost doesn't have a proper, standalone singleton library yet? I don't want to have to rip off another Alexandrescu design and roll my own again, darnit <:mad:>

That Turkey Story
Mar 30, 2003

There are talks of a singleton library every once in a while and I think one or two went up for review without success. If you search through the mailing list archives you could probably see what the problems were and you might even find an implementation you can use even though it did not make it through review.

Edit:

There were two that went up for review

Jason Hise's in May 2005

Tobias Schwinger's in January 2008

I'd imagine that Tobias will resubmit his library after he makes it more generic, but I haven't heard anything about it recently.

Edit2: Haha look at this guy http://john.torjo.com/ (the review manager for the second singleton lib)

Edit3: This guy rules http://torjo.blogspot.com/

That Turkey Story fucked around with this message at 04:21 on Sep 8, 2008

Avenging Dentist
Oct 1, 2005

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

The Red Baron posted:

So why is it that Boost doesn't have a proper, standalone singleton library yet? I don't want to have to rip off another Alexandrescu design and roll my own again, darnit <:mad:>

Probably because singletons are next to trivial to implement?

The Red Baron
Jan 10, 2005

That Turkey Story posted:

There are talks of a singleton library every once in a while and I think one or two went up for review without success. If you search through the mailing list archives you could probably see what the problems were and you might even find an implementation you can use even though it did not make it through review.

Edit:

There were two that went up for review

Jason Hise's in May 2005

Tobias Schwinger's in January 2008

I'd imagine that Tobias will resubmit his library after he makes it more generic, but I haven't heard anything about it recently.

Edit2: Haha look at this guy http://john.torjo.com/ (the review manager for the second singleton lib)

Edit3: This guy rules http://torjo.blogspot.com/

Thanks! I'll have a look at those

quote:

Probably because singletons are next to trivial to implement?

Indeed, but as there are several gotchas with trivial implementations such as static vars (synchronization, lifetime and dependecy issues etc), I'd say there is definitely room for a generic, peer-reviewed library for the purpose

ShinAli
May 2, 2003

The Kid better watch his step.
Not a C question really but I wanna know how to set up vim to be a pretty good IDE for C programming.

I saw a website out there describing out to set up vim for python, and had all these neat things like a debugger, code completion, COLOR, and so forth. I'm starting to like vim (even though I don't have a handle on all the commands and stuff yet), and since I'm going to be using vim for the entire semester, I'd like to configure it a bit for C.

You guys got anything?

FearIt
Mar 11, 2007
I've been using system("start blah.exe") to open external programs, but doing so seems to stall my program until the program called is terminated..

How can I start another program without giving it control?

I'd rather avoid .net if possible.

EDIT: I figured it out, winExec is what I was looking for.

FearIt fucked around with this message at 07:56 on Sep 9, 2008

Avenging Dentist
Oct 1, 2005

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

covener
Jan 10, 2004

You know, for kids!

ShinAli posted:

Not a C question really but I wanna know how to set up vim to be a pretty good IDE for C programming.

I saw a website out there describing out to set up vim for python, and had all these neat things like a debugger, code completion, COLOR, and so forth. I'm starting to like vim (even though I don't have a handle on all the commands and stuff yet), and since I'm going to be using vim for the entire semester, I'd like to configure it a bit for C.

You guys got anything?

cscope integration is neat ":help cs"

Neslepaks
Sep 3, 2003

ShinAli posted:

Not a C question really but I wanna know how to set up vim to be a pretty good IDE for C programming.

I saw a website out there describing out to set up vim for python, and had all these neat things like a debugger, code completion, COLOR, and so forth. I'm starting to like vim (even though I don't have a handle on all the commands and stuff yet), and since I'm going to be using vim for the entire semester, I'd like to configure it a bit for C.

You guys got anything?

These are my C specific settings:

autocmd BufRead,BufNewFile *.c,*.h,*.cc,*.cxx,*.hxx set cindent formatoptions=corq cinoptions=:0(0 textwidth=72 sm comments=sr:/*,rmb:*,exr:*/

That does auto-indentation with lining up the way I like it, paren/brace/bracket-matching, automatic comment formatting and wrapping (ie, you write /*<enter>, it fills in " * " for you, etc). Colors is just :syntax on.

I don't use make integration and that stuff much, but see :help make.

slovach
Oct 6, 2005
Lennie Fuckin' Briscoe

FearIt posted:

I've been using system("start blah.exe") to open external programs, but doing so seems to stall my program until the program called is terminated..

How can I start another program without giving it control?

I'd rather avoid .net if possible.

EDIT: I figured it out, winExec is what I was looking for.

Maybe CreateProcess would be worth a look as well

Lexical Unit
Sep 16, 2003

I'd like to have an asynchronous deadline timer. There's very little I need:

1. I'd like to be able to say: "run this function in x seconds, and don't block while you wait."

2. Assuming I've done #1 above, but x seconds haven't passed, I'd like to be able to say: "ok, nevermind. Stop waiting and don't run that function."

I'd love to use Boost.Asio, but I can't. I may have mentioned not being able to use boost in the past, that's changed recently. Now I'm allowed to use boost 1.32.0 :woop: But of course Asio isn't available in that version :smith:

Does anyone know of any other C/C++ libraries that could do this. I tried using libevent but it didn't really suit my needs. libevent assumes some kind of "main loop" that their event_dispatch() will be called from, but I can't be tied down to that paradigm.

My boss implemented a solution to provide this sort of functionality some years ago, but it's nasty the time has come where we really need to redesign it from the ground up. So I'd like to know if there's already a well made wheel out there (besides Asio) before I try and roll my own.

more falafel please
Feb 26, 2005

forums poster

Lexical Unit posted:

I'd like to have an asynchronous deadline timer. There's very little I need:

1. I'd like to be able to say: "run this function in x seconds, and don't block while you wait."

2. Assuming I've done #1 above, but x seconds haven't passed, I'd like to be able to say: "ok, nevermind. Stop waiting and don't run that function."

I'd love to use Boost.Asio, but I can't. I may have mentioned not being able to use boost in the past, that's changed recently. Now I'm allowed to use boost 1.32.0 :woop: But of course Asio isn't available in that version :smith:

Does anyone know of any other C/C++ libraries that could do this. I tried using libevent but it didn't really suit my needs. libevent assumes some kind of "main loop" that their event_dispatch() will be called from, but I can't be tied down to that paradigm.

My boss implemented a solution to provide this sort of functionality some years ago, but it's nasty the time has come where we really need to redesign it from the ground up. So I'd like to know if there's already a well made wheel out there (besides Asio) before I try and roll my own.

On Unix you can use alarm() or setitimer() and catch SIGALRM, but that not be flexible enough, since you can't set more than one timer.

Lexical Unit
Sep 16, 2003

Unix gets all the cool toys: kqueue, setitimer, ZFS... I guess I should have mentioned I'm on RedHat Linux. Thanks for the suggestion though. I'm not sure if either of those are on RHEL4AS3, but if alarm is, it might be good enough for my immediate needs. If so I could use it for now while I consider more flexible/robust options.

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.
alarm() is POSIX, so any recent RHEL should have it. Keep in mind that, like threads, signal handlers have their own set of limitations and caveats that you might want to brush up on, depending on what your function is doing.

more falafel please
Feb 26, 2005

forums poster

Mustach posted:

alarm() is POSIX, so any recent RHEL should have it. Keep in mind that, like threads, signal handlers have their own set of limitations and caveats that you might want to brush up on, depending on what your function is doing.

alarm(3) man page posted:

HISTORY
An alarm() function appeared in Version 7 AT&T UNIX.

pseudorandom name
May 6, 2007

timer_create()/timer_settime()/etc. are a whole lot more useful than alarm() or setitimer().

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.

more falafel please posted:

Then he can really count on it being there.

FearIt
Mar 11, 2007
Hi, I'm using the windows.h winapi and I'm trying to figure out how to find all of the hwnd's of windows with class "XYZ".

Anyone have a clue how I could do this?

Pooball
Sep 21, 2005
Warm and squishy.

FearIt posted:

Hi, I'm using the windows.h winapi and I'm trying to figure out how to find all of the hwnd's of windows with class "XYZ".

Anyone have a clue how I could do this?

FindWindowEx or EnumWindows

Pooball fucked around with this message at 02:55 on Sep 11, 2008

Rat Supremacy
Jul 15, 2007

The custom title is an image and/or line of text that appears below your name in the forums
Okay so I'm going to uni soon to do Computer Science & Cybernetics and in the 3 (or 4, hopefully) years I'm hoping to a whole multitude of things that I'm sure will be a mix of a lot of languages. I have a lot of ideas about AI, evolution simulation, robotic control, VR/stereoscopic games - interacting at all "levels" from hardware to high level software, that I just can't wait to start putting to the test, and for the core "logic" of most of these it seems like the most obvious option is C++ as a lot of it will be really pushing PCs so needs to be a low level language, and for this reason I *understand* that python would not be as effective, but supporting of objects and various stuff C apparently doesn't have (although I haven't ruled out other languages) also the VR stuff I intend to be doing as mods to games (eg Source/UT4 engine eye tracking based stereoscopic focus will be something that will hopefully be allowed by the bridge between hardware and software). I know this is not beyond me, but it *will* mean I most likely have to do a lot of independent learning outside of classes / lectures so I want to start learning C++ as soon as possible.

However, with most tutorial sites I learn how to make a simple "hello world" app and then look at another site which does it differently or uses a different standard library (which is confusing as hell). I'm not *so* concerned about visual things at the moment as I expect that I'd be building any interfaces or graphical representations in a simpler language (Visual Basic Gui arf).

What is the difference between Visual C++ and straight up C++? I can imagine I'll be working with various environments...Linux, Windows, embedded chips :O

Syntax is not an issue, as I've a lot of experience in PHP and dabbled VB, Basic, Pascal, C, ASM, Java etc, it is about learning how the language does things but I find it hard to sit and read through an ebook as my attention span plummets if I am not doing things and learning and understanding things as I learn interactively to a degree.

I will have a (small) budget for books after I get my Student Loan (I'd count this as a worthwhile expense for my learning).

Is there a reverse version of this? http://bisqwit.iki.fi/story/howto/php/

Where should I start? Are there any good goon recommended free tutorial sites I can busy myself with before I sink money into a good book?


Thanks! :)

Rat Supremacy fucked around with this message at 14:09 on Sep 11, 2008

Vanadium
Jan 8, 2005

haywire posted:

What is the difference between Visual C++ and straight up C++? I can imagine I'll be working with various environments...Linux, Windows, embedded chips :O

Visual C++ is Microsoft's C++ development environment for Windows. Its compiler uses the same language as other C++ compilers (though it provides a bunch of extensions), and people seem to like it. You will probably have to use separate compilers to compile for your embedded platforms but you should be able to actually write and edit code with Visual C++.

quote:

Where should I start? Are there any good goon recommended free tutorial sites I can busy myself with before I sink money into a good book?

I cannot make an official goon recommendation, but "Thinking in C++" is a book by Bruce Eckel that is readable for free on the web. It kind of assumes you are vaguely aware of how programming works and goes on to explain the C++ stuff. It is a bit OOP centered but probably a decent starting place.

Also, most people agree that C++ tutorials you find on the web tend to suck. :shobon:

Adbot
ADBOT LOVES YOU

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.

haywire posted:

What is the difference between Visual C++ and straight up C++? I can imagine I'll be working with various environments...Linux, Windows, embedded chips :O
C++ is the language and standard library. "Visual C++" is the name of Microsoft's C++ compiler and development environment. (Although a lot of the time they'll say "Visual C++" and mean C++/CLI. C++/CLI is their managed dialect of C++ that's for use with the .NET framework.)

I know you said you don't want to buy a book just yet, but once you do (and since you say you've got programming experience) you can't go wrong with The C++ Programming Language. The author invented the language, and aside from covering just about everything in standard C++, it's got plenty of exercises at the end of each chapter.

A "beginner-level" book that gets recommended a lot in this forum is "Accelerated C++", but I've never read it.

I'll second "Thinking in C++" as a decent web book. A good quick reference for the Standard Library is Apache's documentation.

Websites that come up frequently in searches but should be avoided are cplusplus.com and codeproject. Especially cplusplus.com; that site is a bane on the Internet. At least codeproject has some diamonds in its rough. cplusplus.com has nothing worthwhile. Anything decent that it offers is small fries compared to the abundance of misinformation, bad practices, and platform-specific code attributed as standard C++.

Mustach fucked around with this message at 14:52 on Sep 11, 2008

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