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 |
|---|---|---|---|---|
3,089,047 | 3,089,139 | stating jmp_buf as pointer | I'm tring to define jmp_buf as pointer and using it in nested longjmp(s).as follow:
...
jmp_buf *bfj;
...
and then writing if else:
if( setjmp(*bfj) == 0){
DS[SP-2].int_val=(int)bfj;;
//to store the bfj
}else {}
and somewhere else using the stored bfj to longjmp
bfj = (jmp_buf *)DS[TOP].int_val;
longjmp(*bfj,1);
... | From your code, you are not actually allocating memory for your jmp_buf. There are a couple of things you can do:
Dynamically allocate your jmp_buf with new and you will want to delete it when you are done with it
Put the jmp_buf on the stack jmp_buf bfj; and when you want it's pointer, you would take it's address wi... |
3,089,174 | 3,089,227 | ld doesn't recognize object file | I'm having problems with compiling a project I'm working on. Everything else works just fine, but when I compile, I get this error message:
/usr/bin/ld:obj/content/xmSound.o: file format not recognized; treating as linker script
I have no idea why this happens. It's probably some error in the code, but I don't know.
T... | Run 'file obj/content/xmSound.o' and compare what it says for that file with some other object file that the loader does not complain about.
The chances are that the rule for building that object file is incorrect, somehow, and the file you have is not an object file at all.
|
3,089,278 | 3,089,283 | Is there a C++ equivalent to Java's Collection interface for STL container classes? | I would like to pass arbitrary container as an argument of function and iterate over it (no erasing nor pushing elements). Unfortunately it looks like there is no standard way of doing this.
First solution which comes to my mind is an interface (let's call it CollectionInterface) implemented by classes that will wrap ... | ForwardIterator? This is a type of InputIterator (or OutputIterator) that also allows multi-pass algorithms (incrementing it does not invalidate prior values).
Iterators (which are quite different from Java iterators) are the central thread unifying C++ collections. For examples of algorithms working on them (and ass... |
3,089,302 | 3,089,318 | How to order a string[] in c++ | The input is string[] like below.
"CSE111: CSE110 MATH101"
"CSE110:"
I need to order the strings based on some logic. For example my output should be a string[] like
"CSE110","MATH122","CSE111"
My question is
While scanning through the input array, if one string is picked to be the first string of the output array... | I hopefully got it now: For a string of the form A: B C D, the course A has B, C, and D as prerequisites.
In that case you want a mapping from a course to its prerequisites, e.g.:
typedef std::set<std::string> CourseSet;
typedef std::map<std::string, CourseSet> Prerequisites;
Now you can fill a Prerequisites by tokeni... |
3,089,454 | 3,089,709 | "Selected" style for WinAPI toolbar button? | Is there a way to make a toolbar button look different than the rest (Aside from changing bitmap or setting its state to Disable? Is there away to make it look highlighted all the time? I want the selected tool to look selected. Thanks (Sort of like the way open applications are "Selected" in Windows 7.
| Send the TB_SETHOTITEM message
|
3,089,602 | 3,089,627 | Is there a thread safe queue class for Visual Studio C++ 6.0? | I would like to implement a thread safe queue in VS 6.0
Is there a good class to use for this? This is an MFC application using the CWinApp.
My former post lead me to here but I don't have the luxury to code in VS 2010, stuck in 6.0 land.
o well.....
Thank You.
| Obviously you accepted the wrong answer to that question! :-) The code I linked in my answer will work fine with VC++ 6.
|
3,089,744 | 3,089,754 | Accessing a nonmember function of a derived class from a base class | I'm trying to call a nonmember function of a derived class from a base class, but getting this error:
error: no matching function for call to 'generate_vectorlist(const char&)'
Here's the relevant code snippets from the base class:
//Element.cpp
#include "Vector.h"
...
string outfile;
cin >> outfile;
const char*... | You're dereferencing the pointer so you're passing a const char, not a const char*.
try this:
generate_vectorlist(outfile_name);
|
3,089,840 | 3,089,852 | C Preprocessor and if-else condition statement | I run my C code in vs2010 (win32 console application). It was compiled as C++ application.
#include "stdafx.h"
#define YES 1;
#define NO 0;
// function to determine if an integer is even
int isEven(int number)
{
int answer;
if ( number % 2 == 0)
answer = YES;
else
answer ... | The compile error is due to the semicolons on your #define statements. Remove them.
#define is a preprocessor macro, not c syntax. It doesn't need a semicolon. The preprocessor does straight substitution on YES and NO, which makes:
if ( number % 2 == 0)
answer = YES;
else
answer = NO;
Turn into:
if ( number... |
3,089,891 | 3,089,911 | Create a IM program (like MSN or Gtalk ) using C++ | My question is that create a IM software like MSN or Gtalk, to have the basic function using C++.
You can use any technology and libary to do that.
Can someone give me a suggestion?
I add that this not my homework. This
is my job question.
Because I am a fresh man in my
company.
So, they give me some questions to ... | My suggestion from experience with doing this sort of thing before is to find a library that implements Jabber also known as XMPP (Google Talk) for you. That way all you have to do is create the user interface. If you are working with Windows, MSDN has some great tutorials for creating user interfaces in C++. If yo... |
3,089,897 | 3,090,102 | setw : Alignment for UTF-8 text file | all the while, I am using setw for my ANSI text file alignment. Recently, I want to support UTF-8 in my text file. I found out that setw no longer work.
#include <windows.h>
#include <iostream>
// For StringCchLengthW.
#include <Strsafe.h>
#include <fstream>
#include <iomanip>
#include <string>
#include <cassert>
std:... | Even in a "monospaced" font, some East Asian characters are wider than others. You also have to consider combining characters, which have no width of their own.
There's a wcswidth function that may do what you want.
|
3,089,921 | 3,089,946 | C++ iterator in for loop pitfalls? | I see somewhere it mentions:
for ( itr = files.begin(); itr < files.end(); ++itr ) // WRONG
for ( itr = files.begin(); itr != files.end(); ++itr ) // ok
Why is the first expression wrong? I always used the first expression, and didn't have any problems.
| Ordering comparisons such as <, >, <=, >= will work for random-access iterators, but many other iterators (such as bidirectional iterators on linked lists) only support equality testing (== and !=). By using != you can later replace the container without needing to change as much code, and this is especially important... |
3,089,927 | 3,089,941 | How to retrieve an integer value from a character? | How can I convert a character into an integer value? For example, I've been trying to read "A" as 1, "B" as 2, and so forth. I tried comparing the character to each letter in the alphabet and return the appropriate value.
int intvalue(char letter)
{
if(letter == "A")
return 1;
else if(letter == "B")
return 2;
e... | You need to use character literals, not string literals, e.g.,
if (letter == 'A')
^ note the single quotes
That said, if you are willing to assume you are running on a system using the ASCII character set, you can simply use arithmetic:
int charIndex = (letter - 'A') + 1;
In the ASCII character set, let... |
3,090,038 | 3,090,047 | Memory comparison, which is faster? | I have a 3D vector class. The private variables are defined:
union {
struct {
double x;
double y;
double z;
};
double data[3];
};
In implementing operator==, which is faster?
return this->x == v.x && this->y == v.y && this->z == v.z;
OR
return memcmp(this->data, v.data) == 0;
| Unfortunately the two aren't equivalent. (Specifically NaNs and signed zeros don't use bitwise comparison inside the FPU).
So you should make your choice based on correctness, not speed.
|
3,090,080 | 3,090,092 | Need some help in serialization | I am trying to write a program to serialize a linked list to a file without using any libraries. My problem is how to add or remove nodes to the serialized structure since I dont have next pointer ? Also how can I avoid fragmentation ?
| If your linked list doesn't have loops, then the fact that this is a "linked list" is a memory detail, not a serialization detail. Just write the node values out into the file and build the next pointers when you deserialize.
However, if your linked list does have loops, then you'll need something smarter. You'll nee... |
3,090,268 | 3,090,308 | how much memory is required for metadata when using new int[10]? | When array is created using 'new' and deleted using 'delete' operator, delete knows the size of array. As mentioned in other SO threads, this size information is stored in metadata.
My question: what exactly is stored in metadata and how much space is needed for that? Is it only the size which is stored in metadata?
| According to C++ Standard 5.3.4/12:
new T[5] results in a call of operator new[](sizeof(T)*5+x),
<...>where x is a non-negative unspecified values representing array allocation overhead. <...> The amount
of overhead may vary from one invocation of new to another.
|
3,090,270 | 3,096,215 | How to use a phoenix expression with boost::transform_iterator? | <Update> As usual for me, the question was a wrong one. The actual question is: why doesn't transform_iterator use the conventional result_of<> metafunction to determine the return type, instead of accessing UnaryFunc::result_type directly. Posted an answer with a work around. </Update>
Specifically, is there a way ... | It looks like this is fixed in the boost trunk (see line 51, result_of<> instead of an indirect UnaryFunc::result_type). So this shouldn't be an issue in 1.44 and above.
Here's a workaround for boost < 1.44. The transform_iterator instantiation accesses UnaryFunc::result_type only if the Reference template parameter i... |
3,090,457 | 3,094,268 | Extending legacy C++ Windows app with WinForms | I'm working on an legacy C++ application that runs on rugged business mobile devices made by Intermec. I need to add some functionality and would like to build it using WinForms. The idea is that users would click a button in the old app which would launch a WinForms screen. Then they do some stuff, click OK and are re... | First let's be clear that the compact framework is not the full framework and therefore a lot of things that will work on the desktop are not going to work for you.
You really only have one option, though there are a lot of different ways to use the one option. Since teh Compact Framework does not support EE Hosting (... |
3,090,473 | 3,090,640 | StdAfx + Header file - Order of inclusion in MFC application | I am using Visual Studio 2005. I created an MFC based console application named "StdAfx dependancy". The IDE created the following files for me.
Resource.h
StdAfx Dependancy.h
stdafx.h
StdAfx Dependancy.cpp
stdafx.cpp
I added another class CHelper with Helper.h and Helper.cpp as below.
Helper.h:
#pragma once
class C... | This link must give you some clue.
Purpose of stdafx.h
The lines defined before the
#include "stdafx.h" are ignored by the compiler. So if you want to actually include those files then you need to include them after the #include "stdafx.h".
Hope it is clear.
|
3,090,694 | 3,090,760 | Duplication in Drive letters | i get device insertion and removal notification from WM_DEVICECHANGE
i get the dbcc_name from the DBT_DEVTYP_DEVICEINTERFACE
i get the corresponding drive letter from the DBT_DEVTYP_VOLUME
if i insert the device one by one it works correctly
but if i insert two device at a time i get duplication in drive letters
how c... | The DEV_BROADCAST_VOLUME docs mention this piece of info:
Although the dbcv_unitmask member may specify more than one volume in any message, this does not guarantee that only one message is generated for a specified event. Multiple system components may independently generate messages for logical volumes at the same t... |
3,090,725 | 3,090,744 | How to extract audio/video file duration? | I need to find the duration of numerous formats of audio and video files, in milliseconds. I've been searching around for a while, but I can't find anything that will let me do this. I'm using C/++ in Linux. Thanks in advance.
| There is a MediaInfo SourceFourge project that shows this info. You can look in its code for that.
|
3,090,748 | 3,091,462 | Displaying current language layout in traybar | Basically I want to write an application which would display the current language as a tray icon. Mainly I can code C++ and C#. Guess Google would help me out but I would like to ask it here first, since the community, the knowledge here is something I trust.
(Never wrangled with such parts of the system so far. So t... | To get the user's overall UI language, GetUserDefaultUILanguage.
To get the current thread's language, GetThreadUILanguage or GetThreadLocale.
To get the current keyboard input language, GetKeyboardLayout.
To display a notification area icon in Windows prior to Windows 7, Shell_NotifyIcon. In Windows 7 Shell_NotifyIcon... |
3,090,968 | 3,091,032 | Best practices and tools for debugging differences between Debug and Release builds? | I've seen posts talk about what might cause differences between Debug and Release builds, but I don't think anybody has addressed from a development standpoint what is the most efficient way to solve the problem.
The first thing I do when a bug appears in the Release build but not in Debug is I run my program through v... | The very existence of two configurations is a problem from debugging point of view. Proper engineering would be such that the system on the ground and in the air behave the same way, and achieve this by reducing the number of ways by which the system can tell the difference.
Debug and Release builds differ in 3 aspects... |
3,091,152 | 3,091,414 | looking for a MemoryStream in C++ | In the wonderful world of C# i can create a memory stream without specifying its size,
write into it and then just take the underlying buffer.
How can i do the same in c++? basicly i need to do:
memory_stream ms(GROW_AS_MUCH_AS_YOU_LIKE);
ms << someLargeObjects << someSmallObjects << someObjectsWhosSizeIDontKnow;
un... | #include <sstream>
std::ostringstream buffer; // no growth specification necessary
buffer << "a char buffer" << customObject << someOtherObject;
std::string contents = buffer.str();
size_t bufferSize = contents.size();
rawNetworkSocket.Send(contents); // you can take the size in Send
Using this approach you will h... |
3,091,185 | 3,091,253 | Do without USES_CONVERSION macro | I have this code that uses the USE_CONVERSION macro in a C++ project...
I was wondering if this is written well, (not written by me), and if there's any better ways to do it, without the USES_CONVERSION and W2A macros.
STDMETHODIMP CInterpreter::GetStringVar(BSTR bstrNamespace, BSTR bstrVar, BSTR *pbstrValue)
{
USES_CO... | There is the class-based ATL::CA2W and friends (in atlconv.h, I believe) that don't put the string on the stack and don't use macros. You don't need a USES_CONVERSION in the function:
throw x::internal_error(ATL::CA2W(pszErrStr));
Also, since your arguments are BSTR (wchar_t *), you don't need to convert them to _bstr_... |
3,091,186 | 3,091,220 | Qt - How to get the "Temp" dir for an arbitrary user? | For each OS there is a location for storing temporary data. It could be like: C:/Users/[user name]/AppData/Temp (or so). How can I get this path independently from OS with QT?
| It is not possible to get the temp directory for an arbitrary user, but for the current user you can use QDir::temp() or QDir::tempPath().
|
3,091,300 | 3,091,932 | MessageBox with timeout OR Closing a MessageBox from another thread | If my application crashes, I use an ExceptionFilter to catch the crash, perform some final actions, then show a message box to the user that the application has crashed.
Because the application already crashed, there's not much I can (or I dare) to do, because if I do too much, the executed code might access corrupted ... | I noticed that if the main thread simply exits the application while the other thread still has the ::MessageBox open, that the MessageBox is being adopted by a process called CSRSS. This solves my problem, since this only requires a time-out on the Event in the main thread (WaitForSingleObject with timeout).
However,... |
3,091,301 | 3,091,441 | How to get file path from NTFS index number? | I have dwVolumeSerialNumber, nFileIndexHigh, nFileIndexLow values obtained from a call to GetFileInformationByHandle. How can I get file path from these values?
| Because of hard links, there may be multiple paths that map to the given VolumeSerialNumber and FileIndex. To find all such paths:
Iterate volumes to find one whose root directory matches dwVolumeSerialNumber
Recursively enumerate all directories on the volume, skipping symbolic links and reparse points, to find all ... |
3,091,318 | 3,091,740 | Custom interactive shell | I've run into the following problem: My console utility should be running as a process (hope it's the right term) so every command goes to it directly. Like gnuplot, interactive shells (irb, etc.).
This shows what I'm talking about:
Mikulas-Dites-Mac-2:Web rullaf$ command
Mikulas-Dites-Mac-2:Web rullaf$ irb
>> command
... | You have to parse the input yourself. Depending on the complexity of the input, this might be accomplished by some simple string matching for trivial cases. A very simple example:
#include <iostream>
#include <string>
int main()
{
std::string input;
for(;;)
{
std::cout << ">>";
std::cin >> input;
if(... |
3,091,400 | 3,091,884 | iPhone CoreAudio hang when stopping | I have an iPhone app that is recording audio and then broadcasting it across the network. In response to a "stop" from the far end it queues a notification to stop the recording. Alas when it gets to the AudioQueueStop call the application just hangs (ie Stop never exits). Thanks to the notification all AudioQueue m... | How do you call AudioQueueStop ? The function supports two modes: synchronous and asynchronous.
The preferred way is to use the asynchronous stopping as the function will return immediately, while the remaining buffers will be played/recorded.
If you want to go synchronous and you get a hang, then maybe there is a dead... |
3,091,484 | 3,091,498 | Exception in two line Xerces program | The following code gives me an exception on the XMLFormatTarget line, but if I change the string from "C:/test.xml" to "test.xml" it works fine.
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/framewor... | It could be that you don't have sufficient permissions to write to C:\. In such a case, Xerces might report the error throwing an exception.
An Access Denied exception is typically what we could expect if you try to write to a system directory without administrator credentials.
Maybe it has also something to do with t... |
3,091,718 | 3,091,781 | Base 256 GUID String Representation w/Character Offset 0x01F | I need to make a string representation of a 128bit GUID that represents 8bit chunks instead of 4bit; so like base 256 :/ Why? Because I need to shorten the length of the string hex representation of the GUID, it is too long. I have a max array size of 31 plus NULL terminator. Also the character value cannot be from... | Try base64 encoding : it packs 6-bits per character and is still portable. You will need 22 chars to store 128 bits GUID in a portable way.
|
3,091,833 | 3,091,871 | Calling member functions from a constructor | I know this question has a similar title to this: C++: calling member functions within constructor? but I am asking a more general question.
Is it good practice to call member functions from within a constructor? It makes reading the code easier and I prefer the encapsulation type way of doing it (ie. each block of cod... | I don't think there is anything inherently wrong in calling member functions from a constructor provided that they are not virtual functions.
The problem with calling virtual member functions from a constructor is that a subclass can override the function. This will cause the constructor to call the overridden implemen... |
3,092,198 | 3,092,217 | C++, preventing class instance from being created on the stack (during compiltaion) | I know there are methods to prevent a class from being created on the heap, by preventing the user from using the new and delete operator. I am trying to do just the opposite. I have a class that I want to prevent the user from creating an instance of it on the stack, and that only instances instigated using the new op... | When myclass reaches the end of its scope (the next }) the compiler calls the destructor to free it from the stack. If the destructor is private, however, then the destructor cannot be accessed, so the class cannot be placed on the stack.
I don't like the look of delete this. In general I think objects should not des... |
3,092,280 | 3,115,666 | Does any MOF implementation exist in C++? | Is there any alternative to JMI for C++? Thanks for the links or suggestions.
| EMF4CPP has just now been published. It is basically an implementation of Ecore in C++ (and Ecore is basically an adaptation of the Essential MOF OMG standard). Hope it helps
|
3,092,444 | 3,092,544 | keeping private parts outside c++ headers: pure virtual base class vs pimpl | I recently switched back from Java and Ruby to C++, and much to my surprise I have to recompile files that use the public interface when I change the method signature of a private method, because also the private parts are in the .h file.
I quickly came up with a solution that is, I guess, typical for a Java programmer... | I can think of a few differences:
With the virtual base class you break some of the semantics people expect from well-behaved C++ classes:
I would expect (or require, even) the class to be instantiated on the stack, like this:
BananaTree myTree("somename");
otherwise, I lose RAII, and I have to manually start tracking... |
3,092,475 | 3,092,538 | C++ mixins via templates: why doesn't this work? | I've got a interface that's implemented as an abstract base class with a number of pure virtual public methods. These pure virtual functions can be implemented using a template since the differences between subclasses aren't large - so my idea was to use multiple inheritance to mix-in the appropriately templated helpe... | It doesn't work because AverageHelper<>::Average() doesn't override TrivialList::Average(). In order to override a virtual function, the overriding class must inherit from the class containing the function to be overridden.
You could change your template thus:
template<typename TIndexable, typename Base >
class Aver... |
3,092,483 | 3,092,537 | C++: Strange behaviour of `new` | SDL provides me this struct:
typedef struct SDL_Rect {
Sint16 x, y;
Uint16 w, h;
} SDL_Rect;
I want to create a new SDL_Rect on the heap as class variable:
// Forward declaration
private:
SDL_Rect *m_pcScreenRect;
And in the constructor I do this:
/* Screen Rectangle (for clearing) */
m_pcScreenRect = new... | In order to make use of the "default value for an int", you can use value initialization:
m_pcScreenRect = new SDL_Rect(); // this will initialize to zeros
Otherwise, the values are not defined.
To give more details: adding a constructor to this structure would be the best approach, but since it's in a third-party lib... |
3,092,549 | 3,094,533 | What free tiniest flash file system could you advice for embedded system? | I've got DSP tms320vc5509a and NOR flash AT26DF321 on the board and I'm going to store named data on the flash. I don't need directory hierarchy, wear leveling (I hope system will write to flash very few times), but CRC is strongly needed.
Thank you
| You could look at the ELM-Petit FAT File System Module for an good small file system implementation. Not sure that it has CRC but you can add that to your low-level hardware drivers.
|
3,092,550 | 3,328,321 | C++ Keywords not Colored in Emacs | I have been using emacs for a while for mainly python programming, and have started C++ coding with it. When I open a c++ file, it opens without problems with c++-mode. The background and foreground colors are normal for the theme I have with color-theme, but keywords and strings are not colored differently. Below is t... | I finally got syntax highlighting by removing a folder called site-lisp from the folder d:/emacs. My Emacs installation is in d:/emacs/emacs-23.1, and somehow it was reading from these files. So, removing this folder forced Emacs to use the correct ones, I think.
|
3,092,697 | 3,093,034 | c++ boost compilation catastrophe | I'm writing a DLL plugin for a windows application,
after adding the following includes:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
I get a wonderful compilation error:
Error 3 error C2143: syntax error : missing ';' before '__cdecl' c:\program files (x86)\microsoft visual st... | someone who isn't really smart added this :
#define __declspec(dllexport) __stdcall APIENTRY
to one of the API .h files your including
|
3,092,740 | 3,092,783 | Makefile for compiling a number of .cpp and .h into a lib | I am running Windows 7 with gcc/g++ under Cygwin. What would be the Makefile format (and extension, I think it's .mk?) for compiling a set of .cpp (C++ source) and .h (header) files into a static library (.dll). Say I have a variable set of files:
file1.cpp
file1.h
file2.cpp
file2.h
file3.cpp
file3.h
....
What woul... | The extension would be none at all, and the file is called Makefile (or makefile) if you want GNU Make to find it automatically.
GNU Make, at least, lets you rely on certain automatic variables that alone give you control over much of the building process with C/C++ files as input. These variables include CC, CPP, CFLA... |
3,092,763 | 3,095,792 | Is a pointer to a virtual member function valid in the constructor of the base class? | My question is not about calling a virtual member function from a base class constructor, but whether the pointer to a virtual member function is valid in the base class constructor.
Given the following
class A
{
void (A::*m_pMember)();
public:
A() :
m_pMember(&A::vmember)
{
}
virtual void... | The pointer is valid, however you have to keep in mind that when a virtual function is invoked through a pointer it is always resolved in accordance with the dynamic type of the object used on the left-hand side. This means that when you invoke a virtual function from the constructor, it doesn't matter whether you invo... |
3,092,856 | 3,092,882 | How to ensure that randomly generated numbers are not being repeated? |
Possible Duplicates:
Unique (non-repeating) random numbers in O(1)?
How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N
I want to generate random number in a certain diapason, and I must be sure, that each new number is not a duplicate of formers. One solution is to stor... | Is there a range for the random numbers? If you have a limit for random numbers and you keep generating unique random numbers, then you'll end up with a list of all numbers from x..y in random order, where x-y is the valid range of your random numbers. If this is the case, you might improve speed greatly by simply gene... |
3,092,928 | 3,092,948 | How to reuse enum operator overloads in C++? | I have several flag-like enumerations, in C++. For example:
enum some_state {
state_normal = 1 << 0,
state_special = 1 << 1,
state_somethingelse = 1 << 2,
state_none = 0,
};
some_state var1;
Now on using bit operators like & or |, I get compiler errors. I know I can overload operator | et... | I tried and searched, and I think the best solution is a #define. Based on something I found:
#define FLAGS(T) \
inline T operator |(const T s, const T e) { return (T)((unsigned)s | e); } \
inline T &operator |=(T &s, const T e) { return s = s | e; } \
inline T operator &(const T s, const T e) { ret... |
3,093,049 | 3,093,082 | Different behavior of compilers with array allocation | I recently found a interesting behaviour of g++ when compared with MSVC++ 2008. Consider this tiny program:
#include <cstdlib>
const int ARR_LENGTH = 512;
void doSomething( int iLen );
int main( int argc, char** argv )
{
doSomething( ARR_LENGTH );
return 0;
}
void doSomething( int iLen )
{
int iTest[iLe... | C99 (the most recent version of the C standard) does allow dynamically sized arrays.
However, the feature is not supported by Visual Studio (which only implements C89 support)
In C++ it is not, and probably will never be, valid.
|
3,093,116 | 3,093,142 | How do I pass an array as a parameter? | This is driving me crazy:
I have function
void gst_init(int *argc, char **argv[]);
in the gstreamer api and I want to call it with some parameters I define, like:
int argc = 2;
char* argv[2] = {"myvalue1", "myvalue2"};
gst_init(&argc, &argv);
This code doesn't compile (I get error C2664):
error C2664: 'gst_init' : c... | Try
int argc = 2;
char* arg1[1] = {"myvalue1"};
char* arg2[1] = {"myvalue2"};
char** argv[2] = { arg1, arg2 };
gst_init(&argc, argv);
char **argv[] is an array of char**, which is analogous to an array of char* arrays.
OTOH what you tried to pass as parameter is shown as char *(*)[2]: a pointer to an array of char*.
|
3,093,164 | 3,109,269 | Polygon to Polygon Collision Detection Issue | I have been having a few issues implementing my narrow phase collision detection. Broadphase is working perfectly.
I have a group of polygons, that have a stl::vector array of points for their vertices in clockwise order. Every cycle, I check to see whether they're colliding.
I have borrowed the following Point in Po... | Thanks for your help guys! But i've managed to sort it out on my own.
The importance of translating your vertices to world space and rotating them should not be overlooked, especially if you're colliding them.
|
3,093,451 | 3,093,470 | Is it safe to pass a vector as an array? | Say I have a function:
void someFunc(int *x,int count);
which is out of my control, so I can't write it to accept iterators.
Is it safe to call it like so (regardless of the specific STL implementation):
vector<int> v;
/* ... */
someFunc(&v[0],v.size());
Obviously, one counter example is vector<bool>. How about any o... | From section 23.2.4, point 1 of the standard:
[...] The elements of a vector are stored contiguously,
meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
So yes, it is safe.
Note: If v is empty v[0] is undefined behavior so you... |
3,093,535 | 3,094,174 | How to debug a buffer overrun in Visual C++ 9? | I have a huge MMC snapin written in Visual C++ 9. Every once in a while when I hit F5 in MMC mmc.exe crashes. If I attach a debugger to it I see the following message:
A buffer overrun has occurred in mmc.exe which has corrupted the program's internal state. Press Break to debug the program or Continue to terminate th... | I assume you aren't able to reproduce this reliably.
I've successfully used Rational Purify to hunt down a variety of memory problems in the past, but it costs $ and I'm not sure how it would interact with MMC.
Unless there's some sort of built-in memory debugger you may have to try solving this programmatically. Are y... |
3,093,568 | 3,093,608 | unfamiliar with struct/class declaration with template | while going through some of the mili source code I came across a struct declared like this:
template <class T, class Pre, class Pos>
struct PrePosCaller<T*, Pre, Pos>
(from here)
The part I'm unfamiliar with is <T*, Pre, Pos>. I understand what the code does and its purpose in this context but I would like to know whe... | That is a template specialization. In particular a partial specialization.
Somewhere in the code there is a template declared as:
template <class T, class Pre, class Pos>
struct PrePosCaller { //...
};
or something similar. Then they are providing an specialization of that template for the cases where the first argume... |
3,093,632 | 3,094,774 | Why must C/C++ string literal declarations be single-line? | Is there any particular reason that multi-line string literals such as the following are not permitted in C++?
string script =
"
Some
Formatted
String Literal
";
I know that multi-line string literals may be created by putting a backslash before each newline.
I am writing a programming language (similar to C... | One has to consider that C was not written to be an "Applications" programming language but a systems programming language. It would not be inaccurate to say it was designed expressly to rewrite Unix. With that in mind, there was no EMACS or VIM and your user interfaces were serial terminals. Multiline string declar... |
3,093,929 | 3,093,958 | Doesn't C++ IDE Netbeans or Eclipse support class inheritance? | I am using NetBeans IDE 6.8 to create C++ project. While I use class inheritance, however, it seems to me that it does not recognize the derived class. Here is what I have:
class A
{
public:
A(vector<double> a, double b) {...}
};
class B : public A
{
public:
additionalfunction(...) {...}
};
main()
{
vecto... | I'd suggest implementing the constructor in class B.
|
3,093,959 | 3,094,023 | Stream extraction within if/else | Assuming the stream extraction won't fail, will this
if( !(stream >> token) )
throw runtime_error( "Unexpected end of recipe." );
else if( token == "something" )
// do something
else
throw runtime_error( "Unknown token" );
Work like this
if( !(stream >> token) )
throw std::runtime_error( "Unexpected en... | Yes, the logic is exactly the same.
And I wouldn't ever call exit() - at least in your code the exception can be caught by some other code instead of just killing the app. You never know if you will use this code inside a larger application sometime in the future so it's better to keep your options open ;)
|
3,094,219 | 3,094,575 | How can I return a copy of a vector containing elements not in a set? | Suppose I have the following two data structures:
std::vector<int> all_items;
std::set<int> bad_items;
The all_items vector contains all known items and the bad_items vector contains a list of bad items. These two data structures are populated entirely independent of one another.
What's the proper way to write a metho... | Since your function is going to return a vector, you will have to make a new vector (i.e. copy elements) in any case. In which case, std::remove_copy_if is fine, but you should use it correctly:
#include <iostream>
#include <vector>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
std::vect... |
3,094,467 | 3,094,543 | Performance Profiling with Visual Studio | How can I get Visual Studio to help me optimize my application, or tell me areas of slowness? Thanks
| As another suggestion, I have found the AMD CodeAnalyst a great companion. It integrates with VS2010 very well, and provides detailed breakdown of CPU time on a line-to-line basis. You can zoom in and out to see from a top-level to a function-level. Not to mention it even has in-line disassembly display if you need tha... |
3,094,573 | 3,094,860 | extern "C" DLL: Debug is OK, Release throws Error C2059 | I've got a DLL that I've created as a C++ Win32 application. To prevent name mangling in my DLL, I have used the EXPORT definition defined below:
#ifndef EXPORT
#define EXPORT extern "C" __declspec(dllexport)
#endif
EXPORT int _stdcall SteadyFor(double Par[], double Inlet[], double Outlet[]);
To get this code to comp... | If your source file has a .c extension, the compiler you are using will compile it as C (not C++) and produce that error on the extern "C". If that is the case, then you need to use the /TP switch as you already noted or rename the file to .cpp. The other solution is to put #ifdefs around the extern:
#ifdef __cplusplu... |
3,094,758 | 3,095,031 | MessageBox does not work in a catch of an exception | Well I have 2 issues but my main concern right now is my catch exception. Here is the code...
int GXRenderManager::Ignite(HINSTANCE * hinst, int * nCmd, GXDEVICE DeviceType, int width, int height)
{
try
{
GXRenderManager::hinstance = hinst;
GXRenderManager::nCmdShow = nCmd;
GXRenderManager::height = height;
... | If a dialog is present, MessageBox should always be passed a handle to it, rather than 0. Only pass MessageBox 0 if no dialog is available.
Side note, I don't understand the exact reason for this, so it would be great if someone else could give insight.
It's also possible that your message box is being attached to your... |
3,094,875 | 3,179,220 | What's the standard way of trapping system messages in Qt4? | I've been looking for a way to trap and retrieve system messages in Qt4, specifically the WM_DEVICECHANGE messages among others. I know how to in C# but can find any conclusive text on how to in Qt4.
Thanks in advance..
| Look into implementing the winEvent() method, say, in your MainWindow subclass.
#include "Windows.h"
#include "Dbt.h"
bool MainWindow::winEvent(MSG *message, long *result)
{
if (message->message==WM_DEVICECHANGE)
{
ui->plainTextEdit->appendPlainText("WM_DEVICECHANGE message received");
if (mess... |
3,094,917 | 3,095,043 | How does sizeof work? How can I write my own? | I know C++ and know the function sizeof itself but I need to write my own sizeof function so please explain how it works exactly? What does it do with the parameter?
| You haven't provided any meaningful details about what it is you want to do, so it is hard to figure out what you need.
You can "wrap" sizeof by you own template function like
template <typename T> size_t my_sizeof() {
return sizeof(T);
}
and then use it as
size_t s = my_sizeof<int>();
From time to time one can com... |
3,094,972 | 3,094,995 | When should I use do-while instead of while loops? |
Possible Duplicates:
Is there ever a need for a “do {…} while ( )” loop?
Do your loops test at the top or bottom?
While vs. Do While
When is a do-while appropriate?
I've been having a philosophical debate with a colleague as to whether as a general rule, in C/C++ we should should use while loops rather than do-wile ... | Use while loops when you want to test a condition before the first iteration of the loop.
Use do-while loops when you want to test a condition after running the first iteration of the loop.
For example, if you find yourself doing something like either of these snippets:
func();
while (condition) {
func();
}
//or:
... |
3,094,977 | 3,095,028 | How to use Enum with strings in a function? | Basically, I have a Linked List which implements a display()function that simply loops throught he elements and prints out their values.
I wanted to do it like this:
void List::display( std::string type )
{
switch(type)
{
// Do stuff...
The compiler immediately complained. My teacher said this would be b... | Switch, in current C++, only works with integral types. You could define your enum, switch on it, and write an auxiliary function that maps the enum to string values if needed.
Example
enum E { A, B };
string E_to_string( E e )
{
switch(e)
{
case A: return "apple";
case B: return "banana";
}
}
void disp... |
3,095,000 | 3,095,208 | How to monitor/show progress during a C++ sort | I'm planning to write an interactive C++ geometry processing plug-in that will frequently sort large amounts of data. Although preliminary indications are that the sort will take only a second or two, I'd prefer to show progress during that time - i.e I'd like to update a progress indicator a few times per second. Th... | Since std::sort is template based, the source should be available in a header. You can make a copy of it and insert your progress callback. The big problem will be predicting how close you are to completion - most sort functions will be based on Quicksort, which doesn't always do the same number of comparisons.
Writing... |
3,095,062 | 3,096,580 | How to add a QAction to specific position in a QToolBar | QToolBar::insertWidget allows to add a QWidget after a specific QAction.
Is there any way to add a QAction at a specific position?
Removing all actions and then re-adding them again after is my last hope !
| You can use the insertAction() method, inherited from QWidget, to insert your QAction before a given QAction.
|
3,095,549 | 3,095,620 | min and perfect forwarding | The min algorithm is normally expressed like this:
template <typename T>
const T& min(const T& x, const T& y)
{
return y < x ? y : x;
}
However, this does not allow constructs of the form min(a, b) = 0. You can achieve that with an additional overload:
template <typename T>
T& min(T& x, T& y)
{
return y < x ? ... | It looks to me like you're trying to oversimplify the problem. Unfortunately, getting it entirely correct is decidedly non-trivial. If you haven't read N2199, now would be a good time to do so. Rvalue references continue to evolve, so its reference implementation of min and max probably isn't exactly right anymore, but... |
3,095,658 | 3,095,947 | I have some circularities in my template class definitions | I have a matrix class that takes the row and column reference type that can be used to access it as template parameters. Meanwhile, the row and column types are passed the matrix type that they are representing.
Is there any way to break this circularity? Here are some demonstrative code snippets:
#include "MatrixCon... | If I am understanding your question correctly, you are trying to define Matrix as a template taking a row type and a column type, and then the rowType (and i assume also columnType) as templates of a matrix type. My big question is: where is the actual data? At some point, I presume this Matrix should actually break do... |
3,095,856 | 3,098,480 | preventing unaligned data on the heap | I am building a class hierarchy that uses SSE intrinsics functions and thus some of the members of the class need to be 16-byte aligned. For stack instances I can use __declspec(align(#)), like so:
typedef __declspec(align(16)) float Vector[4];
class MyClass{
...
private:
Vector v;
};
Now, since __declspec(align(#)) i... | If you're set against heap allocation, another idea is to over allocate on the stack and manually align (manual alignment is discussed in this SO post). The idea is to allocate byte data (unsigned char) with a size guaranteed to contain an aligned region of the necessary size (+15), then find the aligned position by r... |
3,096,042 | 3,096,245 | Check if string contains a range of numbers | I'd like to test a std::string for containing numbers of any range e.g 5 to 35 in a std::string s = "XDGHYH20YFYFFY" would there be function or I would have to convert a number to string and then use a loop to find each one?
| I'd probably use a locale that treated everything except digits as white-space, and read the numbers from a stringstream imbued with that locale and check if they're in range:
#include <iostream>
#include <algorithm>
#include <locale>
#include <vector>
#include <sstream>
struct digits_only: std::ctype<char>
{
dig... |
3,096,262 | 3,096,341 | Social networking APIs and C/C++ | Folks,
Note sure if this is the best place to ask this one, but I doubt there'd be a better place. I see that github, stackoverflow, facebook, twitter, linkedin etc. have been providing developer API to slice and dice user information. Couple of questions on the general nature of these API:
1) Are these open-source?
... |
An API is a specification, not code, to "open-source" doesn't really apply though each might have licensing restrictions on how you use their API that might affect how suitable they were to your code being open-source.
The language will be dictated (or suggested) primarily based on what you're doing with the data, not... |
3,096,453 | 3,096,556 | Options for granting access to class data members (C++) | This is a basic question about what options are available for defining the scope of some parameters. I'd particularly like to have a sense of the tradeoffs in speed, memory, code clarity, ease of implementation, and code safety. My programming experience is clearly modest, and I have little formal training. I suspect o... | This is normal:
class Simulation
{
public:
// typedef's should be used liberally, it's easier to read
typedef double pmf_type[NUM_SOCIODEM_FILES][INIT_NUM_AGE_CATS];
typedef double sero_type[NUM_EPID_FILES][INIT_NUM_STYPES];
// accessors
const pmf_type& get_pmf(void) const
{
return dem... |
3,096,617 | 3,096,634 | Usage of this pointer | I have a question relating to the usage of "this".
Suppose I have two classes A & B; their rough outline is as follows:
class A
{
public:
...
void AddB( B* b )
{
// inserts B into the vector v
}
private:
std::vector<B*> v;
};
class B
{
public:
...
void foo( void )
{
...
// ... | No, there's nothing wrong with that, as long as you are careful about ownership and deletion.
|
3,096,642 | 3,097,179 | LINK : fatal error LNK1104: cannot open file '..\json_spirit\Debug\json_spirit_lib.lib' | Can someone point me in the right direction? I'm not a C++ or VS developer but I'm trying to compile a project and I'm getting the above error. I don't have any clue why the compiler is looking for that file or what the Debug folder is about (though I could guess). Can somebody explain the issue in other words for m... | This page http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx speaks of two methods to link with the Json spirit library from c++.
I imagine your problem is that one or more of the header files includes a #pragma to automatically link certain libraries, the compiler can't find one of these libraries, namely json_spi... |
3,096,671 | 3,096,712 | OSX, static variable sharing same address | In OSX I have the following code. Using gcc 4.0.1. I'm new to OSX development so I'm not sure what other system information would be useful here...
static int textstrArgs[] = { 1, 1, 1 };
void func()
{
static int first = 1;
if (first)
{
first = 0;
// stuff
}
/* other stuff */
}
... | Just a hunch - try changing:
static int textstrArgs[] = { 1, 1, 1 };
to
static int textstrArgs[3] = { 1, 1, 1 };
One other thing - are you actually referencing textstrArgs anywhere ? If not then it may be that it's getting optimised away.
|
3,096,758 | 3,097,542 | How should I profile visual c++ express? | I've read a lot of the posts here giving profiling advice but I need to ask this.
From what I can tell, Visual C++ Express doesn't generate a debugging file that is used by profiler programs. I tried AMD Codeanalyst and it seemed to work fine except none of the routines in my program were identified -- just a lot of "u... | First, the polar angular velocity of the car should be proportional to the speed of the car and to the angular position of the steering wheel (to a first approximation).
Second, there's hardly a professor or blogger or book author who will tell you this, but if you want to see what the code is doing and optimize it, th... |
3,096,813 | 3,096,839 | C++ Builder onResize event after exit | I wrote some program in C++ Builder 6 (don't ask me why).
I do some actions with on-form components after formResize event occurs.
But it occurs right after I close my program, and looks like all components on form where deleted, so I've got exception and everything crashes.
There is my code:
void __fastcall TForm3::Fo... | You could check to make sure the objects haven't been deleted:
void __fastcall TForm3::FormResize(TObject *Sender)
{
if (Image1) {
Image1->Picture->Graphic->Width = Image1->Width;
Image1->Picture->Graphic->Height = Image1->Height;
}
}
But that assumes you always set pointers back to NULL wh... |
3,096,823 | 3,097,183 | Get USB serial number c++ | I'm looking to retrieve the serial number from a USB memory stick on windows in c++.
I have found plenty of C# examples, and c++ for linux but none for c++ and windows.
Edit
C++/CLI is not an option unfortunately.
I am looking for the serial number of the device not the file system. OR "Device Instance Path" AKA "I... | If C++ is a requirement then you'll have to write COM code. A bit unjoyful compared to VB.NET code, but there are very good examples available in the MSDN library, you just need to adapt the query.
Beware that the example you linked to does not return a serial number of the device itself, just the file system on the d... |
3,097,229 | 3,102,601 | Protocol Buffer and UTF16 Unicode | How do you use Google Protocol Buffer with UTF16 Unicode?
| Basically I will convert UTF16 to UTF8. Searching SO, I think your answer is in this question
|
3,097,264 | 3,097,279 | How can I make a std::list of arrays? | I would like to make an std::list of arrays. specifically, I want a list of arrays of Borland Code Builders AnsiStrings.
the real kicker being that I would like the arrays to be allocated dynamically. How do I define the list? Im so lost here i dont know were to begin.
std::list<???> myList;
What am I putting inside... | typedef std::vector<char> char_array;
typedef std::list<char_array> char_array_list;
Or more appropriately:
typedef std::list<std::string> string_list;
|
3,097,445 | 3,097,555 | vector of double[2] error | why this error:
#include <vector>
typedef double point[2];
int main()
{
std::vector<point> x;
}
/usr/include/c++/4.3/bits/stl_construct.h: In function ‘void std::_Destroy(_Tp*) [with _Tp = double [2]]’:
/usr/include/c++/4.3/bits/stl_construct.h:103: instantiated from ‘void std::_Destroy(_ForwardIterator, _For... | You can't do that. As mentioned, arrays are not copyable or assignable which are requirements for std::vector. I would recommend this:
#include <vector>
struct point {
double x;
double y;
};
int main() {
std::vector<point> v;
}
It will read better anyway since you can do things like:
put(v[0].x, v[0].y, ... |
3,097,548 | 3,097,666 | Exporting global variables from DLL | I'm trying to export a global variable from a DLL.
Foo.h
class Foo
{
public:
Foo()
{}
};
#ifdef PROJECT_EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif
API const Foo foo;
Foo.cpp
#include "Foo.h"
const Foo foo;
When I compile the above code, Visual Studio co... | In your header:
API extern const Foo foo;
In your source file:
API const Foo foo;
If you don't have the extern keyword, your C compiler assumes you mean to declare a local variable. (It doesn't care that you happened to have included the definition from a header file.) You also need to tell the compiler that you're p... |
3,097,593 | 3,097,611 | What happens when C++ reference leaves its scope? | If I interpret C++ references correctly, they are like pointers, but with guaranteed data integrity (no NULL, no (int*) 0x12345). But what happens when scope of referenced object is leaved? If there are no magic involved (and probably it is not), referenced object will be destroyed behind my back.
I wrote a piece of c... | this is undefined behavior and you were simply lucky that the memory for a hadn't been used for anything else yet. In a more complex scenario you would almost certainly get garbage. On my machine I get random garbage with this code. For me, this is likely because I am using a 64-bit machine which uses a register callin... |
3,097,626 | 3,097,671 | strange error in g++ | My program has a class with a vector of Level objects named levels. In a member function there is this line:
levels.push_back(level::Level());
I made several changes to my program today, and that line of code started segfaulting:
0x0804d248 in void std::vector<yarl::level::Level, std::allocator<yarl::level::Level> >:... | level::Level foo();
That declares a function named foo that takes no arguments and returns a level::Level. This is known as the most vexing parse. This creates a level::Level using the default constructor:
level::Level foo;
As for your original problem, you appear to have a null this pointer:
... ::push_back (this=... |
3,097,655 | 3,181,548 | Compilation errors when inheriting PortableServer::RefCountServantBase | I am working on a corba application where in create_servant() method we are creating new servant and returning it to the callee. To make the memory management easier, I am inheriting PortableServer::RefCountServantBase class to the implementation class.
I get the below compilation errors.
"simples.cpp", line 108: ... | In newer versions of CORBA, RefCountServantBase is deprecated. You no longer need to inherit from it because the auto-generated C++ servants now provide the same functionality. You should verify that the ORB you are using has implemented this change.
As to the part of your question about your create_servant() function.... |
3,097,684 | 3,097,709 | how to call a method with string& parameter by using char*? | I have a C++ dll from other company. there is a method with a string& msg parameter, void methodA(string& msg);
What I have now is a char* with length which is big enough to take the msg from methodA. I want to call methodA to get message back from methodA.
Can I do it? how?
thanks,
| #include <algorithm>
void foo(char* buffer)
{
std::string str;
methodA(str);
std::copy(str.begin(), str.end(), buffer);
buffer[str.size()] = 0;
}
|
3,097,779 | 3,097,803 | decltype and parentheses | I don't understand the last line of the example on page 148 of the FCD (§7.6.1.2/4):
const int&& foo();
int i;
struct A { double x; };
const A* a = new A();
decltype(foo()) x1 = i; // type is const int&&
decltype(i) x2; // type is int
decltype(a->x) x3; // type is double
decltype((a->x)) x4 = x... | Just above that example, it says
if e is an unparenthesized id-expression or a class member access (5.2.5), decltype(e) is the type of the entity named by e.
if e is an lvalue, decltype(e) is T&, where T is the type of e;
I think decltype(a->x) is an example of the "class member access" and decltype((a->x)) is an e... |
3,097,806 | 3,097,861 | const reference to temporary oddity | We all know that things like this are valid in c++:
const T &x = T();
while:
T &x = T();
is not.
In a recent question the conversation lead to this rule. The OP had posted some code which clearly evokes UB. But I would have expect a modified version of it to work (This is the modified version):
#include <iostream>
us... | It simply demonstrates that analyzing language behavior by "trying it in the compiler" doesn't normally produce any useful results. Both of your examples are invalid for the very same reason.
The lifetime of the temporary is only extended when you use that temporary as the direct initializer for a const reference - onl... |
3,097,868 | 3,097,892 | Where to place file in order to read? | Hey, where do I place a text file that I'm trying to read using fstream? In this tutorial, http://www.gamedev.net/reference/articles/article1127.asp, they say
ifstream fin("input.txt");
where would "input.txt" be located? Before I tried directing a path to the file by doing this "C:\Users\XXXXXXX\Documents\test.in". Th... | input.txt should be in the working directory. Usually the working directory is the directory containing the executable. In the case of Visual Studio, the working directory when run in the debugger can be set in the Debug options.
|
3,097,882 | 3,098,089 | find most often seen string from a log file | I want to find most often seen string in a huge log file. Can someone help me how to do this. one way to do this is to hash each and every string and count the maximum value but its not efficient. Are there any better ways to do this.
Thanks & Regards,
Mousey.
| If performance is critical you may want to look at a trie or a Radix tree.
If you're just interested to know if one of the strings appears more than 50% of the times (let's call that string the majority string) you can do something like this (see if I can get this right):
get the first string and assume it's the majo... |
3,097,949 | 3,098,338 | How can I determine the statistical randomness of a binary string? | How can I determine the statistical randomness of a binary string?
Ergo, how can I code my own test, and return a single value that corresponds to the statistical randomness, a value between 0 and 1.0 (0 being not random, 1.0 being random)?
The test would need to work on binary strings of any size.
When you do it with ... | This will give you an entropy count from 0 to 1.0:
You might want to try looking into the Shannon Entropy, which is a measure of entropy as applied to data and information. In fact, it is actually almost a direct analogue of Physical formula for entropy as defined by the most accepted interpretations of Thermodynamic... |
3,098,010 | 3,098,036 | Cannot find default constructor | My error occurs on line 191 and 156. For some reason it is saying it cant find the default constructor when I have supplied the right amount of parameters.
The error it is giving me is "Cannot find default constructor to initialize base class"
code: http://pastebin.com/WLMvBMyy
If anyone could offer any input it would ... | HField(int row, int column, int length, const char *s = NULL, void (*h)(void*) = NULL) {
SField(row, column, length, s);
ptrFunc = h;
}
This is not how you call base class constructors. The syntax you are looking for is:
HField(int row, int column, int length, const char *s = NULL, void (*h)(void*) = N... |
3,098,085 | 3,098,124 | Efficient method of passing callback member function | I'm designing a method for an input handler class. Here is some pseudo code...
void InputHandler::ScanEvents( boost::function1< void, std::string& > &func ) {
// Scan keys, determining string to pass
// If string found, call func with string as its argument on object tied to func
}
I'm not exactly sure how to ... | Something along the lines of
class Thingy
{
public:
Thingy() : callback(bind(&Thingy::Callback, this, _1)) {}
void DoStuff()
{
handler.ScanEvents(callback);
}
private:
InputHandler handler;
function<void(string)> callback;
void Callback(string s)
{
cout << "Called with... |
3,098,209 | 3,098,215 | How to find the no of elements in an string array (the string is passed to a function) | #include<iostream>
#include<string>
using namespace std;
class Prerequisites
{
public:
void orderClasses(string* Input);
};
void Prerequisites::orderClasses(string* Input)
{
// Need to find the length of the array Input
}
int main()
{
Prerequisites A;
string classes[]={"CSE121: CSE110"... | You should pass the number of elements in the array to orderClasses(). Since that is not an option, consider some alternatives:
Add another member function to Prerequisites to inform it how large the array will be when you do call orderClasses().
Use a sentinel value for the last string in the array so that when you ... |
3,098,281 | 3,098,334 | Can someone help clarify how header files work? | I've been working with C++ for a good couple of weeks now, but the mechanism behind header files (or the linker I suppose?) confuses the heck out of me. I've gotten in the habit of creating a "main.h" to group my other header files and keep the main.cpp tidy, but sometimes those header files complain about not being ab... | The other answers here have effectively explained the way header files and the preprocessor work. The biggest problem you have is the circular dependencies, which from experience, I know can be a royal pain. Also, when that starts happening, the compiler starts to behave in very odd ways and throw error messages that... |
3,098,347 | 3,098,369 | Nested type as function argument | I have the following template class:
template<class T>
class C
{
typedef C_traits<T> traits;
typedef typename traits::some_type type;
//...
// use 'traits' and 'type' a lot
//...
};
where C_traits is a template struct that has a typedef for some_type that is different for each speci... | template <typename T>
void f(const typename C<T>::type& c) { }
This is allowed, but a qualified type is one of the non-deduced contexts. That is, template argument deduction won't work for this, so you'll have to call the function like so:
f(42); // won't work
f<int>(42); // works
If you don't want to supply t... |
3,098,607 | 3,098,653 | Type of UTF-16 encoding, using wofstream in Windows | Recently, I want to write a text file in unicode (UTF-16) under Windows.
By refering to http://www.codeproject.com/KB/stl/upgradingstlappstounicode.aspx, here is the code I am applying.
When I use Notepad to open up the document, here is the display. Newline seems disappear!!!
(source: google.com)
When I use Firefox ... | When you do ios::binary, the file is opened in binary mode which means newlines aren't converted to the correct \r\n encoding on Windows.
If you write "\r\n" instead of std::endl, it should work in Notepad. I'm not sure if this is the best solution.
|
3,098,718 | 22,864,560 | Installing C++ Armadillo library on Mac OS X | I am trying to use the C++ armadillo library (armadillo-0.9.10) on a Mac Pro. I follow the manual installation instruction in the README.txt file. I have modified the config.hpp file to indicate that I have LAPACK and BLAS installed. I then try to compile the examples. I successfully compile and run example1.cpp, bu... | I am not sure if You are still trying to figure this out or now but to answer your original question, you can easily download and setup Armadillo from the website: http://arma.sourceforge.net/download.html
I would rather use home brew instead:
brew install armadillo
|
3,098,753 | 3,098,776 | Sometimes my windows handle is good, sometimes it bad | I am confused. Sometimes when I initiate my window, the Handle returned is good. and sometimes its not. Here is my code
void GXRenderManager::InitWindows()
{
WNDCLASSEX wndcex;
wndcex.cbSize = sizeof(WNDCLASSEX);
wndcex.style = CS_HREDRAW | CS_VREDRAW;
wndcex.lpfnWndProc = GXRenderManager::WndProc... | You are saving a pointer to a local variable (tempWin) and expecting that will be valid after you return from the InitWindows() function. Instead of making GXRenderManager::mainWindow a pointer, declare it as an actual data member. So:
class GXRenderManager {
...
HWND mainWindow; // not a pointer
...
};
GX... |
3,098,767 | 3,223,783 | Creating a menu strip with WinAPI | In .Net there is something called a menu strip. These are more customizable than HMENU's. How could I create one of these in unmanaged C++?
Thanks
| They aren't more customizable than HMENUs, they're just easier to customize. If you don't want to use MFC C++ WinAPI wrapper, what do you want to customize ?
|
3,098,940 | 3,099,235 | Calculating both weighted and unweighted statistics with the same boost::accumulator_set? | With Boost's accumulators I can easily calculate statistical quantities for
weighted or unweighted input sets. I wonder if it is possible to mix weighted
and unweighted quantities inside the same accumulator. Looking at the
docs it doesn't seem that way.
This compiles fine but produces another result than I would have ... | It does say in the documentation that
When you specify a weight, all the
accumulators in the set are replaced
with their weighted equivalents.
There are probably better ways to do it but you can try something like this (basically swapping the meaning of the value with that of the weight):
accumulator_set< double... |
3,098,983 | 3,099,032 | C++ template specialization of templated types | I'm looking to help users of some of my templated code by using BOOST_STATIC_ASSERT to let them know that they've used an incompatible type with a simpler compile error message than the monster than is currently produced with an incompatible type.
The example is a bit too complex to reproduce here, but hopefully this w... | Change the code to
template <typename P1, int P2, typename P3>
struct is_interesting_type<InterestingType<P1, P2, P3> >{
static const bool value = true;
};
|
3,099,039 | 3,141,301 | How to detect and remove guide lines from a scanned image/document efficiently? | For my project i am writing an image pre processing library for scanned documents. As of now I am stuck with line removal feature.
Problem Description:
A sample scanned form:
Name* : ______________________________
Age* : ______________________________
Email-ID: |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|
Note:
Following are ... | First, I want to mention that I know nothing about image processing in general, and about OCR in particular.
Still, a very simple heuristic comes to my mind:
Separate the pixels in the image to connected components.
For each connected component decide if it is a line or not using one or more of the following heuristic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.