question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,298,166 | 3,317,468 | Change background of indexed QTabBar tabs using stylesheets | Using Qt stylesheets, is it possible to set a different background colour for each tab in a QTabBar that has 4 or more tabs?
My Qt application has 6 tabs underneath the menu bar. I'd like to change their background colours to 6 different colours using stylesheets.
2 issues appear to be standing in my way:
I can only style the "first", "middle", and "last" tabs using pure stylesheet syntax (hence why I say "4 or more" tabs).
I don't think the individual tabs are child widgets of the QTabBar that I can access. The idea being that I could then attach a property to each child tab that I could reference in the stylesheet.
For example:
// Stylesheet
QTabBar::tab[index="3"] {
background: blue;
}
// Code
QTabBar* bar = new QTabBar;
int index = bar->addTab("Tab 1");
QWidget* tab1; //= ????
tab1->setProperty("index", index);
Any help would be much appreciated. Thanks.
| The individual tabs are structs rather than objects. These structs are then used on painting. See the Qt source for more details.
I've had an experiment with this and I can't find a way to access a direct index, like you indicated. For your reference, I tried using properties such as the text, toolTip, whatsThis but couldn't access any of them from the stylesheets, unfortunately.
I'm afraid I don't think what you want to do is possible without subclassing and modifying the paint events yourself.
|
2,298,217 | 2,298,301 | JNI Application State | How is state kept when accessing methods through JNI? In the example below my Java code is calling the native method drawFromJni, will my native class _nc be persisted between calls?
If there were better native debugging tools for the NDK this would be pretty easy to find out, but I'm really having problems with the NDK and C++.
extern "C" {
JNIEXPORT void JNICALL Java_com_jnitest_SurfaceRenderer_drawFromJni(JNIEnv * env, jobject obj);
};
myNativeClass _nc;
JNIEXPORT void JNICALL Java_com_jnitest_SurfaceRenderer_drawFromJni(JNIEnv * env)
{
_nc.draw();
}
| The implementation of JNI functions follows the scoping rules for the language you're implementing in. If you declare _nc as a global variable (as you've done in your example), it will be shared throughout the entire application.
|
2,298,292 | 2,298,383 | Container relationships and encapsulation | In my game engine I have a State class that represents the game world at a point in time. This State contains a number of Body objects that define one rigid body each. Each State has a container to keep track of the Body objects it owns, and each Body has a pointer back to its parent State.
Outline of State class:
class State {
private:
std::set<Body*> _bodies;
public:
//It could be done here
void addBody(Body* body) {
//Remove from old State
if (body->_state)
body->_state->_bodies.erase(this);
//Set Body's back-reference
body->_state = this;
//Add to this State
_bodies.insert(body);
}
};
Outline of Body class:
class Body {
private:
State* _state;
public:
//It could also be done here
void setState(State* state) {
//Remove from old State
if (_state)
_state->_bodies.erase(this);
//Set back-reference
_state = state;
//Add to the new State
if (_state)
_state->bodies.insert(this);
}
};
The problem, if there is one, is that adding/removing a Body to/from a State requires changing a private member of each.
At one point I considered having a State-Body-mediator static class, which would have friend access to both classes. It sounds nice, because the State-Body relationship would be explicitly managed by that name, but it's a lot of declaration overhead for managing a simple relationship.
Is there a "better" way to do this? I'd like to see what kinds of ideas are out there.
| Well, one way you could do it would be to have a friend function of both classes:
void associate(State& s, Body& b)
{
s.addBody(&b);
b.setState(&s);
}
|
2,298,305 | 2,298,394 | OpenProcess / SetProcessAffinityMask on process started by my service | In my manager.exe, I'm trying to change the CPU usage of my worker.exe, which is started by my service.exe. Service.exe is running under the System Account, while manager.exe is running under the logged in user's account.
When I call OpenProcess in manager.exe with worker.exe's PID, I get NULL for procHandle:
HANDLE procHandle = OpenProcess(PROCESS_SET_INFORMATION, 0, pid);
Using GetLastError() I see that I got an Access Denied error.
Any ways around this? Can I somehow modify worker.exe to grant other processes full control over itself?
| You shouldn't have to call OpenProcess.
The service should already have a full-permission handle to the worker from when it called CreateProcessAsUser or CreateProcessWithLogonW. Use DuplicateHandle to make a version of that handle suitable for use by the manager process, and then have the service send that handle to the manager. The service already has a handle to the manager, right? It will need that for DuplicateHandle.
Or have the manager ask the service to change the worker process.
|
2,298,387 | 2,298,531 | #warning and macro evaluation | I have the following code :
#define LIMIT_DATE \"01-03-2010\"
#ifdef LIMIT_DATE
#if _MSC_VER
#pragma message ("Warning : this release will expire on " LIMIT_DATE)
#elif __GNUC__
#warning ("Warning : this release will expire on " LIMIT_DATE)
#endif
#endif
The problem is that LIMIT_DATE is not evaluated when printing the warning.
I searched on Google, but didn't found yet the solution.
Thanks for help.
| From gcc preprocessor documentation
Neither #error nor #warning
macro-expands its argument. Internal
whitespace sequences are each replaced
with a single space. The line must
consist of complete tokens. It is
wisest to make the argument of these
directives be a single string
constant; this avoids problems with
apostrophes and the like.
So it's not possible at least in gcc.
According to MSDN this should work for MSVC althrough I don't have access to Visual Studio currently to test this
|
2,298,604 | 2,299,253 | When should I concern myself with std::iostream::sentry? | Online references have rather brief and vague descriptions on the purpose of std::iostream::sentry. When should I concern myself with this little critter? If it's only intended to be used internally, why make it public?
| Most people will never write any code that needs to deal with creating sentry objects. A sentry object is needed when/if you extract data from (or insert it into) the stream buffer that underlies the stream object itself.
As long as your insertion/extraction operator uses other iostream members/operators to do its work, it does not have to deal with creating a sentry object (because those other iostream operators will create and destroy sentry objects as needed).
|
2,298,781 | 2,298,796 | Why do un-named C++ objects destruct before the scope block ends? | The following code prints one,two,three. Is that desired and true for all C++ compilers?
class Foo
{
const char* m_name;
public:
Foo(const char* name) : m_name(name) {}
~Foo() { printf("%s\n", m_name); }
};
void main()
{
Foo foo("three");
Foo("one"); // un-named object
printf("two\n");
}
| A temporary variable lives until the end of the full expression it was created in. Yours ends at the semicolon.
This is in 12.2/3:
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.
Your behavior is guaranteed.
There are two conditions that, if met, will extend the lifetime of a temporary. The first is when it's an initializer for an object. The second is when a reference binds to a temporary.
|
2,299,028 | 2,299,053 | C++ pthreads - using code I used in C gives me a conversion error | I am running the same exact code that I ran in plain C:
pthread_create(&threads[i], &attr, SomeMethod, ptrChar);
And I get the errors:
error: invalid conversion from
'void*(*)(char'*)' to 'void*(*)(void*)'
error: initializing argument 3 of 'int
pthread_create(__pthread_t**,
__pthread_attr_t* conts*, void*(*)(void*), void*)'
SomeMethod is:
void *SomeMethod(char *direction)
Do I need to do something different in C++? I thought you could just run any C code in C++ and it would work fine?
I am using Cygwin at the moment.
| Like it says, they are two different function signatures. You should do:
void *SomeMethod(void* direction) // note, void
{
char* dir = static_cast<char*>(direction); // and get the value
}
C was casting from one function pointer to the other, apparently. Casting one function pointer to another is undefined behavior in C++.
That said, I'm pretty sure POSIX requires that casts between function pointers be well-defined, so you may be able to do this instead:
pthread_create(&threads[i], &attr, // cast the function pointer
reinterpret_cast<void* (*)(void*)>(SomeMethod), ptrChar);
|
2,299,106 | 2,299,158 | How do I determine the number of places following a decimal in a floating point value? | In C++ you can use std::numeric_limits<FloatingPointType>::digits10 to find out exactly how many places of precision you can get before the decimal place. How do I find out how many decimal places I can get following it, if I know the number will always be fixed-point between 0 and 1 inclusive?
Edit: The reason I ask is that I have an external RNG generating doubles and piping them through to a second program using standard input and output, so if the randomly generated numbers aren't output correctly to standard output, the second program can't grab their full values through standard input because they get truncated by the output of the first program, then rounded to representable values by the second program. I'd like to pipe the values between programs fully intact.
Thanks
| std::numeric_limits<FloatingPointType>::digits10 is the total number of decimal digits the type can exactly represent. If you write a number as 1234.56 or 1.23456 ⋅ 103 or 123456 ⋅ 10-2 doesn't matter for the number of exact digits, so there is no distinction between before and after the decimal place.
|
2,299,109 | 2,299,492 | How to handle linker errors in C++/GNU toolchain? | Given a C++/GNU toolchain, what's a good method or tool or strategy to puzzle out linker errors?
| With gcc toolchain, I use:
nm: to find the symbols in object files
ld: to find how a library links
c++filt: to find the C++ name of a symbol from its mangled name
Check this for details.
|
2,299,360 | 2,302,553 | Comparison of performance between Scala etc. and C/C++/Fortran? | I wonder if there is any reliable comparison of performance between "modern" multithreading-specialized languages like e.g. scala and "classic" "lower-level" languages like C, C++, Fortran using parallel libs like MPI, Posix or even Open-MP.
Any links and suggestions welcome.
| Given that Java, and, therefore, Scala, can call external libraries, and given that those highly specialized external libraries will do most of the work, then the performance is the same as long as the same libraries are used.
Other than that, any such comparison is essentially meaningless. Scala code runs on a virtual machine which has run-time optimization. That optimization can push long-running programs towards greater performance than programs compiled with those other languages -- or not. It depends on the specific program written in each language.
|
2,299,397 | 2,299,500 | How to get the currently focused menu item ID? | I want to display info when my mouse cursor is on an item in my menu by using SendMessage() to my statusbar. How do i get the current menu item ID ? I suppose they use same ID's as my Visual Studio shows in the menu editor.
I found these on msdn but none of them seems to serve my needs:
WM_COMMAND
WM_CONTEXTMENU
WM_ENTERMENULOOP
WM_EXITMENULOOP
WM_GETTITLEBARINFOEX
WM_MENUCOMMAND
WM_MENUDRAG
WM_MENUGETOBJECT
WM_MENURBUTTONUP
WM_NEXTMENU
WM_UNINITMENUPOPUP
| While the user is moving around the menu you get WM_MENUSELECT messages. LOWORD(lParam) will be the id of the menu item unless what is currently being selected is a popup rather than an item.
so your code looks something like this
case WM_MENUSELECT
{
HMENU hmenu = (HMENU) lParam;
UINT idItem = (UINT) LOWORD(wParam);
UINT flags = (UINT) HIWORD(wParam);
if (flags & MF_POPUP)
{
// idItem is actually a popup index
HMENU hSubMenu = GetSubMenu(hmenu, idItem);
idItem = 0; // assign an id to the menu, or just set to 0 for no output
}
// show menu info on status bar for idItem
SendMessage(hwndStatbar, ..., idItem, ...);
}
|
2,299,460 | 2,299,542 | For a given number N i have to find all the prime numbers it's consisting of | Need a suggestion for an algorithm.
For a given number N i have to find all the prime numbers it's consisting of, like this:
N = 49
49 = 7 ^ 2
N = 168
168 = (2 ^ 3) * (3 ^ 1) * (7 ^ 1)
If you want to help me even more you can write the algo in c++.
Thanks.
| The most straightforward way is trial division. Basically just try dividing n by each prime number up to sqrt(n). For large numbers, this is a very slow algorithm.
http://en.wikipedia.org/wiki/Trial_division
For more sophisticated algorithms, try http://en.wikipedia.org/wiki/Integer_factorization
|
2,299,523 | 2,299,591 | Why does function calls to templatized base classes not work? | Consider the following example:
template <typename T>
class A {
public:
void f() {
cout << "A::f()\n";
}
};
template<>
class A<int> {
};
template<typename T>
class B: public A<T> {
public:
void g() {
cout << "B::g()\n";
A<T>::f();
}
};
int main() {
B<int> b; // (1)
b.g(); // (2)
return 0;
}
Obviously the call to A::f() inside B::g() will fail for int template type. My question is at what point does the call fail? At (1) or (2)? I thought it should be (1) because at that point the compiler creates a new class with the template type int and compiles it. That compilation should fail in f() correct?
| It fails at 2). Member function of templates are instantiated when called.
More precisely: When a class template is instantiated, the declaration of its member functions are instantiated, but not their definition. The definition is instantiated when the function is used.
|
2,299,564 | 2,299,794 | Sending data between two ethernet interfaces on the same box | I would like to send data between two ethernet interfaces that are connected with a crossover cable in Linux. The two ethernet interfaces are on the same box. I defined the ethernet interfaces to have different static ip addresses (1.2.3.4 and 5.6.7.8) and have been using sockets to send bytes from one IP address to the other. I want to emphasize that I want the data to leave the box one interface of the box and get received on the other interface of the same box. One consequence of this is that unplugging the cable would prevent communication between the client and server on the same box.
The kernel is smarter than me I guess and decides it doesn't need to send information out on the wire and routes the data directly between the sockets internally, thus negating the test. I have tried to use SO_BINDTODEVICE to force the client to send data out of a particular interface, but the server never sees it. I am really stuck and this doesn't seem like it should be this difficult.
There are two entries in the route -n table
Dest Gateway Genmask flags metric use interface
1.2.3.0 0.0.0.0 255.255.255.0 U 0 0 eth0
5.6.7.0 0.0.0.0 255.255.255.0 U 0 0 eth1
| You can not communicate using IP between 1.2.3.4/24 to 5.6.7.8/24 without going though a router. The problem is that IP can only talk to other computers in the same network segment. To calulate the network address you need to do a logic AND between both the interface address and the subnet mask. This will give you the network addresses. If the two network addresses are different then a router will be required. In your example you will have network address 1.2.3.0 and 5.6.7.0. Because these are different it will will to send data.
More importantly most network stacks are smart enough to see that if both interfaces are on the same computer it will not send the data all the way to the phyical interface. It will probably only send the message though the IP stack. But again it would need to be vaild address for it to work.
You should even be able to test a similar setup using just loopback network devices. (virtual network cards.)
|
2,299,626 | 2,299,679 | Problem with sprintf function, last parameters are wrong when written | So I use sprintf
sprintf(buffer, "%f|%f|%f|%f|%f|%f|%d|%f|%d", x, y, z, u, v, w, nID, dDistance, nConfig);
But when I print the buffer I get the 2 last parameters wrong, they are lets suppose to be 35.0000 and 0 and in the string they are 0.00000 and 10332430 and my buffer is long enough and all the other parameters are good in the string
Any idea? Is there a length limit to sprintf or something?
I checked the types of all the numbers and they are right, but what seems to be the problem is the dDistance. When I remove it from the sprint, the nConfig gets the right value in the string, but when I remove nConfig, dDistance still doesn't get the right value. I checked and dDistance is a double. Any idea?
Since people don't seem to believe me I did this :
char test[255]={0};
int test1 = 2;
double test2=35.00;
int test3 = 0;
sprintf(test,"%d|%f|%d",test1,test2,test3);
and I get this in my string:
2|0.000000|1078034432
| I'd check to make sure your argument types match up with your format string elements. Trying to display a double as an integer type (%d) or vice versa can give you strange output.
|
2,299,824 | 2,299,847 | How do I use the C preprocessor to make a substitution with an environment variable | In the code below, I would like the value of THE_VERSION_STRING to be taken from the value of the environment variable MY_VERSION at compile time
namespace myPluginStrings {
const char* pluginVendor = "me";
const char* pluginRequires = THE_VERSION_STRING;
};
So that if I type:
export MY_VERSION="2010.4"
pluginRequires will be set at "2010.4", even if MY_VERSION is set to something else at run time.
UPDATE: (feb 21) Thanks for your help everyone. It works.
As I'm using Rake as a build system, each of my CFLAGS is a ruby variable. Also the values need to end up in quotes. Therefore the gcc command line for me needs to look like this:
gcc file.c -o file -D"PLUGIN_VERSION=\"6.5\""
Which means this is in my Rakefile:
"-D\"PLUGIN_VERSION=\\\"#{ENV['MY_VERSION']}\\\"\""
| If I recall correctly, you can use the command line parameter -D with gcc to #define a value at compile time.
i.e.:
$ gcc file.c -o file -D"THE_VERSION_STRING=${THE_VERSION_STRING}"
|
2,300,191 | 2,300,377 | Dynamic memory allocation question | when you allocate dynamic memory on the heap using a pointer,
char *buffer_heap = new char[15];
it would be represented in memory as:
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««þþþ
why doesn't there be a NULL terminating character at the end instead of ýýýý««««««««þþþ?
| Í is byte 0xCD, which the Windows debug allocator writes into your 15 bytes of memory to indicate that it is uninitialised heap memory. Uninitialized stack would be 0xCC. The idea is that if you ever read memory and unexpectedly get this value, you can think to yourself, "hmm, I've probably forgotten to initialise this". Also, if you read it as a pointer and dereference it, then Windows will crash your process, whereas if an uninitialised buffer were filled with random or arbitrary values then sometimes by fluke you'd get a valid pointer, and your code might cause all kinds of trouble. C++ doesn't say what values uninitialized memory holds, and non-debug allocators won't waste time filling memory with special values for every allocation, so you must never rely on that value being there.
This is followed by 4 bytes of ý (byte 0xFD), which the Windows debug allocator uses to indicate an out-of-bounds region at the end of a buffer. The idea is that if you ever find yourself in the debugger writing to a region that looks like this, you can think "hmm, I've probably overrun my buffer here". Also, if the value has changed when the buffer is freed, the memory allocator can warn you that your code is wrong.
« is byte 0xAB, and þ is 0xFE. Presumably these are also intended as eye-catchers (they aren't plausible pointers or offsets, so they don't form part of the heap structure). I don't know what they signify, possibly more guard data like the 0xFD.
Finally, I guess, you've found a 0 byte, the 16th byte beyond the end of your 15 byte buffer (i.e. the 31st byte counting from the start of it).
Asking the question as "C++" without mentioning that you're on Windows suggests that this is how C++ behaves. It isn't, it's how one implementation of C++ behaves, with particular compiler options and/or linked dlls. C++ does not permit you to read past the end of the buffer, Microsoft is just being nice to you and letting you get away with it not crashing or worse.
|
2,300,193 | 2,300,323 | How can I search for a specific computer over a closed network? | I have a network of 16 computers all linked to the same switch, not connected to the internet. One of the 16 computers has a small Java app running on it along with a BlazeDS server (aka it's listening on a port for a message).
Currently, the other 15 "client" computers have to manually enter the "server" IP where the java app resides. My client app is Adobe Air, so I have no abilities there as far as scanning for the server.
I was thinking of writing a helper app / utility in Java or C++. At the very least, this app could display the IP to the user who could then input it into the Air app; sloppy but better than nothing.
I'm sure there are some tools out there that deal with this type of problem. Any ideas?
| I would strongly recommend using Zeroconf/Bonjour for this as it makes it trivially easy to handle decentralized "where is the others who I should know about and should know about me"?
The easiest way to do this in Java (and completely inside your own application) is with the jmdns project. http://jmdns.sourceforge.net/
|
2,300,351 | 2,300,409 | Playing MIDI out in OS X, C++ | How can I send MIDI messages out from a C++ program and have them play the sound from the General MIDI bank?
I've looked around and there doesn't seem to be a simple answer, and my brain starts to melt after reading long manuals about CoreMIDI and things like that.
I have a simple C++ game/synthesizer project, and all I want to do is, for example, when this ball hits the floor, trigger a C4 from the Grand Piano bank. I'm fine with the majority of the program, but the integral MIDI part has so far been utterly opaque to me.
I'd like to use CoreMIDI, because it seems like it might be simplest, but something multi-platform would be a bonus.
Thank you very much for any help!
| Another option would be rtmidi
It's aimed to be simple and crossplatform
I've used the similar rtaudio for realtime audio i/o, and it was relatively easy to use.
You should be able to list all midi devices with the example code, then select the GM bank, and send the appropriate MIDI message (note on/off message), after you select the piano with a program change message. Wikipedia has a helpful page to get started
|
2,300,401 | 2,300,761 | QApplication: How to shutdown gracefully on Ctrl-C | I have a QApplication that, depending on command line parameters, sometimes doesn't actually have a GUI window, but just runs without GUI. In this case, I want to shut it down gracefully if CTRL-C was hit. Basically my code looks like this:
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
... // parse command line options
if (no_gui) {
QObject::connect(&app, SIGNAL(unixSignal(int)),
&app, SLOT(quit()));
app.watchUnixSignal(SIGINT, true);
app.watchUnixSignal(SIGTERM, true);
}
...
return app.exec();
}
However, this does not work. CTRL-C seems to be caught (the application doesn't get killed), but it also doesn't exit. What am I missing?
| As it isn't documented, QApplication::watchUnixSignal shouldn't be used. And, from reading the code, it will not work properly when using the glib event dispatcher (which is the default on Linux).
However, in general you can safely catch Unix signals in Qt applications, you just have to write a bit of the code yourself. There is even an example in the documentation - Calling Qt Functions From Unix Signal Handlers.
|
2,300,471 | 2,300,511 | Windows Command Line History | I need to programmatically mount a WebDAV volume in Windows using C, and I think I'm going to use system() to achieve this (via the 'net use' command)... However, since net use requires that the password be written in plain text, I just wanted to make sure there's no logging of commands run in the Windows command line shell... I know in Mac OS X and Linux in some circumstances commands can be logged in the file .bash_history, so I thought maybe something similar was going on in Windows. I don't think so though, since nothing showed up on Google.
| The shell has a history, but it's only stored in memory not a log on disk. That said, it could end up in the swap file and open to (slightly non-trivial) discovery. Then again, if you did the connection directly in your own program using something like WNetAddConnection2, it could end up in the swap file anyway.
|
2,300,703 | 2,300,711 | STL vector taking up too much memory | Im using a STL vector in my SDL program. and it looks like this: vector< Bullet * > vec; this makes a vector that can contain pointers to Bullet objects. when i run my program i only add one item at a time using: vec.push_back( new_bullet ); (new_bullet is a pointer to a "new" Bullet object. then in a following function i erase an object using: vec.erase(...); vec.size() shows that the items are being pushed and popped properly. I'm running Ubuntu 9.10 and System Monitor shows my programs memory usage slowly increasing. Is it my program or something I'm missing about STL vector?
| Sounds like you're not deleteing the "bullet" objects as you remove them from the vector.
|
2,300,894 | 2,301,062 | Reading a process memory | I'm trying to read the process memory of a console program using ReadProcessMemory() API function.
Updated Code:
HWND hWnd = FindWindow(NULL, "Read Memory Window");
DWORD ProcessId;
ProcessId = GetProcessId(hWnd);
GetWindowThreadProcessId(hWnd, &ProcessId);
HANDLE hProcess = OpenProcess(PROCESS_VM_READ,FALSE, ProcessId);
SIZE_T NumberOfBytesRead;
CHAR Buffer[128] = {0};
dwAddr = 0x0012FD6C; //address of array to get
BOOL sucess = ReadProcessMemory(hProcess, &dwAddr, &Buffer, 128, &NumberOfBytesRead);
I get null and garbage values as i run the program along with program to read the array.
| your using a fixed address, that is generally a very bad idea, even more so now that windows vista and windows 7 use ASLR, making it unsafe for even fixed based modules(even without ASLR its unsafe, because the image can reallocated for various reasons).
also, that address looks very dodgy, how did you derive that address? and is it adjusted correctly as a virtual address and not a relative address?
finally and most importantly, you shouldn't be passing the address and buffer as you do, it should be passed like so:
BOOL sucess = ReadProcessMemory(hProcess, (LPVOID)dwAddr, &Buffer[0], 128, &NumberOfBytesRead);
or
BOOL sucess = ReadProcessMemory(hProcess, (LPVOID)dwAddr, Buffer, 128, &NumberOfBytesRead);
|
2,300,895 | 2,300,918 | How to add many strings in c++ | As I know that C++ only allows to add 2 strings together, i.e:
s = s1 + s2
But how can I add many strings together? Like:
s = s1 + s2 + s3 + s4 + ... + sn
| If you're trying to append string objects of std::string class, this should work.
string s1 = "string1";
string s2 = "string2";
string s3 = "string3";
string s = s1 + s2 + s3;
OR
string s = string("s1") + string("s2") + string("s3") ...
|
2,301,065 | 2,301,080 | Why use template<> without specialization? | I was reading the STL source code (which turned out to be both fun and very useful), and I came across this kind of thing
//file backwards/auto_ptr.h, but also found on many others.
template<typename _Tp>
class auto_ptr
//Question is about this:
template<>
class auto_ptr<void>
Is the template<> part added to avoid class duplication?
| That's specialization. For example:
template <typename T>
struct is_void
{
static const bool value = false;
};
This template would have is_void<T>::value as false for any type, which is obviously incorrect. What you can do is use this syntax to say "I'm filling in T myself, and specializing":
template <> // I'm gonna make a type specifically
struct is_void<void> // and that type is void
{
static const bool value = true; // and now I can change it however I want
};
Now is_void<T>::value is false except when T is void. Then the compiler chooses the more specialized version, and we get true.
So, in your case, it has a generic implementation of auto_ptr. But that implementation has a problem with void. Specifically, it cannot be dereferenced, since it has no type associated with it.
So what we can do is specialize the void variant of auto_ptr to remove those functions.
|
2,301,363 | 2,301,375 | Creating a unique, auto assigned variable with Microsofts Extensible Storage Engine | I'm using Extensible Storage Engine and want a unique column (32bits wide). I need the values in this column to be auto assigned by the database
I'm hoping to find something like JET_bitIndexUnique that I can mask in?
if there isnt such a mask whats the proper way to achieve the goal?
| Please see: Version, Auto-Increment and Escrow Columns
Auto increment columns are automatically
incremented by ESE when a new record
is inserted into the table. The value
contained in the auto-increment column
is unique for every record in the
table and is not guaranteed to be
continuous. These values are not
recycled, but can be reused in certain
cases. Only columns of type
JET_coltypLong (Long) and JET_coltypLongLong
(Currency) may be auto increment columns.
Wiki: Extensible Storage Engine
|
2,301,371 | 2,301,401 | SendMessage Always returns ZERO? | Why does Windows SendMessage() always return ZERO, even the message delivery is success? Is there anyway to check the message delivery failure with SendMessage() ?
EDIT
Forgot to mention that I'm using SendMessage() inside a c++ DLL
LRESULT result = ::SendMessage(hwndOtherWindow,WM_COPYDATA, NULL/*(WPARAM)this->GetSafeHwnd()*/,(LPARAM)&structCDS);
"result" is always zero :(, but message delivers to other window successfully
EDIT
BOOL CDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
return /*CDialog::OnCopyData(pWnd, pCopyDataStruct)*/ true; //true is the trick
}
| A zero return from SendMessage for WM_COPYDATA means the target application didn't process the message (FALSE = 0).
The message might deliver successfully, but if the target application doesn't handle the message properly (ie, wrong return value, or passing it to the default window procedure) then your SendMessage call will appear to come back with the wrong result.
It might be worth your time to see what the target application's handling of the WM_COPYDATA message is, if possible.
|
2,301,372 | 2,301,427 | Undefined/Unspecified/Implementation-defined behaviour warnings? | Can't a compiler warn (even better if it throws errors) when it notices a statement with undefined/unspecified/implementation-defined behaviour?
Probably to flag a statement as error, the standard should say so, but it can warn the coder at least. Is there any technical difficulties in implementing such an option? Or is it merely impossible?
Reason I got this question is, in statements like a[i] = ++i; won't it be knowing that the code is trying to reference a variable and modifying it in the same statement, before a sequence point is reached.
| It all boils down to
Quality of Implementation: the more accurate and useful the warnings are, the better it is. A compiler that always printed: "This program may or may not invoke undefined behavior" for every program, and then compiled it, is pretty useless, but is standards-compliant. Thankfully, no one writes compilers such as these :-).
Ease of determination: a compiler may not be easily able to determine undefined behavior, unspecified behavior, or implementation-defined behavior. Let's say you have a call stack that's 5 levels deep, with a const char * argument being passed from the top-level, to the last function in the chain, and the last function calls printf() with that const char * as the first argument. Do you want the compiler to check that const char * to make sure it is correct? (Assuming that the first function uses a literal string for that value.) How about when the const char * is read from a file, but you know that the file will always contain valid format specifier for the values being printed?
Success rate: A compiler may be able to detect many constructs that may or may not be undefined, unspecified, etc.; but with a very low "success rate". In that case, the user doesn't want to see a lot of "may be undefined" messages—too many spurious warning messages may hide real warning messages, or prompt a user to compile at "low-warning" setting. That is bad.
For your particular example, gcc gives a warning about "may be undefined". It even warns for printf() format mismatch.
But if your hope is for a compiler that issues a diagnostic for all undefined/unspecified cases, it is not clear if that should/can work.
Let's say you have the following:
#include <stdio.h>
void add_to(int *a, int *b)
{
*a = ++*b;
}
int main(void)
{
int i = 42;
add_to(&i, &i); /* bad */
printf("%d\n", i);
return 0;
}
Should the compiler warn you about *a = ++*b; line?
As gf says in the comments, a compiler cannot check across translation units for undefined behavior. Classic example is declaring a variable as a pointer in one file, and defining it as an array in another, see comp.lang.c FAQ 6.1.
|
2,301,615 | 2,301,636 | sorting vector with 3D points by a coordinate value -- syntax | I want to sort points_vec vector as shown in the pseudocode below. I want to sort this vector, by a coordinate value like x or y or z
class A{
std:vector<double*> points_vec;
void doSomething();
}
Then, in method A::doSomething, I want sort this vector:
void A::doSomething() {
std::sort(points_vec.begin(), points_vec.end(), sortPoints());
}
Can someone please show me syntax for the sortPoints() method.. Preferably I want it to be a method of class A. this post creates a struct to do this, not sure if I should create a similar struct within the class. Is there another way to handle this?
thanks
| You have two options for sorting: either pass a function/functor to sort or define the operator< for your class. Now, your class A seems to be more of a wrapper for a set of coordinates. So, create another class for your co-ordinates.
struct Point {
double x_, y_, z_;
Point(double x, double y, double z) : x_(x), y_(y), z_(z) {}
// just an example, you can refine the following as much as you need
bool operator<(Point const& other) {
return x < other.x;
}
};
bool sortOnY(Point const& l, Point const& r) const {
return l.y < r.y;
}
class A {
std::vector<Point> pts_;
void doSomething() {
sort(pts_.begin(), pts_.end());
}
// if sorting on y is also required, you will need
// to use a custom comparator which can be either
// a functor or a function
void doSomeOtherThing() {
sort(pts_.begin(), pts_.end(), sortOnY);
}
};
|
2,301,839 | 2,301,868 | Class constructed only on stack; not with new. C++ | Is there a way to create a class Foo
so that I can do:
Foo foo;
but not
Foo* foo = new Foo();
?
I don't want people to be able to allocate copies of Foo on the heap.
Thanks!
EDIT: Sorry, I was wrong on the "stack only, not heap". What I want to say is "can not use new operator".
| Make your operator new private.
#include <new>
struct Foo {
int x;
private:
void* operator new (std::size_t size) throw (std::bad_alloc);
};
On C++0x you can delete the operator new:
struct Foo {
int x;
void* operator new (std::size_t size) throw (std::bad_alloc) = delete;
};
Note that you need to do the same for operator new[] separately.
|
2,301,928 | 2,301,994 | measuring response time through packets? | good day!
im developing an app in c++ and winpcap that will list all the URL accessed in the browser with its corresponding response time..
currently, i can now track or monitor all accessed url through capturing and analyzing packets..
is there any way of measuring the response time of a web page to load, from the request made to the server's response?..
any easy way?
thanks..
| You will have to keep track of the individual TCP connections between the browser and the server -
that's just keeping track of the source/destination IP and port numbes in the packets you capture.
Then you'll have to parse the HTTP in the captured packets and correlate HTTP requests with its response and take the time difference(which you'll get from the timestamps from pcap).
This is non-trivial in the cases the HTTP request/responses spans several packets, and certainly non-trivial if you also want to account for lost packets and retransmission.
|
2,301,991 | 2,302,007 | C++ Portable way of programmatically finding the executable root directory |
Possible Duplicate:
how to find the location of the executable in C
Hi,
I am looking for a portable way to find the root directory of a program (in C++). For instance, under Linux, a user could copy code to /opt, add it to the PATH, then execute it:
cp -r my_special_code /opt/
export PATH=${PATH}:/opt/my_special_code/
cd /home/tony/
execution_of_my_special_code
(where "execute_my_special_code" is the program in /opt/my_special_code).
Now, as a developer of "execution_of_my_special_code", is there a portable programmatical way of finding out that the executable is in /opt/my_special_code?
A second example is on MS Windows: What if my current working directory is on one hard drive (e.g. "C:\") and the executable is placed on another (e.g. "D:\")?
Ultimately, the goal is to read some predefined configuration files that are packaged with the program code without forcing the user to enter the installation directory.
Thanks a lot in advance!
| There is no portable way of doing this. Neither the C nor C++ standard require the argv array to hold this information and there are no library routines in the standard libraries that provide it.
You will need to find a non-portable way of obtaining this information in a platform-specific way, such as GetModuleFileName under Windows or reading /proc/self/exe under Linux.
In any case, it's actually a bad idea to store configuration information with the executable since that means it's the same for all users. The UNIX way of doing this is to store program-specific information in the /etc tree and user-specific info in the user's home directory. For example, for your application called dodgybob, the user's configuration file could be called $HOME/.dodgybob or $HOME/.dodgybobrc.
For Windows, you should be storing program-specific information in the registry (HKLM) and user-specific information either in the registry (HKCU) or in the user's own areas (e.g., Documents & Settings\<username>\Local Settings although the right way to do that is with SHGetSpecialFolderPath passing CSIDL_APPDATA or (Vista and later) with known folder IDs, though the old method still works on Vista as a stub function).
|
2,302,251 | 2,302,259 | checking if a point is already in a vector/list -- performance | This is related to this question
I have a vector of points that will, for instance, store 100K+ points.
std::vector<Point> point_vec;
I want to check if a position (x, y, z) to be added is already in point_vec (represented by an instance of class Point ). The following function will check this (in a for loop)
bool samePoints(const Point& p1,
const double x1,
const double y1,
const double z1) {
return fabs(p1.x - x1) < EPSILON &&
fabs(p1.y - y1) < EPSILON &&
fabs(p1.z - z1) < EPSILON;
}
But, I guess checking if x in list/ vector will be a costly operation. I want to know if there is a better way to check if a) Points are equal (perhaps an operator "=" on class Point?? and (b) Is there some other , better data structure than `vector' that I should make use of. OR if there is an operation on vector that will speed up checking for 'same points'
For (b) please note that I need to std::sort these points as well. So any other data structure that you may suggest should be able to sort these points.
UPDATE
I want the points in the sorted state only. It is just that vector doesn't sort those (so I need to perform a sort operation. Should I use std::set<Point> point_set instead of instead of std::vector <Point> point_vec ? IF SO: Is adding each point to a set a costly operation ? Or 'vector' sorting that I do in the end turns out costlier overall?
| Is the collection of points always sorted or must it sometimes be in an unsorted state? If the former, a std:;set of points will be fast to determine if a point is already there, and will maintain the points in sorted order. You would have to supply a suitable ordering function (not an equality one), which may be faster than your equality test.
|
2,302,279 | 2,302,463 | Return an array in c++ | Suppose I have an array
int arr[] = {...};
arr = function(arr);
I have the function as
int& function(int arr[])
{
//rest of the code
return arr;
}
What mistake am I making over here??
| int& function(int arr[])
In this function arr is a pointer, and there's no way to turn it back to an array again. It's the same as
int& function(int* arr)
int arr[] = {...};
arr = function(arr);
Assuming the function managed to return a reference to array, this still wouldn't work. You can't assign to an array. At best you could bind the result to a "reference of an array of X ints" (using a typedef because the syntax would get very ugly otherwise):
typedef int ten_ints[10];
ten_ints& foo(ten_ints& arr)
{
//..
return arr;
}
int main()
{
int arr[10];
ten_ints& arr_ref = foo(arr);
}
However, it is completely unclear what the code in your question is supposed to achieve. Any changes you make to the array in function will be visible to the caller, so there's no reason to try to return the array or assign it back to the original array.
If you want a fixed size array that you can assign to and pass by value (with the contents being copied), there's std::tr1::array (or boost::array). std::vector is also an option, but that is a dynamic array, so not an exact equivalent.
|
2,302,288 | 2,302,506 | Set up CUTE (Eclipse CDT Unit Testing Plugin) on OSX | I am trying to set up the CUTE unit testing plugin for Eclipse C/C++ Development Tools.
The documentation says:
If you did not install Boost in the standard location, you will need to specify it. Right click on the newly created CUTE project, and select Properties. In C/C++ Build, Settings, choose the Tool Settings tab. Specify the Boost include path in GCC C++ Compiler, Directories, and specify the library path and the boost_thread library name, for example, boost_thread-gcc-mt-d-1_33.
What is the bolded part talking about? I have no idea what it is asking me to do.
So far I downloaded boost and moved the directory to /usr/local/, then I added "/usr/local/boost_1_42_0/boost" to the include path list under Project Properties > C/C++ Build > Settings > Tool Settings > GCC C++ Compiler > Directories in my Cute Project, but Eclipse is still giving me lots of errors and warnings indicating that it cannot find boost, eg:
Errors:
Description Resource Path Location Type
'boost_or_tr1' has not been declared cute_suite_test.h /helloworld/cute line 45 C/C++ Problem
'boost_or_tr1' has not been declared cute_test.h /helloworld/cute line 53 C/C++ Problem
'boost_or_tr1' was not declared in this scope cute_testmember.h /helloworld/cute line 30 C/C++ Problem
'boost_or_tr1' was not declared in this scope cute_testmember.h /helloworld/cute line 34 C/C++ Problem
'boost' is not a namespace-name cute_equals.h /helloworld/cute line 41 C/C++ Problem
'boost' is not a namespace-name cute_suite_test.h /helloworld/cute line 33 C/C++ Problem
'boost' is not a namespace-name cute_test.h /helloworld/cute line 34 C/C++ Problem
Warnings:
Description Resource Path Location Type
boost/bind.hpp: No such file or directory cute_suite_test.h /helloworld/cute line 32 C/C++ Problem
boost/function.hpp: No such file or directory cute_test.h /helloworld/cute line 33 C/C++ Problem
boost/type_traits/is_floating_point.hpp: No such file or directory cute_equals.h /helloworld/cute line 34 C/C++ Problem
boost/type_traits/is_integral.hpp: No such file or directory cute_equals.h /helloworld/cute line 33 C/C++ Problem
boost/type_traits/make_signed.hpp: No such file or directory cute_equals.h /helloworld/cute line 35 C/C++ Problem
This is my first time attempting C++ development in about 10 years and I am really lost here. Any help would be greatly appreciated!
| While many libraries in boost are header-only, some require libraries (as in .lib .a .dyld &c) to be built. Here are instructions on building boost.
As the bold part says "specify the library path and the boost_thread library name", it seems like you should build boost sources so that it produces needed libraries, like in your case libboost_thread. Then specify path and the name of that lib in your project settings.
Apart from that I think you also need to specify include paths, as /usr/local/<boost_somthing> is not likely to be found by default, hence all those 'boost' is not a namespace-name errors.
|
2,302,388 | 2,302,575 | Draw a antialiased line in a fast way | I have a little problem. I've recently created an algorithm to allow thick lines to be drawed onscreen (as a quad structure), the problem is that when the line is very long and diagonal the aliasing is very high, making the line look very bad.
What are my chance to reduce the aliasing while trying to have high performance?
I'm using (as the tags says) DirectX as graphics API.
| There is a very good article in GPU Gems 2 about antialiasing technique for lines, see it here:
http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter22.html
|
2,302,419 | 2,302,492 | C++ TCL (tree container library): How to traverse a tree from a node straight to root | I am using this library to hold information about tree structure:
http://www.datasoftsolutions.net/tree_container_library/overview.php
Here is simplified version of my C++ code:
#include "tcl/sequential_tree.h"
// Node has some data which is not important now
typedef sequential_tree<Node> gametree_t;
typedef sequential_tree<Node>::iterator gametree_iter;
int main() {
gametree_t gametree;
gametree_iter gametree_it;
gametree_it = gametree.insert(Node(0));
gametree_it->insert(Node(1));
gametree_it->insert(Node(2));
gametree_it = gametree_it->insert(Node(3));
gametree_it->insert(Node(4));
gametree_it = gametree_it->insert(Node(5));
gametree_it->insert(Node(6));
return 1;
}
The tree looks like this
0
|_ 1
|_ 2
|_ 3
|_4
|_5
|_6
I am trying to make a function which given the Node(6) will traverse all the nodes leading to root i.e 6,5,3,0. This is my first project in C++ and I have trouble understanding pointers. Probably it is a few lines of C++ but I'm trying to do this for a couple of hours with no success. Any help will be appreciated.
something like this works but it must work with many levels not only with 4:
gametree_it->get()->get_value();
gametree_it->parent()->get()->get_value();
gametree_it->parent()->parent()->get()->get_value();
gametree_it->parent()->parent()->parent()->get()->get_value();
| the common method is to use something like this
Node tmp = gametree_it;
while (tmp->parent() != NULL) {
tmp = tmp->parent();
}
root = tmp->get();
Maybe you have to use while (tmp->has_parent()) or something like that instead.
|
2,302,475 | 2,302,498 | unresolved external symbol "public: void __thiscall..." | I'm using boost::function to enable the passing of a function to a Button constructor so it holds that function. Calling it whenever it is activated.
typedef boost::function< void() > Action;
In my TitleState I've constructed a Button like this.
m_play(
ButtonAction, // This is where I pass a function to Button's Action argument
sf::Vector2f( 500, 400 ),
sf::IntRect( 500, 400, 700, 500 )
)
where ButtonAction is a static void function privately held in TitleState's header, defined in the implementation file as simply outputting to the console via std::cout (just as a test for whether it is working).
In my code, if the mouse clicks a button in TitleState's HandleEvents function, the program calls that button's Activate function which looks like this.
void Button::Activate() const {
m_action(); // m_action is the Action member that holds the ButtonAction I passed earlier
}
The problem is that, when the program tries to link I get this error....
unresolved external symbol "public: void __thiscall Button::Activate(void)" (?Activate@Button@@QAEXXZ) referenced in function "public: virtual void __thiscall TitleState::HandleEvents(void)" (?HandleEvents@TitleState@@UAEXXZ)
I'm not sure what the problem is besides that the linker can't find the definition of the function. Everything is #included or declared properly. Any assistance is appreciated. Thanks.
P.S. When I used the BoostPro installer, I only installed the single-threaded stuff and none of the multi-threaded stuff. Could this be a reason why it isn't working? I read that linker problems can occur when libraries are linking in different ways. If this could be an issue, I'll add that I'm also using the SFML library.
| Add the library option when you are linking your program:
g++:
g++ -L/your/library/path -lyour_library_name
vc++:
using boost with vc++
|
2,302,487 | 2,305,834 | OpenGL Texture Transparency | I'm using C++ and OpenGL to make a basic 2D game, I have a png image with transparent areas for my player. It works perfectly on my laptop and lab computers, but on my desktop the entire image is mostly see through, not just the areas that are meant to be. What could cause/fix this?
Here is the code I've used and is the same on all machines
glPushMatrix();
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture(GL_TEXTURE_2D, playerTex);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTranslatef(XPos, YPos, 0.0);
glRotatef(heading, 0,0,1);
glBegin(GL_POLYGON);
glTexCoord2f(0.0, 1.0); glVertex2f(-40,40);
glTexCoord2f(0.0, 0.0); glVertex2f(-40,-40);
glTexCoord2f(1.0, 0.0); glVertex2f(40,-40);
glTexCoord2f(1.0, 1.0); glVertex2f(40,40);
glEnd();
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
| I found the problem, I changed
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
to
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
and it works correctly, not sure why though.
|
2,302,713 | 2,302,766 | Problem with method in a class when called from another class | I'm writing a simple scene graph to hold some objects so I can control the rendering and drawing of these objects in OpenGL. I have two classes, one called GameObject which defines the objects with certain parameters such as position and velocity as well as how to draw the object. It has a method called update() which is used to calculate any change in position and then calls the draw() to draw itself onto the screen.
Another class is called sceneNode. This class controls the data structure which I use to store the objects. This an instance of this class contains a pointer to a GameObject instance to allow me to access the data and a sceneNode has children of type sceneNode stored in a vector.
Each class works perfectly well on their own. I can add children to the scene graph etc and I can create a GameObject and tell it to draw itself and everything works as expected.
I then added a new method to sceneNode which is called render(), this method gets the pointer to gameObject and calls it's update function before calling render() on any children of the node.
The problem is: the update() method is called and the GameObject is drawn but it is always drawn in the same place and doesn't move despite having a velocity and change in position. Calling the update() function by using an instance of GameObject DOES draw the object and move the object around the screen. I've been staring at this code for hours and can't see what I'm missing. I'm still fairly new to the idea of pointers and calling methods from another class so I may have missed something obvious.
Here are the relevant methods:
GameObject.cpp:
The variables position, velocity etc are listed as protected.
void GameObject::update(){
for (int i = 0; i<3;i++){
this->velocity[i] +=this->acceleration[i];
}
this->position[0] += this->velocity[0];
this->position[1] += this->velocity[1];
this->position[2] += this->velocity[2];
this->draw();
}
void GameObject::draw() {
glTranslatef(this->position[0], this->position[1], this->position[2]);
glBegin(GL_TRIANGLES);
for (int i = 0; i < this->num_tris; i++) {
for (int j = 0; j <3 ; j++) {
glVertex3fv(vertices[triangles[i].INDEXES[j]]);
}
}
glEnd();
}
sceneNode.cpp:
void sceneNode::render(){
GameObject *go = new GameObject();
go = this->data;
//data is the name of the variable storing a pointer to a GameObject
go->update();
//update() is a method that redraws the object and calc's new position etc
if (hasChildren()) { //if this node has children, render all of them aswell...
for (int i = 0; i< this->node_tree.size(); i++) {
this->node_tree.at(i).render();
}
}
sceneNode.h:
This is how the GameObject pointer is set up in the sceneNode
Protected:
GameObject* data;
I'm lost as to why the position is not changing for the render() method but is for the update() method as they are both calling the same thing?
Thanks for any help
| There are some big problems here.
GameObject *go = new GameObject();
go = this->data;
You're creating a new object and then you are forgetting the pointer to that object. This happens every time you call render, so you have tons of memory that you aren't using that grows with time. You can just say:
GameObject *go = NULL;
to create a pointer without allocating data to it.
You can also omit the this->foo everywhere. It's implied within all classes.
So although I can't see the error in this code, chances are it is elsewhere, since you're making mistakes with pointers like above. You probably have pointers pointing to things you're not drawing. If you look at the memory addresses of the things that are updating and the memory addresses of the things being updated in render(), they may actually be different. If they are then you know that you're not calling update on the same things you are drawing. To get a memory address look at the value of 'this' within a function call. Write them down and make sure they are the same as the objects you are drawing. The error is not in this code.
|
2,302,734 | 2,302,806 | Memory debugger for mixed-mode C++ applications | I have to maintain a large C++ mixed-mode application (VC++ 2005, CLR-support: /clr:oldsyntax). I suspect the program has a number of memory leaks but it's hard to find them manually. For native C++ applications we use Purify (and Valgrind on Linux).
Unfortunately Purify does not support mixed mode assemblies. Anybody here knows a decent memory debugger with support for mixed mode assemblies?
| Take a look at AQTime. I've used it and it's pretty decent. They also provide a free trial version that's unhindered (last I checked).
|
2,302,815 | 2,303,509 | VS C++ 2008: Modifying Output text? | I'm using Visual Studio C++ 2008 Express Edition.
Is it possible to modify the text in the Output pane for compilation (or other) errors?
For example, I might receive an error that reads: error C2556: int Class::getResult(void) + a lot more relative garbage.
I can parse the output text and find and fix my mistakes easily. It would still be nice/useful if I could modify the errors to make them cleaner, shorter, and more friendly. An example would be receiving an error that read: "Source.cc (Line 10): Missing a closing;"
| It's pretty easy to take your best shot at this problem. The compiler itself is a command-line program named cl.exe. If you want to filter its output, what you need to do is create a program that's also named cl.exe. It will need to pass all the command line arguments through to the original cl.exe. Then it'll take whatever the original one produces as messages on its standard output, parse them, replace them with the messages you prefer, and print those to its own standard output.
When you do that, you'll probably want to at least retain the information about the file and line where the problem occurred in the original format. The IDE parses and uses that to support navigating among errors (e.g., with F4 or double-clicking).
|
2,302,841 | 2,303,612 | Win32 PlaySound: How to control the volume? | I'm using the Win32 MultiMedia function PlaySound to play a sound from my application.
I would like to be able to dynamically adjust the volume of the sound that is being played without modifying the system volume level.
The only suggestions I could find for manipulating the volume of sounds played via PlaySound was to use waveOutSetVolume, however that function sets the system-wide volume level (not what I want).
| Two possible solutions:
First, if you are targeting Vista and up, you can use the new Windows Audio APIs to adjust the per-application volume. ISimpleAudioVolume, IAudioEndpointVolume, etc...
If that's not suitable, can load the WAV file directly into memory and modify the samples in place. Try this:
Read the WAV file from disk and into a memory buffer and scale the samples back. I'm going to assume that the WAV file in question is 16-bit stereo with uncompressed (PCM) samples. Stereo or mono. If it's not, much of this goes out the window.
I'll leave the reading of the WAV file bytes into memory as an exercise for the reader: But let's start with the following code, where "ReadWavFileIntoMemory" is your own function.
DWORD dwFileSize;
BYTE* pFileBytes;
ReadWavFileIntoMemory(szFilename, &pFileBytes, &dwFileSize);
At this point, an inspection of pFileBytes will look something like the following:
RIFF....WAVEfmt ............data....
This is the WAV file header. "data" is the start of the audio sample chunk.
Seek to the "data" portion, and read the 4 bytes following "data" into a DWORD. This is the size of the "data" chunk that contains the audio samples. The number of samples (assuming PCM 16-bit is this number divided by 2).
// FindDataChunk is your function that parses the WAV file and returns the pointer to the "data" chunk.
BYTE* pDataOffset = FindDataChunk(pBuffer);
DWORD dwNumSampleBytes = *(DWORD*)(pDataOffset + 4);
DWORD dwNumSamples = dwNumSamplesBytes / 2;
Now, we'll create a sample pointer that points to the first real sample in our memory buffer:
SHORT* pSample = (SHORT*)(pDataOffset + 8);
pSample points to the first 16-bit sample in the WAV file. As such, we're ready to scale the audio samples to the appropriate volume level. Let's assume that our volume range is between 0.0 and 1.0. Where 0.0 is complete silence. And 1.0 is the normal full volume. Now we just multiply each sample by the target volume:
float fVolume = 0.5; // half-volume
for (DWORD dwIndex = 0; dwIndex < dwNumSamples; dwIndex++)
{
SHORT shSample = *pSample;
shSample = (SHORT)(shSample * fVolume);
*pSample = shSample;
pSample++;
if (((BYTE*)pSample) >= (pFileBytes + dwFileSize - 1))
break;
}
At this point, you are ready to play your in memory WAV file with PlaySound:
PlaySound((LPCSTR)pFileBytes, NULL, SND_MEMORY);
And that should do it. If you are going to use the SND_ASYNC flag to make the above call non-blocking, then you won't be able to free your memory buffer until it has finished playing. So be careful.
As for the parsing of the WAV file header. I hand-waved my way out of that by declaring a hypothetical function called "FindDataChunk". You should probably invest in writing a proper WAV file header parser rather than just seeking to where you first encounter "data" in the header. For the sake of brevity, I left out the usual error checking. As such, there may be a few security concerns to address with the above code - especially as it relates to traversing the memory buffer and writing into it.
|
2,302,969 | 2,303,798 | Convert a float to a string | How can I convert a floating point integer to a string in C/C++ without the library function sprintf?
I'm looking for a function, e.g. char *ftoa(float num) that converts num to a string and returns it.
ftoa(3.1415) should return "3.1415".
| When you're dealing with fp numbers, it can get very compex but the algorithm is simplistic and similar to edgar holleis's answer; kudos! Its complex because when you're dealing with floating point numbers, the calculations will be a little off depending on the precision you've chosen. That's why its not good programming practice to compare a float to a zero.
But there is an answer and this is my attempt at implementing it. Here I've used a tolerance value so you don't end up calculating too many decimal places resulting in an infinite loop. I'm sure there might be better solutions out there but this should help give you a good understanding of how to do it.
char fstr[80];
float num = 2.55f;
int m = log10(num);
int digit;
float tolerance = .0001f;
while (num > 0 + precision)
{
float weight = pow(10.0f, m);
digit = floor(num / weight);
num -= (digit*weight);
*(fstr++)= '0' + digit;
if (m == 0)
*(fstr++) = '.';
m--;
}
*(fstr) = '\0';
|
2,303,067 | 2,303,085 | Initialize static member of template inner class | I have problem with the syntax needed to initialize a static member in a class template. Here is the code (I tried to reduce it as much as I could):
template <typename T>
struct A
{
template <typename T1>
struct B
{
static T1 b;
};
B<T> b;
typedef B<T> BT;
T val() { return b.b; }
};
template <typename T>
T A<T>::BT::b;
struct D
{
D() : d(0) {}
int d;
};
int main()
{
A<D> a;
return a.val().d;
}
With g++, the error I get is:
error: too few template-parameter-lists
Any ideas how to initialize b?
Note that I would like to keep the typedef, as in my real code, B is way more complex than that.
| Change the definition of b to the following:
template <typename T> template<typename T1>
T1 A<T>::B<T1>::b;
Notice that the typedef and B<T1> don't necessarily specify the same type: While the typedef relies on T being passed to B, B<T1> relies on the template parameter T1 being passed. So you cannot use the typedef here to specify a definition for b in B<T1>.
|
2,303,087 | 2,303,103 | Assignment vs Initialization in C++ | I thought that constructors control initialization and operator= functions control assignment in C++. So why does this code work?
#include <iostream>
#include <cmath>
using namespace std;
class Deg {
public:
Deg() {}
Deg(int a) : d(a) {}
void operator()(double a)
{
cout << pow(a,d) << endl;
}
private:
int d;
};
int
main(int argc, char **argv)
{
Deg d = 2;
d(5);
d = 3; /* this shouldn't work, Deg doesn't have an operator= that takes an int */
d(5);
return 0;
}
On the third line of the main function, I am assigning an int to an object of class Deg. Since I don't have an operator=(int) function, I thought that this would certainly fail...but instead it calls the Deg(int a) constructor. So do constructors control assignment as well?
| This is what's called implicit type conversion. The compiler will look to see if there's a constructor to directly change from the type you're assigning to the type you're trying to assign, and call it. You can stop it from happening by adding the explicit keyword in front of the constructor you wouldn't like to be implicitly called, like this:
explicit Deg(int a) : d(a) {}
|
2,303,188 | 2,303,197 | const correctness and return values - C++ | Please consider the following code.
struct foo
{
};
template<typename T>
class test
{
public:
test() {}
const T& value() const
{
return f;
}
private:
T f;
};
int main()
{
const test<foo*> t;
foo* f = t.value();
return 0;
}
t is a const variable and value() is a constant member-function which returns const T&. AFAIK, a const type is not assignable to a non-const type. But how foo* f = t.value(); compiles well. How this is happening and how can I ensure value() can be only assigned to const foo*?
Edit
I found that, this is happening on when templates are used. Following code works as expected.
class test
{
public:
test() {}
const foo* value() const { return f; }
private:
foo* f;
};
int main()
{
const test t;
foo* f = t.value(); // error here
return 0;
}
Why the problem is happening when templates are used?
| Because you have two levels of indirection - in your main function, that call to value returns a reference to a const pointer to a non-const foo.
This can safely be copied into non-const pointer to a non-const foo.
If you'd instantiated test with const foo *, it would be a different story.
const test<const foo*> t;
foo* f = t.value(); // error
const foo* f = t.value(); // fine
return 0;
Update
From the comment:
value() returns const T& which can
only be assigned to another const
type. But in this case, compiler is
safely allowing the conversion.
Const data can only be read. It cannot be written ("mutated"). But copying some data is a way of reading it, so it's okay. For example:
const int c = 5;
int n = c;
Here, I had some const data in c, and I copied the data into a non-const variable n. That's fine, it's just reading the data. The value in c has not been modified.
Now, suppose your foo had some data in it:
struct foo { int n; };
If I have a non-const pointer to one of those, I can modify the n value through the pointer. You asked your test template to store a pointer to a non-const foo, and then made a const instance of test. Only the pointer address is constant, therefore. No one can change the address stored in the pointer inside test, so it cannot be made to point to another object. However, the object it points to can have its contents modified.
Update 2:
When you made your non-template version of the example, you made a mistake. To get it right, you need to substitute foo * into each place where there's a T.
const T& value() const
Notice that you have a reference to a const T there. So the return value will be a reference to something const: a foo *. It's only the pointer address that can't be modified. The object it points to can have its contents modified.
In your second example, you got rid of the reference part, which changes the meaning and makes the const modifier apply to the object that the pointer points to, instead of applying to the pointer itself.
|
2,303,264 | 2,303,284 | What is causing a segmentation fault? | I have been attempting to write a program that will determine if a number is prime or not. I have based it off of the Sieve of Eratosthenes. Anyway, my program works for small numbers (15485863 works), but if I use large numbers (ex. 17485863) I receive a segmentation fault. I am using unsigned long longs and do not think I have surpassed their maximum value. I just don't see what I have done wrong. Thank you in advance for any assistance!
#include <iostream>
#include <limits>
using namespace std;
bool soe (unsigned long long);
int main (void)
{
unsigned long long x = 17485863;
bool q = soe(x);
cout << x << " is ";
if(q)
cout << "prime." << endl;
else
cout << "not prime." << endl;
return 0;
}
bool soe(unsigned long long input)
{
unsigned long long arrayLength = input%2 + input/2;
unsigned long long index = 2;
unsigned long long greatestMult = 0;
bool array[arrayLength];
array[0] = true; //ignore true values in the array
array[1] = true;
do{
array[index] = false;
}while(++index < arrayLength);
index = 2;
do
{
if(input%index != 0)
{
greatestMult = input/index;
while(index*greatestMult > arrayLength)
greatestMult--;
do
{
array[index*greatestMult] = true;
}while(--greatestMult > 0);
do
{
if(!array[index])
break;
}while(++index < arrayLength);
}
else
{
cout << endl << input << " is divisble by " << index << endl;
return false;
}
}while(index < arrayLength);
return true;
}
| On Line 24 you have: bool array[arrayLength]; You cannot declare an array on the stack like this. The program is crashing on line 29. You need to declare this on the heap using new/delete;
Something to this effect (I may have a leak or two in there, but you get the idea);
//Beginning on Line 28
bool *array = new bool[arrayLength];
array[0] = true; //ignore true values in the array
array[1] = true;
do{
array[index] = false;
}while(++index < arrayLength);
index = 2;
do
{
if(input%index != 0)
{
greatestMult = input/index;
while(index*greatestMult > arrayLength)
greatestMult--;
do
{
array[index*greatestMult] = true;
}while(--greatestMult > 0);
do
{
if(!array[index])
break;
}while(++index < arrayLength);
}
else
{
cout << endl << input << " is divisble by " << index << endl;
delete [] array;
return false;
}
}while(index < arrayLength);
delete [] array;
return true;
}
Output
g++ -g test.cpp
gdb ./a.out
...clipped...
(gdb) run
Starting program: /Users/nextraztus/a.out
Reading symbols for shared libraries ++. done
17485863 is divisble by 3
17485863 is not prime.
Program exited normally.
(gdb)
|
2,303,345 | 2,303,369 | Undefined reference to | I'm doing an opengl/qt3 assignment, but I'm running into an undefined reference error:
Renderer.h:
...
#include "Mesh.h"
... Mesh mesh;
Renderer.cpp:
...
mesh.load("ball.obj");
...
Mesh.h:
...
bool load(string filename);
...
Mesh.cpp:
#include "Mesh.h"
...
bool Mesh::load(string filename) { ... }
...
but the compiler complains about the line mesh.load("ball.obj") as an undefined reference... What is going on? Thank you in advance!
| Forgot to add the files to QT Designer. Solved!
|
2,303,381 | 2,317,312 | Qt - how to detect what application is in focus | Is it possible to know what application is in focus using Qt ?
| You'll need to use some Win32 API functions. Mainly GetActiveWindow(). Search MSDN for the function.
|
2,303,408 | 2,303,574 | C++ Unwanted infinite while loop | I get an infinite loop when I use the following code in C++ and I don't understand why. I suspect the problem is within the input_words() function. Here is the code:
#include<iostream>
using namespace std;
string input_words(int maxWords) {
int nWord = 0;
string words[maxWords];
string aWord = "";
while (aWord != "Quit" && nWord < maxWords) {
cout << "Enter a number ('Quit' to stop): ";
getline (cin, aWord);
words[nWord] = aWord;
nWord++;
}
return *words;
}
int num_words (string words[], int maxWords) {
int numWords = 0;
for (int i=0; i<maxWords; i++) {
if (words[i] == "Quit") {
break;
}
numWords++;
}
return numWords;
}
int main() {
const int MAX_WORDS = 100;
string words[MAX_WORDS] = input_words(MAX_WORDS);
int lenWords = num_words(words, MAX_WORDS);
cout << "\nThere are " << lenWords << " words:\n";
for (int i=0; i<MAX_WORDS; i++) {
if (words[i] == "Quit") {
break;
}
cout << words[i] << "\n";
}
return 0;
}
More specifically, I can't exit even when I type 'Quit' when prompted for a word. How could I solve this? I know this is noob code :) I'm just starting on C++
| I modified the function in such a way:
string input_words(int maxWords) {
cout << "started" << endl;
int nWord = 0;
string words[maxWords];
string aWord = "";
while (aWord != "Quit" && nWord < maxWords) {
cout << "Enter a number ('Quit' to stop): ";
getline (cin, aWord);
words[nWord] = aWord;
nWord++;
}
cout << "finished" << endl;
return *words;
}
After inputting Quit, it prints "finished", and then "started" again.
Your code is calling the function several times.
The problem is that the function returns only one string. so the line
string words[MAX_WORDS] = input_words(MAX_WORDS);
seems to call the function input_words MAX_WORDS times.
A good way would be to switch to vector<string>:
vector<string> input_words(int maxWords) {
vector<string> words;
string aWord;
while (aWord != "Quit" && nWord < maxWords) {
cout << "Enter a number ('Quit' to stop): ";
getline (cin, aWord);
words.push_back(aWord);
}
return words;
}
...
vector<string> words = input_words(MAX_WORDS);
|
2,303,435 | 2,303,449 | How to declare vectors in C++? | I'm trying to use a vector of strings in my code instead of an array of strings but apparently I miss some detail in the declaration of the vector. Using the following code, I get this error: ‘vector’ was not declared in this scope
// Try to implement a vector of string elements
#include<iostream>
using namespace std;
int main() {
const int MAX_ITEMS = 10;
vector<string> my_vector(MAX_ITEMS);
return 0;
}
How should I correctly declare the vector?
| You should add these includes:
#include <vector>
#include <string>
|
2,303,440 | 2,303,478 | Limit Speed Of Gameplay On Different Computers | I'm creating a 2D game using OpenGL and C++.
I want it so that the game runs at the same speed on different computers, At the moment my game runs faster on my desktop than my laptop (i.e. my player moves faster on my desktop)
I was told about QueryPerformanceCounter() but I don't know how to use this.
how do I use that or is there a better/easier way?
My Display function
void display()
{
static long timestamp = clock();
// First frame will have zero delta, but this is just an example.
float delta = (float)(clock() - timestamp) / CLOCKS_PER_SEC;
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
createBackground();
int curSpeed = (player.getVelocity()/player.getMaxSpeed())*100;
glColor3f(1.0,0.0,0.0);
glRasterPos2i(-screenWidth+20,screenHeight-50);
glPrint("Speed: %i",curSpeed);
glRasterPos2i(screenWidth-200,screenHeight-50);
glPrint("Lives: %i",lives);
glRasterPos2i(screenWidth-800,screenHeight-50);
glPrint("Heading: %f",player.getHeading());
for(int i = 0;i<90;i++){
if (numBullets[i].fireStatus == true){
numBullets[i].updatePosition(player);
if (numBullets[i].getXPos() > screenWidth || numBullets[i].getXPos() < -screenWidth || numBullets[i].getYPos() > screenHeight || numBullets[i].getYPos() < -screenHeight ){
numBullets[i].fireStatus = false;
numBullets[i].reset(player);
numBullets[i].~Bullet();
}
}
}
player.updatePosition(playerTex,delta);
glFlush();
timestamp = clock();
}
My Update positiom method
void Player::updatePosition(GLuint playerTex, float factor){
//draw triangle
glPushMatrix();
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture(GL_TEXTURE_2D, playerTex);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTranslatef(factor*XPos, factor*YPos, 0.0);
glRotatef(heading, 0,0,1);
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
glTexCoord2f(0.0, 1.0); glVertex2f(-40,40);
glTexCoord2f(0.0, 0.0); glVertex2f(-40,-40);
glTexCoord2f(1.0, 0.0); glVertex2f(40,-40);
glTexCoord2f(1.0, 1.0); glVertex2f(40,40);
glEnd();
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
XPos += speed*cos((90+heading)*(PI/180.0f));
YPos += speed*sin((90+heading)*(PI/180.0f));
}
| As a rule, you want to do all gameplay calculations based on a time delta, i.e. the amount of time that has passed since the last frame. This will standardize speed on all machines. Unless you want extreme precision, you can use clock() (from <ctime>) to get the current timestamp.
Example:
void main_loop() {
static long timestamp = clock();
// First frame will have zero delta, but this is just an example.
float delta = (float)(clock() - timestamp) / CLOCKS_PER_SEC;
calculate_physics(delta);
render();
timestamp = clock();
}
void calculate_physics(float delta) {
// Calculate expected displacement per second.
applyDisplacement(displacement * delta);
}
void render() {
// Do rendering.
}
EDIT: If you want higher precision, you should use your OS timer features. On Windows, the most precise method is using QueryPerformanceCounter(). Example
#include <windows.h>
void main_loop(double delta) {
// ...
}
int main() {
LARGE_INTEGER freq, last, current;
double delta;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&last);
while (1) {
QueryPerformanceCounter(¤t);
delta = (double)(current.QuadPart - last.QuadPart) / (double)freq.QuadPart;
main_loop(delta);
last = current;
}
}
|
2,303,490 | 2,303,881 | Why can't the linker prevent the C++ static initialization order fiasco? | EDIT: Changed example below to one that actually demonstrates the SIOF.
I am trying to understand all of the subtleties of this problem, because it seems to me to be a major hole in the language. I have read that it cannot be prevented by the linker, but why is this so? It seems trivial to prevent in simple cases, like this:
// A.h
extern int x;
// A.cpp
#include <cstdlib>
int x = rand();
// B.cpp
#include "A.h"
#include <iostream>
int y = x;
int main()
{
std::cout << y; // prints the random value (or garbage)?
}
Here, the linker should be able to easily determine that the initialization code for A.cpp should happen before B.cpp in the linked executable, because B.cpp depends on a symbol defined in A.cpp (and the linker obviously already has to resolve this reference).
So why can't this be generalized to all compilation units. If the linker detects a circular dependency, can't it just fail the link with an error (or perhaps a warning, since it may be the programmer's intent I suppose to define a global symbol in one compilation unit, and initialize it in another)?
Does the standard levy any requirements on an implementation to ensure the proper initialization order in simple cases? What is an example of a case where this would not be possible?
I understand that an analogous situation can occur at global destruction time. If the programmer does not carefully ensure that the dependencies during destruction are symmetrical to construction, a similar problem occurs. Could the linker not warn about this scenario as well?
| Linkers traditionally just link - i.e. they resolve addresses. You seem to be wanting them to do semantic analysis of the code. But they don't have access to semantic information - only a bunch of object code. Modern linkers at least can handle large symbol names and discard duplicate symbols to make templates more useable, but so long as linkers and compilers are independent, that's about it. Of course if both linker and compiler are developed by the same team, and if that team is a big corporation, more intelligence can be put in the linker, but it's hard to see how a standard for a portable language can mandate such a thing.
If you want to know more about linkers, BTW, take a look at http://www.iecc.com/linker/ - about the only book on an often ignored tool.
|
2,303,555 | 2,303,674 | Taking user input with pointers | I'm trying to get better at using pointers, and not using array notation. So I have a function to read user input and return a pointer to that array. I can do it like this and it seems to work ok:
float *GetValues(float *p, size_t n)
{
float input;
int i = 0;
if ((newPtr = (float *)malloc(n * sizeof(float))) == NULL) {
cout << "Not enough memory\n";
exit(EXIT_FAILURE);
}
cout << "Enter " << n << " float values separated by whitespace: \n";
while (scanf("%f", &input) == 1) {
p[i] = input;
i++;
cout << *p;
}
return p;
}
But then if I do this:
float *GetValues(float *p, size_t n)
{
float *newPtr;
float input;
if ((newPtr = (float *)malloc(n * sizeof(float))) == NULL) {
cout << "Not enough memory\n";
exit(EXIT_FAILURE);
}
cout << "Enter " << n << " float values separated by whitespace: \n";
while (scanf("%f", &input) == 1) {
*newPtr++ = input;
}
return newPtr;
}
I get just 0s entered into p. Why is that?
Also, do I have to allocate memory here for an array of size n? I first tried it with the method above using pointers and not allocating memory but just set p = to input and I was getting garbage values. Thanks!
Edited: Sorry, I allocated a new ptr and was returning the wrong one like you said. I was just trying to input the numbers into my pointer and display it back on the screen to myself and wasn't paying attention to the return type and I was getting an output of 0 when I would cout << *newPtr.
| A few tips:
The first GetValues allocates newPtr (which is not declared within the function, a global variable?) but then does nothing with it. There are two possible ways that your function could work with regards to memory storage:
The function gets a pointer to valid memory for an array of size large enough. In that case the signature of the function ought to be
float *GetValues(float *array, size_t arraySize)
to more clearly state the nature of the arguments. You need not to allocate anything inside the function.
The function should allocate the needed memory itself and let the caller free the memory some time later. In that case you MUST have some kind of hint in the name of the function that it allocates memory. Otherwise you are in for a disaster in terms of maintaining this code because it will be extremely easy to make mistakes in freeing memory. You will not need to pass an array pointer to the function, but if you do it needs to be a double pointer for it to be of any meaning (C and C++ passes arguments by value so it is not possible to change a pointer which is passed as an argument)
float *GetValuesAndAllocateMemmory(size_t n)
float *GetValuesAndAllocateMemmory(float **array_pp, size_t n)
The loop in the second GetValues should be
float *start_p = p;
...
while (scanf("%f", &input) == 1) {
*p++ = input;
cout << *start_p;
}
return start_p;
in order to be identical to the first GetValues.
Here there is upper limit of number of float values is n but your code does not check this
cout << "Enter " << n << " float values separated by whitespace: \n";
while (scanf("%f", &input) == 1) {
and will crash if more than n floats are entered. Never trust user input data, even when it comes from yourself. Always verify. Search for the term "input validation" for more information about this.
cout << "Enter " << n << " float values separated by whitespace: \n";
entered_values = 0;
while (entered_values < n && scanf("%f", &input) == 1) {
entered_values++;
|
2,304,061 | 2,304,127 | Is it safe to use boost serialization to serialize objects in C++ to a binary format for use over a socket? | I know that you can use boost serialization to serialize to a text format and then push over a socket, but I'd like to serialize a class of statistics data into a binary format (both for size and encoding/decoding overhead reasons). Is it safe to use boost serialization for this?
My specific worries are:
Differences between integer type sizes on different platforms (mainly 32-bit vs 64-bit).
Though I can largely get around this by using exactly-sized integer from stdint, I'd still like to understand the behavior.
Differences in endianness between systems, does boost serialize into a standard endian-ness (eg: network ordering), and then deserialize using the host's endianness?
It's a very nice library, but unfortunately documentation on it's binary capabilities is somewhat limited, so I just want to make sure that using it this way would be safe.
| No, in general boost binary serialization is not machine-independent. See here.
|
2,304,077 | 2,304,094 | How do i create a unicode filename in linux? | I heard fopen supports UTF8 but i dont know how to convert an array of shorts to utf8
How do i create a file with unicode letters in it? I prefer to use only built in libraries (no boost which is not installed on the linux box). I do need to use fopen but its pretty simple to.
| fopen(3) supports any valid byte sequence; the encoding is unimportant. Use nl_langinfo(3) with CODESET to get what charset you should use for the encoding, and libiconv or icu for the actual encoding.
|
2,304,203 | 2,304,211 | How to use boost bind with a member function | The following code causes cl.exe to crash (MS VS2005).
I am trying to use boost bind to create a function to a calls a method of myclass:
#include "stdafx.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <functional>
class myclass {
public:
void fun1() { printf("fun1()\n"); }
void fun2(int i) { printf("fun2(%d)\n", i); }
void testit() {
boost::function<void ()> f1( boost::bind( &myclass::fun1, this ) );
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this ) ); //fails
f1();
f2(111);
}
};
int main(int argc, char* argv[]) {
myclass mc;
mc.testit();
return 0;
}
What am I doing wrong?
| Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
|
2,304,415 | 2,304,464 | question about recompiling the library in C++ | Suppose my class is depending on other library. Now I need to modify the class for one application. What kind of modification will force me to recompile
all libraries. What's the rule to recompile all libraries?
for example, I only know the case 2) is like this. What about the others?
1) add a constructor
2) add a data member
3) change destructor into virtual
4) add an argument with default value to an existing member function
| Do you really mean that the class you are changing depends on the library? You never have to recompile a library because you've changed something that depends on the library. You recompile a library if you change something that the library depends on.
The answer is that in C++, technically all of those things require recompiling anything that uses the class. The one definition rule only permits classes to be defined in multiple translation units if the definitions are exactly the same in all units (I think "exactly" means the same sequence of tokens after preprocessing, in which case even changing the name of a parameter requires recompilation). So if different source files share a header, and a class definition in that header changes, C++ guarantees nothing about whether code compiled from those two source files remains compatible if only one of them is rebuilt.
However, your particular C++ implementation will use a static/dynamic library format which relaxes the rules, and allows some changes to be "binary compatible". Of the things you list, only (1) has much chance of being binary compatible. You'd have to check your documentation, but it's probably fine. In general (2) changes the size and layout of the objects, (3) changes the code required by the caller to destroy objects, and (4) changes the signature of the function (default values are inserted by the calling code, not the callee).
It's often worth avoiding default parameters pretty much for this reason. Just add another overload. So instead of changing:
void foo(int a);
to
void foo(int a, int b = 0);
replace it with:
void foo(int a) { foo(a, 0); }
void foo(int a, int b);
Of course the former change isn't even source-compatible if a user is taking a pointer to the function foo, let alone binary compatible. The latter is source-compatible provided that the ambiguity is resolved over which foo to use. C++ does make some effort to help with this, initializing a function pointer is a rare (only?) case where context affects the value of an expression.
|
2,304,466 | 2,391,745 | Render webbrowser control offscreen (or hidden) | I have a small application which embeds webbrowser controls. In that application I have created a popup class. This popup is used to display server generated error messages.
I want to be able to resize the popup to suit the message. This is so a short message is not contained in an oversize form and a large message is not in an undersized form.
Rather than send a width and height I would like to calculate the dimensions on the fly. I also did not want to visibly resize the form, that is just plain ugly.
Everything I try fails :(
This is what I thought should work
create the form
move it offscreen by setting its left position to -1000
show the form (offscreen)
write the contents to the webrowser ctl
get the width and height after it renders
hide the form
resize the form to fit the above width and height
center it onscreen
show the form
That should work just great, except the webbrowser control refuses to render, therefore I can't get the client width and height
Does anyone know how this can be done?
DC
| I have solved the issue I was having. it was a timing one.
the problem was I was writing content to the webbrowser control. And then attempting to read the width and height. but the control hadn't rendered and so I was not getting those parameters.
I realised this early in the piece so I instead put the resize code in the ondocumentcomplete event. sadly what I didn't realise was this event is not called when you write directly to the document. somehow I managed to convince myself it wasn't being called because the control was hidden. that was not the case.
So once I managed to figure that out I put a message pump in after I called the write function and before I called the show function. the message pump looped around until the control returned complete (checks the readystate flag)
PopUp->Write(text.c_str());
while (!PopUp->Complete() && ProcessMessages()){ ; }
popup_ctlDownloadComplete(0);
now when the DownloadComplete event is called manually, the document has rendered and I can get the width and height.
The code above could cause an infinite loop if there is an error so I have added a counter to kill it should that happen. just not shown for brevity and clarity.
Oh and the code is legacy code not managed code
DC
|
2,304,608 | 2,304,771 | Reading socket reply in loop | I have:
char buf[320];
read(soc, buf, sizeof(buf));
//print buf;
However, sometimes the reply is much bigger then 320 characters, so I'm trying to run the read in a loop to avoid taking up too much memory space. I tried read(soc, buf, sizeof(buf)) but that only prints the same first x characters over again. How would I print the leftover characters that did not fit into the first 320 characters in a loop?
Thanks
| Change your loop to something like:
int numread;
while(1) {
if ((numread = read(soc, buf, sizeof(buf) - 1)) == -1) {
perror("read");
exit(1);
}
if (numread == 0)
break;
buf[numread] = '\0';
printf("Reply: %s\n", buf);
}
for the reasons Nikola states.
|
2,304,634 | 2,304,651 | Why do we need a Unit Vector (in other words, why do we need to normalize vectors)? | I am reading a book on game AI.
One of the terms that is being used is to normalize a vector which is to turn a vector into a unit. To do so you must divide each dimension x, y and z by its magnitude.
We must turn vector into a unit before we do anything with it. Why?
And could anyone give some scenarios where we must use a unit vector?
Thanks!
| You don't have to normalize vectors, but it makes a lot of equations a little simpler when you do. It could also make API's smaller: any form of standardization has the potential to reduce the number of functions necessary.
Here's a simple example. Suppose you want to find the angle between two vectors u and v. If they are unit vectors, the angle is just arccos(uv). If they're not unit vectors, the angle is arccos(uv/(|u| |v|)). In that case, you end up computing the norms of u and v anyway.
|
2,304,673 | 2,304,682 | Are destructors not meant to be called when returning that object (not as a pointer)? | I have a function:
static Bwah boo(){
Bwah bwah;
return bwah;
}
And a main function:
int main(){
Bwah boo = Assigner::boo();
cout << "got here.." << endl;
}
The destructor to Bwah is only called once, after the "got here" print.
Is this guaranteed or is this a compiler optimization?
| This is an optimization called Return Value Optimization (RVO). It is a common optimization, but you can't rely on it.
Here are two really excellent links for learning more:
First, a really detailed article about pass by value, rvalue semantics, the return value optimization, and rvalue references and the move constructor and assignment operator in C++0x
Second, the good old standby Wikipedia and their entry on the return value optimization.
The Wikipedia article in particular directly addresses your question. But the other article goes more in depth about the whole issue.
|
2,304,729 | 2,316,049 | How do I declare an array created using malloc to be volatile in c++ | I presume that the following will give me 10 volatile ints
volatile int foo[10];
However, I don't think the following will do the same thing.
volatile int* foo;
foo = malloc(sizeof(int)*10);
Please correct me if I am wrong about this and how I can have a volatile array of items using malloc.
Thanks.
| int volatile * foo;
read from right to left "foo is a pointer to a volatile int"
so whatever int you access through foo, the int will be volatile.
P.S.
int * volatile foo; // "foo is a volatile pointer to an int"
!=
volatile int * foo; // foo is a pointer to an int, volatile
Meaning foo is volatile. The second case is really just a leftover of the general right-to-left rule.
The lesson to be learned is get in the habit of using
char const * foo;
instead of the more common
const char * foo;
If you want more complicated things like "pointer to function returning pointer to int" to make any sense.
P.S., and this is a biggy (and the main reason I'm adding an answer):
I note that you included "multithreading" as a tag. Do you realize that volatile does little/nothing of good with respect to multithreading?
|
2,304,732 | 36,835,959 | How do I specify an integer literal of type unsigned char in C++? | I can specify an integer literal of type unsigned long as follows:
const unsigned long example = 9UL;
How do I do likewise for an unsigned char?
const unsigned char example = 9U?;
This is needed to avoid compiler warning:
unsigned char example2 = 0;
...
min(9U?, example2);
I'm hoping to avoid the verbose workaround I currently have and not have 'unsigned char' appear in the line calling min without declaring 9 in a variable on a separate line:
min(static_cast<unsigned char>(9), example2);
| C++11 introduced user defined literals. It can be used like this:
inline constexpr unsigned char operator "" _uchar( unsigned long long arg ) noexcept
{
return static_cast< unsigned char >( arg );
}
unsigned char answer()
{
return 42;
}
int main()
{
std::cout << std::min( 42, answer() ); // Compile time error!
std::cout << std::min( 42_uchar, answer() ); // OK
}
|
2,304,834 | 2,307,639 | getting the right compiler for C++ | I am trying to learn c++ but most of the tutorials and books I have read or looked up teaches you this...
(I am assuming like most tutorials, they are teaching in the beginning to code either in win32 console or CLR console. In either case the following does not work.)
#include <iostream>
int main( )
{
std::cout << "Hello World\n";
return (0);
}
The IDE that i have is Visual C++ 2008 Express edition and they accept code like this
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
Or like this
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
return 0;
}
Honestly I do not no the difference in none of these and I am not sure if I should just download a older compiler so that it works. If someone can tell me what the difference in these are and where to go from there. That will help tremendously. Thanks
[Edited]
I am trying to do a simple hello world. But I get the error "system can not find path specified." I have screenshot that shows what the error looks like. It also is saying that my project is out of date when I clearly save the file before I build it. Apparently it can not find the executable file. I went to the debug fold and did not see any .exe file.
[Edited]
Ok, now When I try to build the project I get the following errors
1>------ Rebuild All started: Project: test, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'test', configuration 'Debug|Win32'
1>Compiling...
1>stdafx.cpp
1>Compiling...
1>test.cpp
1>c:\users\numerical25\desktop\test\test\test.cpp(1) : warning C4627: '#include <iostream>': skipped when looking for precompiled header use
1> Add directive to 'stdafx.h' or rebuild precompiled header
1>c:\users\numerical25\desktop\test\test\test.cpp(6) : error C2653: 'std' : is not a class or namespace name
1>c:\users\numerical25\desktop\test\test\test.cpp(6) : error C2065: 'cout' : undeclared identifier
1>Build log was saved at "file://c:\Users\numerical25\Desktop\test\test\Debug\BuildLog.htm"
1>test - 2 error(s), 1 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
Here is the code I used
#include <iostream>
#include "stdafx.h"
int main( )
{
std::cout << "Hello World\n";
return (0);
}
Note: I tried using it with and without the #include "stdafx.h" When I tried it without the #include "stdafx.h", it said I might be missing it.
| A minor point, which I don't see elsewhere in the answers: When using precompiled headers, such as your stdafx.h, you need to include them first. Change it to:
#include "stdafx.h"
#include <iostream>
and that should fix the errors about it.
Alternatively, it may be easier to simply switch off precompiled headers: Project > Properties > Configuration Properties > C/C++ > Precompiled Headers > Switch first option to "Not using precompiled headers". They can be useful for big projects but will just be awkward and annoying while you're learning, since they have extra rules (like this "must be included first") which aren't requirements of standard C++ .
|
2,304,989 | 2,305,005 | error: ‘traits’ is not a template - C++ | I am having a very weird issue with templates. Getting an error error: ‘traits’ is not a template. I couldn't reproduce the issue on a sample test project. But it happens on my project (which is bigger than I can post here).
Anyway, following are the files and usages I have. Anyone have any idea about when this error occurs?
I have the following in traits.hpp.
namespace silc
{
template<class U>
struct traits<U>
{
typedef const U& const_reference;
};
template<class U>
struct traits<U*>
{
typedef const U* const_reference;
};
}
This is used in another header file.
namespace silc {
template<typename T>
class node {
public:
typedef typename traits<T>::const_reference const_reference;
const_reference value() const {
/* ... */
}
}
}
| Syntax for template specialization is... not pleasant.
I believe your error can be fixed by replacing struct traits<U> by struct traits (but leave struct traits<U*> as-is!).
But look on the bright side! At least you aren't doing partial specialization over function types:
// Partial class specialization for
// function pointers of one parameter and any return type
template <typename T, typename RetVal>
class del_ptr<T, RetVal (*)(T*)> { ... };
// Partial class specialization for
// functions of one parameter and any return type
template <typename T, typename RetVal>
class del_ptr<T, RetVal(T*)> { ... };
// Partial class specialization for
// references to functions of one parameter and any return type
template <typename T, typename RetVal>
class del_ptr<T, RetVal(&)(T*)> { ... };
|
2,305,009 | 2,305,129 | How can I find the largest item in a linked list recursively given the head node? | int findLargest (ListNode *p)
// --------------------------------------------------------------------------
// Preconditions: list head pointer is passed as a parameter.
// Postconditions: returns the largest value in the linked list.
// --------------------------------------------------------------------------
{
if (p->item != NULL)
{
int largest = p->item;
if (largest > p->next->item)
...
}
...
}
Is it possible to write this recursive function passing only a pointer as a parameter? I can't figure out how to do this without adding more parameters. Any ideas? I am only using sequential search. Nothing fancy.
Here is the portion of class List that will be needed:
struct ListNode
{
ListItemType item; // A data item on the list.
ListNode *next; // Pointer to next node
}; // end ListNode
ListNode *head; // Pointer to linked list of items.
I am mainly worried about the feasibility of the problem. Can this be done with only a pointer as a parameter?
| This is definitely feasible, although I agree that recursion is not the best solution to solve this problem. In this case, non-recursive code would be easier to read (recursion), faster (overhead of function call), and more memory efficient (obviously more stack frames).
Each recursive call returns the greater of either it's value or the value from the rest of the list.
int findLargest (ListNode *p) {
int current = p->item;
int next;
if (p->next == NULL) {
//The value at this node is obviously larger than a non-existent value
return current;
} else {
//Recur to find the highest value from the rest of the LinkedList
next = findLargest(p->next);
}
//Return the highest value between this node and the end of the list
if (current > next) {
return current;
} else {
return next;
}
}
Recursion stops when the next item is null.
|
2,305,014 | 2,305,037 | What are Iterators, C++? | What are Iterators in C++?
| Iterators are a way of traversing a collection of objects. Typically, they allow you to access an STL (Standard Template Library) container sequentially in ways similar to accessing a classical C array with a pointer. To access an object through an iterator, you dereference it like a C pointer. To access the next object in a collection, you use the increment (++) operator. Some containers have multiple kinds of iterators that allow you to traverse the collection in different ways.
|
2,305,044 | 2,305,132 | A question about strftime | The question is simple "Say we have an integer 1 <= n <= 12,How to use strftime to display January for '1',February for '2',March for '3' and so on ... ?"
| #include <stdio.h>
#include <time.h>
size_t monthName( char* buf, size_t size, int month)
{
struct tm t = {0};
t.tm_mon = month - 1; // turn month 1..12 to 0..11 as `struct tm` wants
return strftime( buf, size, "%B", &t);
}
int main(int argc, char* argv[])
{
char buf[10];
monthName( buf, sizeof( buf), 9);
printf( "%s\n", buf);
return 0;
}
|
2,305,178 | 2,305,383 | Directx9 Index Buffers & Multiple Streams | Im trying to write up a 3DS Loader, which has an OpenGL rendering implementation for use in my generic rendering system.
The problem here is I have vertices indexed to one array, and texture coordinates indexed to another. I dont want to generate a new set of indexes and original vertices by checking each vertexes combination of coordinates and texture coordinates, so how do I specify the two arrays in buffers in directx optimally?
What I'd like is to have 3 vertex buffers, one for vertices, one for texture coordinates, and one for vertex normals. Then I would have index buffers for all three. I don't know how I would do this.
I'm working in directx9 and C++
| The thing is as far as the graphics card is concerned if 2 vertices have the same position and different tex coordinates (or different any vertex element) then they are different vertices. They will be stored on the card with the position/tex coord duplicated whatever you do under OpenGL (The driver will just expand the vertices implicitly). DirectX forces you to do this.
Multiple Streams are slightly different but expand to the same thing. ie you only have one index value into both streams.
So, optimally, you need to expand both lists into one big list and set up the, single list of, indices appropriately.
|
2,305,299 | 2,305,354 | Draw sound wave with possibility to zoom in/out | I'm writing a sound editor for my graduation. I'm using BASS to extract samples from MP3, WAV, OGG etc files and add DSP effects like echo, flanger etc. Simply speaching I made my framework that apply an effect from position1 to position2, cut/paste management.
Now my problem is that I want to create a control similar with this one from Cool Edit Pro that draw a wave form representation of the song and have the ability to zoom in/out select portions of the wave form etc. After a selection i can do something like:
TInterval EditZone = WaveForm->GetSelection();
where TInterval have this form:
struct TInterval
{
long Start;
long End;
}
I'm a beginner when it comes to sophisticated drawing so any hint on how to create a wave form representation of a song, using sample data returned by BASS, with ability to zoom in/out would be appreciated.
I'm writing my project in C++ but I can understand C#, Delphi code so if you want you can post snippets in last two languages as well :)
Thanx DrOptix
| By Zoom, I presume you mean horizontal zoom rather than vertical. The way audio editors do this is to scan the wavform breaking it up into time windows where each pixel in X represents some number of samples. It can be a fractional number, but you can get away with dis-allowing fractional zoom ratios without annoying the user too much. Once you zoom out a bit the max value is always a positive integer and the min value is always a negative integer.
for each pixel on the screen, you need to have to know the minimum sample value for that pixel and the maximum sample value. So you need a function that scans the waveform data in chunks and keeps track of the accumulated max and min for that chunk.
This is slow process, so professional audio editors keep a pre-calculated table of min and max values at some fixed zoom ratio. It might be at 512/1 or 1024/1. When you are drawing with a zoom ration of > 1024 samples/pixel, then you use the pre-calculated table. if you are below that ratio you get the data directly from the file. If you don't do this you will find that you drawing code gets to be too slow when you zoom out.
Its worthwhile to write code that handles all of the channels of the file in an single pass when doing this scanning, slowness here will make your whole program feel sluggish, it's the disk IO that matters here, the CPU has no trouble keeping up, so straightforward C++ code is fine for building the min/max tables, but you don't want to go through the file more than once and you want to do it sequentially.
Once you have the min/max tables, keep them around. You want to go back to the disk as little as possible and many of the reasons for wanting to repaint your window will not require you to rescan your min/max tables. The memory cost of holding on to them is not that high compared to the disk io cost of building them in the first place.
Then you draw the waveform by drawing a series of 1 pixel wide vertical lines between the max value and the min value for the time represented by that pixel. This should be quite fast if you are drawing from pre built min/max tables.
|
2,305,480 | 2,305,512 | Why can't I read and append with std::fstream on Mac OS X? | Consider the following C++ program, which takes a file and prints each line. It's a slice of a larger program where I later append to the file, based on what I see.
#include <fstream>
using std::fstream;
#include <iostream>
#include <string>
using std::string;
int main()
{
fstream file("file.txt", fstream::in | fstream::out | fstream::app);
string line;
while (std::getline(file, line))
std::cerr << line << std::endl;
return 0;
}
Now apply this version of file.txt (One word on the first line, followed by a newline):
Rain
On my machine (Snow Leopard), this prints out nothing. On closer inspection, the first call to getline fails. Strangely, it also fails if I add a second line: still nothing is printed!
Can anyone solve this mystery?
| When you say:
fstream file("file.txt", fstream::in | fstream::out | fstream::app);
you open the file in append mode - i.e. at the end. Just open it in read mode:
fstream file("file.txt", fstream::in );
or use an ifstream:
ifstream file("file.txt" );
And of course as Earwicker suggests, you should always test that the open succeeded.
If you are determined to open in append mode, you can move the read pointer explicitly:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
fstream file( "afile.txt", ios::in | ios::out | ios::app );
if ( ! file.is_open() ) {
cerr << "open failed" << endl;
return 1;
}
else {
file.seekg( 0, ios::beg ); // move read pointer
string line;
while( getline( file, line ) ) {
cout << line << endl;
}
}
}
Edit: It seems that the combination of flags used in the opening of the file leads to implementation specific behaviour. The above code works with g++ on Windows, but not with g++ on Linux.
|
2,305,652 | 2,305,712 | Pollard rho integer factorization | I am trying to implement Pollard Rho integer factorization in C/C++.Google gives me a Java implementation of the problem here.
I don't know Java that well,so what I came up with this.My implemenation in C++ works for most cases but not in few like the one "9999", I used there.
I am aware that C++ didn't have Biginteger class so I can't have the full functionality as it gives in JAVA but I want to factorize 15 digits numbers that's sufficient for unsigned long long
Please point out what wrong in my implementation.
| The problem's right here:
#define abs(x) (x>0)?(x):(-x)
You're missing some parentheses in your abs macro. Try:
#define abs(x) ((x)>0 ? (x) : -(x))
instead. (Consider what happens when abs(x-xx) is expanded in the case x-xx <= 0.)
Also, why does your gcd function return an int rather than a BigInteger?
You should also be aware that (assuming unsigned long long is a 64-bit integer type) this code won't work correctly for N larger than 2**32: if x (or xx) is greater than or equal to 2**32 then x*x will wrap modulo 2**64, giving you the wrong value for x*x % N.
|
2,305,767 | 2,305,850 | Converting sets of integers into ranges | What's the most idiomatic way to convert a set of integers into a set of ranges?
E.g. given the set {0, 1, 2, 3, 4, 7, 8, 9, 11} I want to get { {0,4}, {7,9}, {11,11} }.
Let's say we are converting from std::set<int> into std::vector<std::pair<int, int>>.
I treat Ranges as inclusive on both sides, since it's more convenient in my case, but I can work with open-ended ranges too if necessary.
I've written the following function, but I feel like reinventing the wheel.
Please tell maybe there's something in STL or boost for this.
typedef std::pair<int, int> Range;
void setToRanges(const std::set<int>& indices, std::vector<Range>& ranges)
{
Range r = std::make_pair(-INT_MAX, -INT_MAX);
BOOST_FOREACH(int i, indices)
{
if (i != r.second + 1)
{
if (r.second >= 0) ranges.push_back(r);
r.first = i;
}
r.second = i;
}
ranges.push_back(r);
}
| I don't think there's anything in the STL or Boost that does this.
One thing you can do is to make your algorithm a little bit more general:
template<class InputIterator, class OutputIterator>
void setToRanges(InputIterator first, InputIterator last, OutputIterator dest)
{
typedef std::iterator_traits<InputIterator>::value_type item_type;
typedef typename std::pair<item_type, item_type> pair_type;
pair_type r(-std::numeric_limits<item_type>::max(),
-std::numeric_limits<item_type>::max());
for(; first != last; ++first)
{
item_type i = *first;
if (i != r.second + 1)
{
if (r.second >= 0)
*dest = r;
r.first = i;
}
r.second = i;
}
*dest = r;
}
Usage:
std::set<int> set;
// insert items
typedef std::pair<int, int> Range;
std::vector<Range> ranges;
setToRanges(set.begin(), set.end(), std::back_inserter(ranges));
You should also consider using the term interval instead of range, because the latter in STL parlance means "any sequence of objects that can be accessed through iterators or pointers" (source).
Finally, you should probably take at look at the Boost Interval Arithmetic Library, which is currently under review for Boost inclusion.
|
2,305,777 | 2,305,784 | Constructor in class with inheritance | I'm having some problems with inheritance and constructors in C++. What I've got is a class VirtualMotor which inherits Motor (is that the correct way to say it?). The class VirtualMotor should have it's own constructor, but I'm doing something wrong when I create it and the compiler gives me an error (se below). My source code is like this:
Motor.h
class Motor
{
protected:
float speed;
float angle;
public:
Motor();
float getSpeed();
float getAngle();
virtual void setSpeed( float speed );
virtual void setAngle( float angle );
Motor.cpp
#include "Motor.h"
float Motor::getSpeed() { return speed; }
float Motor::getAngle() { return angle; }
VirtualMotor.h
#include "Motor.h"
class VirtualMotor: public Motor
{
private:
float lastSpeed;
public:
VirtualMotor();
void setSpeed(float speed);
void setAngle(float angle);
};
VirtualMotor.cpp
#include "VirtualMotor.h"
VirtualMotor::VirtualMotor()
{
speed = 2;
angle = 5;
}
void VirtualMotor::setSpeed(float speed)
{
this->speed = speed;
}
void VirtualMotor::setAngle(float angle)
{
this->angle = angle;
}
Main.cpp
#include <iostream>
#include "VirtualMotor.h"
using namespace std;
int main (int argc, char **argv)
{
VirtualMotor m;
cout << m.getSpeed() << endl;
m.setSpeed(9);
cout << m.getSpeed() << endl;
return 0;
}
To compile I use the command g++ Main.cpp Motor.cpp VirtualMotor.cpp -o main and I get the following error:
/tmp/ccIdYJaR.o: In function `VirtualMotor::VirtualMotor()':
VirtualMotor.cpp:(.text+0x29): undefined reference to `Motor::Motor()'
/tmp/ccIdYJaR.o: In function `VirtualMotor::VirtualMotor()':
VirtualMotor.cpp:(.text+0x5d): undefined reference to `Motor::Motor()'
/tmp/ccIdYJaR.o:(.rodata._ZTI12VirtualMotor[typeinfo for VirtualMotor]+0x8): undefined reference to `typeinfo for Motor'
collect2: ld returned 1 exit status
I feel there's a really simple solution to this, but I just can't see it. I've tried to use VirtualMotor::VirtualMotor() : Motor::Motor() and other variations without any luck.
| You've declared a default constructor for the class Motor in Motor.h (Motor(); immediately below public:), but you haven't given it a definition in Motor.cpp.
|
2,306,011 | 2,307,014 | Implementation of True Size display | I have an MFC application displaying images where I need to display the image in true-size i.e. the image should be rendered such that physical length of the object captured on the image should be same as the displayed length. For example, if I captured a object of 5 cm length the image should be displayed such that if I take a scale and measure its length on the monitor it should be 5 cm. I know the distance between the pixels in the image. But I need to display these images on different types of monitors. How do I get the physical distance between the pixels on the monitor? Any clues? Or is there any other way to implement it?
| The proper way would be calling GetDeviceCaps with LOGPIXELSX and LOGPIXELSY. For a screen device context, however, it is very likely that the value will simply be set to 96 (it is set by the user in a control panel). The function works fine for printer DCs.
|
2,306,307 | 2,306,385 | C++: How to access a class function inside another class? | I am learning how to work with std::vector and want to access its values and functions. I have a vector object inside another object called spectrum. Now when I try to determine the capacity of the vector using .capacity it works fine if I just declare the vector. But when I declare the vector inside another object, I get syntax errors.
The error:
test.c++:36: error: base operand of ‘->’ has non-pointer type ‘Spectrum’
As mentioned already below, -> should be a dot.
What I want is to determine the capacity of the container, and even though it now compiles it gives result 0 instead of the 8 I would expect.
The code:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
/* spectrum */
class Spectrum{
public:
float oct;
vector<float> band;
float total(){
int k;
float lpow;
// logarithmic summation
for(k = 0; k < oct; k++){
lpow = lpow + pow(10, band[k]);
}
return(10*log10(lpow));
}
Spectrum(int max_oct = 3){
oct = max_oct;
cout << "max oct = " << max_oct << endl;
vector<float> band(max_oct); //create vector/array with max_oct bands
cout << (int)band.capacity() << endl;
}
};
int main()
{
//does not work in a class
Spectrum input(8);
cout << (int)input->band.capacity() << endl;
//does work outside of a class
vector<float> band(8);
cout << (int)band.capacity() << endl;
}
| The line vector<float> band(max_oct); doesn't do what you think it does.
It defines an automatic variable called band in the scope of the Spectrum constructor. It doesn't touch the member variable also called band: in fact it "hides" it, so that any later references to band in the constructor refer to the automatic variable, not the member variable (which you could access with this->band).
What you want is:
Spectrum(int max_oct = 3) : oct(max_oct), band(max_oct) {
}
or (less good, because it constructs an empty vector and then resizes it, rather than constructing it the right size in the first place):
Spectrum(int max_oct = 3) {
oct = max_oct;
band.resize(max_oct);
}
By the way, I think you might be confusing the size and the capacity of vectors (not sure though from what you say). The single-arg constructor of vector creates a vector with the specified size. So if you don't already, you should expect the capacity to be 8 or more, rather than 8.
[Edit: in answer to your next question, you need to initialize lpow in total(): float lpow = 0;]
|
2,306,345 | 2,306,393 | function static binding in C++ | I am asking about the static binding of the function in C++. What's the data type conversion rules for the function binding.
Suppose we have
void func(int x);
void func(long x);
void func(float x);
void func(double x);
void func(char x);
and I have one function in main
func(1)
I know the function func(int x) will be called. I am curious about the rules of that.
Is it always the best match?
Does the order of declaration matter?
In any case the data type conversion will be applied?
What's the concern when the rules are designed?
|
Is it always the best match?
Yes: 1 is an int. If an appropriate overload exists, it will be taken since this minimizes the number of necessary implicit conversions (none).
Does the order of declaration matter?
No. However, it matters whether a function has been declared before the call is made. If the function is declared after the call, it will not be taken into consideration for overload resolution.
In any case the data type conversion will be applied?
There’s no conversion here because int is an exact match. Conversions only come into play when there’s no exact match available.
What's the concern when the rules are designed?
Well, it’s the only rule that makes sense, isn’t it?
|
2,306,350 | 2,306,371 | what will happen to inline functions inside virtual functions? | What will happen if I use a inline function inside a virtual function? I'm confused with questions like
http://www.parashift.com/c++-faq-lite/value-vs-ref-semantics.html#faq-31.6
I can understand it, but is that mean, it will non-sense to use (call) inline functions inside virtual functions (please assume that it is calling dynamically)?
class Wrapper
{
public:
inline void doInlineJob() {;}
};
class Base
{
virtual void foo()
{
//Do something
}
};
class Derived: public Base
{
void foo()
{
wrapObj.doInlineJob();
}
Wrapper wrapObj;
};
| It doesn't matter whether foo is virtual or not. It only matters whether doInlineJob is virtual. It's not, so it can be inlined without a problem.
|
2,306,432 | 2,306,635 | In Qt, how do I query the state of a QMutex or a QReadWriteLock? | I'm using a QReadWriteLock in my application to guard access to a resource object.
I'm using QReadLocks and QWriteLocks where I can, but sometimes I need a "long-lived" lock that crosses function boundaries. So sometimes I need to be able to query the state of the QReadWriteLock (or QMutex, same thing in this situation) because unlocking a mutex that is already unlocked is very bad.
For QMutex:
Unlocking a mutex that is not locked results in undefined behavior.
For QReadWriteLock:
Attempting to unlock a lock that is not locked is an error, and will result in program termination.
Being able to query the state of the mutex would also come in very handy for debug assertions to test that before starting some operation, I really do have that "long-lived" lock.
But all I really want is to be able to unlock a mutex if I have the lock, and not unlock it if I don't have it. That would make my day. IMO the unlock() function should already do this for me, but it doesn't.
Any way around this?
(and no, using Recursive mode does not help in this situation)
| Untested code,
But this should be possible to do, if Qt Doc is correct (though it's a little short about when tryLock() returns true/false)
QMutex m;
bool queryMutexState(){
//static QMutex lock; if you call this frequent, you may need this "protector"
lock.lock();
bool b(m.tryLock());
if (b)
m.unlock();
//lock.unlock()
return b;
}
Try to lock, if it fails, return false (=mutex is aquired somewhere else), if it is not locked, tryLock() will lock it, so unlock it again and return true (=mutex is availiable)
Note:
Another option would be a custom class with member QMutex and bool to indicate lock state. This may work better for you, as the mutex does not need to be locked and unlocked to get the state.
I suggest you go for method #2
|
2,306,538 | 2,306,557 | C++: How to make constructor for multidimensional vector? | I want to create two and three dimensional vectors using a constructor in a class. However, I do not know how for multidimensional vectors.
One dimensional works:
class One{
public:
vector < float > myvector;
One(int length) : myvector(length){}
};
Two dimensional does not work:
class Two{
public:
vector < vector < float > > myvector;
Two(int length, int width) : myvector(length)(width) {}
};
Three dimensional does not work either:
class Three{
public:
vector < vector < vector < float > > > myvector;
Three(int length, int width, int height) : myvector(length)(width)(height) {}
};
The answer below works for two dimensional vector. I would expect the following code for three dimensional however it seems to be wrong
class Three{
public:
vector < vector < vector < float > > > myvector;
Three(int length, int width, int height) : myvector(length, vector<float>(width, vector<float>(height))) {}
};
| For the twodimensional case, it should be:
Two(int length, int width) : myvector(length, std::vector<float>(width)) {}
I’ll let you figure out the third case yourself.
|
2,306,587 | 2,307,021 | "as if" in language standards | What is the exact meaning of the phrase "as if" in the standard and how does it work when a user can modify individual parts of the behavior.
The question is in regards to the C++ standard when talking about the nothrow version of operator new. 18.4.1.1/7 reads (my emphasis):
This nothrow version of operator new returns a pointer obtained as if acquired from the ordinary version.
My understanding is that "as if" does not require a specific implementation as long as the behavior is appropriate. So if operator new was implemented like this (I know this is not a compliant implementation as there is no loop or use of the new_handler; but I'm shortening that to focus on my issue):
// NOTE - not fully compliant - for illustration purposes only.
void *operator new(std::size_t s)
{
void *p = malloc(s);
if (p == 0)
throw std::bad_alloc();
return p;
}
Then it would be legal to write the nothrow version like this:
// NOTE - not fully compliant - for illustration purposes only.
void *operator new(std::size_t s, const std::nothrow_t &nt)
{
return malloc(s);
}
But let's say a program replaces operator new to use some other allocator. Does "as if" mean the compiler has to automatically change the behavior of the nothrow version to use this other allocator? Is the developer required to replace both the plain and nothrow versions?
| From 1.9 "Program execution:
conforming implementations are required to emulate (only) the observable behavior of the abstract machine
and in an informational footnote:
This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.
The standard does specifically note that the "as-if" requirement is binding on a replacement version of the nothrow version of operator new(). However, as I read it, that requirement would fall to the programmer overriding operator new() not the compiler. The flip side of this responsibility is that I think the standard pretty much requires the default implementation of the nothrow operator new() provided by the library must do something along the lines of calling the throwing new in a try/catch and return 0 if std::bad_alloc is caught.
Where the "as if rule" could come in to play here is if the compiler/linker/whatever were smart enough to figure out that when the default throwing new() was in being used, the default non-throwing new() could take the shortcut, but if the default throwing new() was overridden, the default non-throwing new() would have to act differently. I'm sure this is technically possible for an implementation (even if you probably can't express it in standard C++). I'd be surprised if there was ever an implementation that did this.
I might be reading too much into the requirement, but I think that's what can be inferred.
|
2,306,645 | 2,306,705 | Using boost::optional with constant types - C++ | I have a container class which uses boost::optional to hold the value. Here is the code looks like,
template<typename T>
struct traits
{
typedef T value_type;
typedef T& reference;
};
template<typename T>
struct traits<const T>
{
typedef const T value_type;
typedef const T& reference;
};
template<typename T>
struct traits<T*>
{
typedef T* value_type;
typedef T* reference;
};
template<typename T>
struct traits<const T*>
{
typedef const T* value_type;
typedef const T* reference;
};
template<typename T>
class container
{
public:
typedef typename traits<T>::reference reference;
typedef typename traits<T>::value_type value_type;
container() {}
void set(reference value) {
op.reset(value);
}
reference get() const {
return boost::get(op);
}
private:
boost::optional<value_type> op;
};
int main()
{
foo f;
container<const foo> c;
c.set(f);
return 0;
}
It works well for other types except const. I am getting error when I use const types (const foo* works fine).
Is boost::optional supports constant types? If no, how can I work around this issue?
Is there a ready made traits implementation available which I can use rather than defining my own traits?
Any help would be great!
| The problem is not with boost::optional, but with the logic of what you're trying to do. First you create a container of const, and then you try to modify what's contained. I would be surprised if that worked.
I think you should probably do what standard containers (like vector) do and forbid non-copyable template arguments.
Otherwise you'll have to live with the fact that your set method won't work when T is non-copyable, and provide a constructor that performs the initialization:
class container
{
public:
container(reference init_value) : op(init_value) {}
};
int main()
{
foo f;
container<const foo> c(f); // OK
// c.set(f); NO
return 0;
}
|
2,306,972 | 2,307,038 | Is there any way to decompile Linux .so? | Is there any way to decompile Linux .so?
| There are decompilers, but a decompiler might not emit code in the same language that the original program was written in.
There are also disassemblers, which will reassemble the machine code into assembly.
The Decompilation Wiki may be a good source of additional information.
|
2,307,062 | 2,307,416 | Drag and Drop like Winspector Spy | I was wondering if anybody could give insight on how to implement the window selector in Winspector Spy. Basically, I would want to provide a panel that I could mouse down on, drag over to another processes window (or sub window) and get something like the HWND out of it. Ideally, I would do this in C#, but if it's only possible by wrapping the C APIs, then I can just do it in C++.
I messed around with the DragDrop event and calling DoDragDrop on mouse down in C#, but wasn't really sure if that could give me what I want. Will it be easier to just get the global X/Y pos of the mouse and find the topmost window at that location? Is there an API which does that automagically for me given x, y parameters?
EDIT: Just discovered WindowFromPoint for the latter question
| You don't normally get mouse messages when the mouse isn't over your window. But you need to in order to do drag and drop operations. So, Windows provides a mechanism called mouse capture. To prevent mouse capture from being abused, you can only capture the mouse on a button down message. Once you have capture, you get mouse move messages no matter where the mouse is on screen until you release capture or when Windows sees the corresponding button up message.
The C++ code for this looks something like this
case WM_LBUTTONDOWN:
{
SetCapture(hwnd);
}
break;
case WM_MOUSEMOVE:
if (GetCapture() == hwnd)
{
POINT pt = {GET_MOUSE_X(lParam), GET_MOUSE_Y(lParam));
ClientToScreen(hwnd, &pt);
HWND hwndAtPoint = WindowFromPoint(pt);
// Show info for hwndAtPoint....
}
break;
case WM_LBUTTONUP:
if (GetCapture() == hwnd)
{
ReleaseCapture();
}
break;
case WM_CANCELMODE:
// this is a request from Windows that leave my modal state
if (GetCapture() == hwnd)
ReleaseCapture(hwnd);
break;
case WM_CAPTURECHANGED:
// notification that I lost capture (I released it or it was taken from me)
break;
The GetAncestor function can be helpful to go from the window at the point, to the top level window that own it. GetWindow can be used to walk around the window tree.
In .NET, the Control class has a Capture property that does the same thing see
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.capture.aspx
|
2,307,146 | 2,307,215 | Stack Overflow Error With This Recursive Program? - C++ | I'm a programming student in my first C++ class, and recently we were given an assignment to implement a recursive program that finds the first occurrence of a given substring in a given string.
For example:
int StringIndex("Mississippi", "sip"); // this would return 6
The hint we are given is to use a recursive helper function that takes the index as a parameter.
Here is what I've done so far:
int index_of(string s, string t)
{
int index = 0;
if (s[index] == NULL)
return -1;
else if (starts_with(s, t, ++index))
{
return index;
}
return index_of(s, t);
}
bool starts_with(string s, string t, int index)
{
if (t[index] != s[index] || s[index] == NULL)
return false;
return starts_with(s, t, ++index);
}
I am getting a stack overflow error, and I don't understand why. So would somebody mind helping me understand why I'm getting this error? And help me get pointed in the right direction as to how to fix it?
| When writing recursive functions you should always keep two things in mind: you need stop conditions which end the recursion and you have to get closer to a stop condition with each function call. If you fail to check stop conditions or if your function doesn't get closer to a stop condition during each call, you'll run into stack overflows (or infinite loops).
The problem in your first function is that it doesn't get closer to the stop condition. At the end you "return index_of(s, t)" without modifying s or t in the meantime. So the function will start over with the same parameters, again and again until you run into a stack overflow.
Another problem is in your starts_with function. It only returns false but never true.
|
2,307,251 | 2,307,265 | How can I concisely initialize a safe collection in C++? |
Possible Duplicate:
C++: Easiest way to initialize an STL vector with hardcoded elements
I'm learning C++ right now, and I'm looking for a way to quickly and easily initialize a "safe" collection (like a vector) with different values for each element. I'm accustomed to Python's concise list/tuple initializations, and I want to know if there's an equivalent syntax trick or collection type in C++.
For example, if I want to initialize a list of unique Payment objects in Python, I can do this:
payments = [Payment(10, 2), Payment(20, 4), Payment(30, 6)]
However, in order to initialize a vector of Payment structures in C++, I need to write something like this:
Payment tempPayments[] = {
{10, 2},
{20, 4},
{30, 6}
};
vector<Payment> examplePayments(tempPayments, tempPayments +
sizeof(tempPayments) / sizeof(Payment));
Is there an easier way to initialize a vector with unique structures, or another safe collection that's more convenient?
| Look into Boost.Assign, particularly list_of. It allows you to initialize a collection using code such as:
const vector<int> primes = list_of(2)(3)(5)(7)(11);
|
2,307,395 | 2,307,413 | How to print string C++ mfc | I created project using VS2008 wizard SDI > CView
How can i print some text from Cstring to my main window CView
for example in dialog window with list box i use smth like this m_ListBox1.AddString((LPCTSTR)s);
| To print it in the view (without any controls or anything like that), you can use something like pDC->Textout() or pDC->DrawText() inside your view class' OnDraw() function. Note that by default the pDC parameter has its name commented out -- you'll need to un-comment it before you can use it.
|
2,307,460 | 2,307,526 | Reading variable length user input in C++ | How do I read in a variable number of characters? The user can input a positive or negative number that is too big to be stored in an integer. I am then checking to make sure the char is a number and storing it in an array of ints (although that will probably be changed to a short since I only need to be able to store 0-9).
istream& operator>>(istream &in, LargeInt &l)
{
char x;
do
{
cin >> x;
int v = (int)x;
switch( v )
{
case 48: v = 0;
case 49: v = 1;
case 50: v = 2;
case 51: v = 3;
case 52: v = 4;
case 53: v = 5;
case 54: v = 6;
case 55: v = 7;
case 56: v = 8;
case 57: v = 9;
default: v=10 /* END INPUT */;
}
l.largeInt[ l.usedLength ] = v;
l.usedLength++;
//need to check array length and make bigger if needed
}
while( (x == 45) || ((x > 47) && (x < 57)) );
}
| If you wish to read digits, you need to do it a character at a time. E.g.
char ch;
while (std::cin.get(ch) && ch >= '0' && ch <= '9') {
// You have a digit to process (maybe you want to push_back it into a vector)
}
Notice that you need to use ch - '0' to get the value of the digit because ch contains the character code rather than the value. In ASCII this means that '0' is in fact 48, '1' is 49 and so on (and 'A' is 65). The values may be different for different character encodings but the digits are guaranteed by the standard to be sequential, so that subtracting zero works.
|
2,307,534 | 2,307,580 | Enable AntiAliasing in Direct3D9 (MultiSample Render Target) | I am trying to enable AA in a D3D9 application, but am not sure how to set up the surfaces correctly. So far, I have:
IDirect3DDevice9* m_pd3dDevice;
IDirect3DSurface9* screen;
IDirect3DSurface9* msaasurf;
D3DPRESENT_PARAMETERS m_presentationParameters;
Initialization:
m_presentationParameters.Windowed = TRUE;
m_presentationParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
m_presentationParameters.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES;
m_presentationParameters.MultiSampleQuality = 0;
m_presentationParameters.BackBufferFormat = D3DFMT_UNKNOWN;
m_presentationParameters.EnableAutoDepthStencil = TRUE;
m_presentationParameters.AutoDepthStencilFormat = D3DFMT_D16;
m_presentationParameters.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
// create d3d device
m_pD3D->CreateDevice(
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&m_presentationParameters, &m_pd3dDevice
)
// save screen surface
m_pd3dDevice->GetRenderTarget(0, &screen);
D3DSURFACE_DESC desc;
screen->GetDesc(&desc);
// Create multisample render target
m_pd3dDevice->CreateRenderTarget(
800, 600,
D3DFMT_A8R8G8B8,
desc.MultiSampleType, desc.MultiSampleQuality,
false,
&msaasurf,
NULL
);
And then, for each frame:
// render to multisample surface
m_pd3dDevice->SetRenderTarget(0, msaasurf);
m_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 0, 0, 0 ), 1.0f, 0 );
m_pd3dDevice->BeginScene();
// render stuff here
m_pd3dDevice->EndScene();
m_pd3dDevice->SetRenderTarget(0, screen);
// get back buffer
IDirect3DSurface9* backBuffer = NULL;
m_pd3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);
// copy rendertarget to backbuffer
m_pd3dDevice->StretchRect(msaasurf, NULL, backBuffer, NULL, D3DTEXF_NONE);
backBuffer->Release();
// Present the backbuffer contents to the display
m_pd3dDevice->Present(NULL, NULL, NULL, NULL);
However, nothing is appearing on my screen (all black). No errors are occuring (I check the return value of all d3d calls). What am I doing wrong?
| You don't need the extra surface, you can render directly to the multisampled backbuffer. For me, the only reason to use StretchRect() like this is to get a non-multisampled copy of the scene for use with postprocessing (because multisampled render targets are bad textures, so you need the scene data in a resolved texture). If you want to do this, you don't need to specify multisampling for the backbuffer. A multisampled render target to render the scene to is sufficient then.
|
2,307,621 | 2,330,194 | Does getting random SIGTRAP signals (in MinGW-gdb) is a sign of memory corruption? | I wrote my own reference counted memory manager c++ (for fun) and I'm sure it isn't perfect ;) . And now when I'm trying to use it I got random SIGTRAP signals. If I comment out every line which are in connection with that memory manager everything runs fine. Getting SIGTRAP-s instead of SIGSEGV is quite strange.
I know that SIGTRAP-s are thrown when the program hits a breakpoint, but no breakpoint is set. I read in an other thread that debug builds of the exe's and dll's must be up to date. They are up to date and so it is not the reason.
Does anyone know why is this happening?
| After searching on Google I realized that those sigtraps are same as those warnings you get in MSVC++ saying "Windows has triggered a breakpoint in xxxx.exe. This may be due to a corruption of the heap, and indicates a bug blahblahblah"...
So it seems yes, unexpected sigtraps can indicate memory corrupction (quite strange...)
And I found my bug too. The MM is in a static library which is linked to a dll. And that static lib and the dll is linked to my exe. So there were two memory managers, one in my exe and one in my dll. If call the initaialization method of the MM. It initialized the MM in my exe but not in the dll so the dll went without init. I solved this by not linking my exe against that static library.
|
2,307,780 | 2,307,864 | C++ Beginner's question on input/output text files.? | If I have an input text with the only thing written of "A" and I want a series of code that will allow me to generate the next ASCII set (B), how would I do so?
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
#include iostream>
#include fstream>
#include iomanip>
#include string>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
string firstName;
string lastName;
string character;
int age;
double rectangle, length, width, area, parameter, circle, radius, areaCircle, circumference, beginningBalance, interestRate, endBalance;
inFile.open("inData.txt");
outFile.open("outData.txt");
outFile << fixed << showpoint;
outFile << setprecision(2);
cout << "Data is processing..." << endl;
inFile >> length >> width;
area = length * width;
parameter = (length * 2) + (width *2);
outFile << "Rectangle:" << endl;
outFile << "Length = " << length << " " << "width = " << width << " " << "area = " << area << " " << "parameter = " << parameter << endl;
inFile >> radius;
outFile << " " << endl;
outFile << "Cricle:" <<endl;
areaCircle = 3.14159 * (radius * radius);
circumference = 2 * (3.14159 * radius);
outFile << "Radius = " << radius << " " << "area = " << areaCircle << " " << "circumference = " << circumference;
outFile << endl;
outFile << endl;
inFile >> firstName >> lastName >> age;
outFile << "Name: " << firstName << " " << lastName << "," << " " << "age: " << age;
outFile << endl;
inFile >> beginningBalance >> interestRate;
outFile << "Beginning balance = " << beginningBalance << "," << " " << "interest rate = " << interestRate << endl;
endBalance = ((18500 * .0350) / 12.0 ) + 18500;
outFile << "Balance at the end of the month = $" << endBalance;
outFile << endl;
inFile >> character;
outFile << "The character that comes after" << character << "in the ASCII set is" << character +1;
inFile.close();
outFile.close();
return 0;
}
| Instead of declaring character as a string, declare it as a char. string refers to std::string, a high-level object for storing multiple characters. char is a low-level native type which stores exactly 1 character.
char character;
infile >> character;
outfile << "next after " << character << " is " << char(character+1) << endl;
input of Z or besides letters notwithstanding.
|
2,307,815 | 2,308,001 | Segmentation Fault when outputting in C++ | I am trying to print out an array of integers. I am getting a seg fault when I try to print as below. If I uncomment the "In for loop" it will print everything except the last item of the array and it still has a seg fault. When I uncomment both of the comments (or just the "done with for loop") everything prints fine. Why does this happen and how do I fix it?
for( int i = 0; i < l.usedLength; i++ )
{
//cout << "**********In for loop" << endl;
cout << l.largeInt[ i ];
}
//cout << "**********done with for loop" << endl;
Here is the whole class:
#include "LargeInt.h"
#include <ctype.h>
LargeInt::LargeInt()
{
usedLength = 0;
totalLength = 50;
largeInt = new int[totalLength];
for( int i=0; i<totalLength; i++ )
{
largeInt[i] = 0;
}
}
LargeInt LargeInt::operator+(const LargeInt &l) const
{}
LargeInt LargeInt::operator-(const LargeInt &l) const
{}
LargeInt LargeInt::operator*(const LargeInt &l) const
{}
LargeInt LargeInt::operator/(const LargeInt &l) const
{}
bool LargeInt::operator==(const LargeInt &l) const
{}
ostream& operator<<(ostream &out, const LargeInt &l)
{
cout << "In output" << endl;
if( l.usedLength == 0 )
{
cout << 0;
}
else
{
cout << "In else... NON 0" << endl;
for( int i = 0; i < l.usedLength; i++ )
{
cout << "In for loop" << endl;
cout << l.largeInt[ i ];
}
//cout << "done with for loop" << endl;
}
//cout << "after the if.... all done with output" << endl;
}
istream& operator>>(istream &in, LargeInt &l)
{
char x;
while (std::cin.get(x) && x >= '0' && x <= '9')
{
l.largeInt[ l.usedLength ] = x-48;
l.usedLength++;
//need to check array length and make bigger if needed
}
}
Main:
#include <stdlib.h>
#include <iostream>
#include "LargeInt.h"
int main(int argc, char** argv) {
cout << "\nJosh Curren's Assignment #5 - Large Integer\n" << endl;
LargeInt lint;
cout << "Enter a large int: ";
cin >> lint;
cout << "\nYou entered: " << endl;
cout << lint << endl;
cout << endl;
return (EXIT_SUCCESS);
}
| You forgot the last line in ostream& operator<<(ostream &out, const LargeInt &l):
return out;
With this line it works perfectly.
|
2,307,884 | 2,307,889 | C++ Linker Error involving operator overload function | I have a List of type Node. I want to set a temporary Node equal to the Node at the front of the List, as follows:
class Node
{
public:
Node();
Node& operator = (const Node& n);
};
but I keep getting a Linker Error:
Linking...
main.obj : error LNK2019: unresolved external symbol "public: class Node & __thiscall Node::operator=(class Node const &)" (??4Node@@QAEAAV0@ABV0@@Z) referenced in function "void __cdecl fillScan(int,class std::list >)" (?fillScan@@YAXHV?$list@VNode@@V?$allocator@VNode@@@std@@@std@@@Z)
C:\Users\Aaron McKellar\Documents\School Stuff\CS445\Test\Debug\Test.exe : fatal error LNK1120: 1 unresolved externals
Thanks in advance!
| You only showed the declaration of operator=, not the definition. Either you didn't supply a definition or the linker can't find it.
Well, I should say: The linker definitely can't find the definition for operator=. Either that's because you forgot to supply one or because your project/Makefile is set up incorrectly.
|
2,307,895 | 2,307,914 | Force initialization of singleton in c++ before main() | I am using singletons as follows:
// Foo.hpp
class Foo {
static Foo* instance() {
static Foo* foo = new Foo();
return foo;
}
}
Now, my singleton is initialized the first time Foo::instance() is called. I want to make sure this is before main executes (my code is multi threaded, I want all singletons initialized before pThreads are created).
Question is:
Is there anything I can put in Foo.hpp to make the above happen? (I don't want a generic Globals.hpp taht initializes all singletons; I'd also prefer to not have to touch Foo.cpp).
Thanks!
| Your usage of singletons indicates interdependencies between them. Is that the case? Also, you shouldn't allocate it on the heap; it will never be be destroyed.
class Foo {
static Foo& instance() {
static Foo foo; // no pointer needed
return foo;
}
};
Anyway, the answer you ask for is to add such a dependency:
class InitStons {
InitStons() {
Foo::instance();
}
} master_initialize;
But this is really not good practice, and you should just initialize things at the beginning of main().
|
2,307,933 | 2,307,995 | C++ struct alignment and STL vectors | I have a legacy data structure that's 672 bytes long. These structs are stored in a file, sequentially, and I need to read them in.
While I can read them in one-by-one, it would be nice to do this:
// I know in advance how many structs to read in
vector<MyStruct> bunchOfStructs;
bunchOfStructs.resize(numberOfStructs);
ifstream ifs;
ifs.open("file.dat");
if (ifs) {
ifs.read(&bunchOfStructs[0], sizeof(MyStruct) * numberOfStructs);
}
This works, but I think it only works because the data structure size happens to be evenly divisible by my compiler's struct alignment padding. I suspect it'll break on another compiler or platform.
The alternative would be to use a for loop to read in each struct one-at-a-time.
The question --> When do I have to be concerned about data alignment? Does dynamically allocated memory in a vector use padding or does STL guarantee that the elements are contiguous?
| The standard requires you to be able to create an array of a struct type. When you do so, the array is required to be contiguous. That means, whatever size is allocated for the struct, it has to be one that allows you to create an array of them. To ensure that, the compiler can allocate extra space inside the structure, but cannot require any extra space between the structs.
The space for the data in a vector is (normally) allocated with ::operator new (via an Allocator class), and ::operator new is required to allocate space that's properly aligned to store any type.
You could supply your own Allocator and/or overload ::operator new -- but if you do, your version is still required to meet the same requirements, so it won't change anything in this respect.
In other words, exactly what you want is required to work as long as the data in the file was created in essentially the same way you're trying to read it back in. If it was created on another machine or with a different compiler (or even the same compiler with different flags) you have a fair number of potential problems -- you might get differences in endianness, padding in the struct, and so on.
Edit: Given that you don't know whether the structs have been written out in the format expected by the compiler, you not only need to read the structs one at a time -- you really need to read the items in the structs one at a time, then put each into a temporary struct, and finally add that filled-in struct to your collection.
Fortunately, you can overload operator>> to automate most of this. It doesn't improve speed (for example), but it can keep your code cleaner:
struct whatever {
int x, y, z;
char stuff[672-3*sizeof(int)];
friend std::istream &operator>>(std::istream &is, whatever &w) {
is >> w.x >> w.y >> w.z;
return is.read(w.stuff, sizeof(w.stuff);
}
};
int main(int argc, char **argv) {
std::vector<whatever> data;
assert(argc>1);
std::ifstream infile(argv[1]);
std::copy(std::istream_iterator<whatever>(infile),
std::istream_iterator<whatever>(),
std::back_inserter(data));
return 0;
}
|
2,307,965 | 2,307,989 | LibGD library is not working: crash when saving image | I've been seeking for JPG saving library for long time for c++, but i cant seem to get anything to work. Now i am trying use LibGD:
What im doing wrong ? It seems to work, but the saving crashes. Code:
...
#pragma comment(lib, "bgd.lib")
#include <gd/gd.h>
...
void save_test(){
gdImagePtr im;
FILE *jpegout;
int black;
int white;
im = gdImageCreateTrueColor(64, 64);
black = gdImageColorAllocate(im, 0, 0, 0);
white = gdImageColorAllocate(im, 255, 255, 255);
gdImageLine(im, 0, 0, 63, 63, white);
if(jpegout = fopen("test.jpg", "wb")){
if(im){
gdImageJpeg(im, jpegout, -1); // crash here!
}
fclose(jpegout);
}
gdImageDestroy(im);
}
I downloaded the library from: http://www.libgd.org/releases/gd-latest-win32.zip
I have the library / include / bgd.dll files in correct directories etc.
Edit: Answer below includes this code that fixed my problem:
int size;
char* data = (char*)gdImagePngPtr(im, &size);
fwrite(data, sizeof(char), size, out);
gdFree(data);
| Check im and jpegout before you try and use them to make sure they were both allocated.
[Edit] It would be better to split assigning the file handle from the test for it's validity. Have you tried the libgd example?
[Edit2] I downloaded the same source etc, set up a project in VS2008 and get the exact same problem. You could try this suggestion..
one important thing about GD is to make sure it's built against the same CRT as the main project because it uses such structures as FILE and if you call GD DLL built with one version of the compiler from an executable built with another version, you will run into memory access violations.
There's a code snippet in there which fixes the crash on my machine:
/* Bring in gd library functions */
#include "gd.h"
/* Bring in standard I/O so we can output the PNG to a file */
#include <stdio.h>
int main() {
/* Declare the image */
gdImagePtr im;
/* Declare output files */
FILE *pngout, *jpegout;
/* Declare color indexes */
int black;
int white;
/* Allocate the image: 64 pixels across by 64 pixels tall */
im = gdImageCreate(64, 64);
/* Allocate the color black (red, green and blue all minimum).
Since this is the first color in a new image, it will
be the background color. */
black = gdImageColorAllocate(im, 0, 0, 0);
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);
/* Draw a line from the upper left to the lower right,
using white color index. */
gdImageLine(im, 0, 0, 63, 63, white);
/* Open a file for writing. "wb" means "write binary", important
under MSDOS, harmless under Unix. */
errno_t result1 = fopen_s(&pngout, "C:\\Projects\\Experiments\\LibGD\\test.png", "wb");
/* Do the same for a JPEG-format file. */
errno_t result2 = fopen_s(&jpegout, "C:\\Projects\\Experiments\\LibGD\\test.jpg", "wb+");
/* Output the image to the disk file in PNG format. */
int size;
char* data = (char*)gdImagePngPtr(im, &size);
fwrite(data, sizeof(char), size, pngout);
gdFree(data);
data = (char*)gdImageJpegPtr(im, &size, -1);
fwrite(data, sizeof(char), size, jpegout);
gdFree(data);
/* Close the files. */
fclose(pngout);
fclose(jpegout);
/* Destroy the image in memory. */
gdImageDestroy(im);
}
|
2,308,026 | 2,308,177 | Which has been the most reliable, fastest Windows C++ profiler that you have used? | I need to profile a real time C++ app on Windows. Most of the available profilers are either terribly expensive, total overkill, or both. I don't need any .NET stuff. Since it is a real time app, I need the profiler to be as fast as possible. It would be excellent if it integrated in some way with Visual Studio 2005/2008, but that's not necessary. If this description reminds you of a profiler that you have used, I would really like to know about it. I am hoping to draw from people's use of C++ profilers on Windows to pinpoint one that will do the job. Thanks.
| When I have to profile realtime code, I think the only solution is something hand-rolled. You don't want too much coverage or you end up slowing the code down, but with a small data set, you need to be very focused, essentially picking each point by hand.
So I wrote a header file several years ago that defines some macros and a mechanism for capturing data, either as function timings or as a timeline (at time T in function X). The code uses QueryPerformanceCounter for the timings and writes the data into named shared memory via CreateFileMapping so that I can look at the timing data from another process live.
It takes a recompile to change what timing information I want to capture, but the code is so inexpensive that It has virtually no effect on the code.
All of the code is in the header file, (with macro guards so the code only gets included once). so the header file itself is my 'profiler'. I change some tables in the header, then and markup the target code, recompile and start profiling.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.