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 |
|---|---|---|---|---|
1,695,421 | 1,695,442 | Creating spherical meshes with Direct x? | How do you go about creating a sphere with meshes in Direct-x? I'm using C++ and the program will be run on windows, only.
Everything is currently rendered through an IDiRECT3DDEVICE9 object.
| You could use the D3DXCreateSphere function.
|
1,695,474 | 1,695,485 | Localization of string literals | I need to localize error messages from a compiler. As it stands, all error messages are spread throughout the source code as string literals in English. We want to translate these error messages into German. What would be the best way to approach this? Leave the string literals as-is, and map the char* to another langu... | On Windows, typically this is done by replacing the string with integer constants, and then using LoadString or similar to get them from a resource in a DLL or EXE. Then you can have multiple language DLLs and a single EXE.
On Unixy systems I believe the most typical approach is gettext. The end result is similar, bu... |
1,695,681 | 1,695,690 | Reading from and writing to the middle of a binary file in C/C++ | If I have a large binary file (say it has 100,000,000 floats), is there a way in C (or C++) to open the file and read a specific float, without having to load the whole file into memory (i.e. how can I quickly find what the 62,821,214th float is)? A second question, is there a way to change that specific float in the f... | You know the size of a float is sizeof(float), so multiplication can get you to the correct position:
FILE *f = fopen(fileName, "rb");
fseek(f, idx * sizeof(float), SEEK_SET);
float result;
fread(&result, sizeof(float), 1, f);
Similarly, you can write to a specific position using this method.
|
1,695,777 | 1,695,850 | Any tips for a newbie who wants to find a good debugger for C++? | I'm trying to debug my code. I haven't really used a debugger before. I know that in the long run, learning how to use a debugger will be very, very helpful, so I'm trying to find one that suits me. Are there any newbie-friendly debuggers for C++? Ideally with a good GUI...
If not, can anyone point me to a good, newbie... | If you are having troubles with the UI of GDB, try DDD. It is a graphical front-end for debuggers like GDB, and has quite a number of nice features. You can see a sample session of it here.
|
1,695,807 | 1,696,194 | Why isn't C/C++'s "#pragma once" an ISO standard? | I am currently working on a big project and maintaining all those include guards makes me crazy! Writing it by hand is frustrating waste of time. Although many editors can generate include guards this doesn't help much:
Editor generates guard symbol based on a filename. The problem occurs when you have headers with th... | A directive like #pragma once is not trivial to define in a fully portable way that has clear an unambiguous benefits. Some of the concepts for which it raises questions are not well defined on all systems that support C, and defining it in a simple way might provide no benefit over conventional include guards.
When th... |
1,695,922 | 1,695,939 | Representing integers as a byte | Currently I'm working on an assignment and using C++ for the first time.
I'm trying to append certain "message types" to the beginning of strings so when sent to the server/client it will deal with the strings depending on the message type. I was wondering if I would be able to put any two-digit integer into an element... | '10' is not a valid value, thus the overflow
either write 10 as in messageBuffer[0]=10 - if ten is the value you want to put it or do as Lars wrote.
|
1,696,009 | 1,696,038 | Mysql_num_rows() Segfaults | I'm writing a program using C++ and the MySQL C API (version 5.1.31 ubuntu2). However, if the query is UPDATE then I get a Segmentation Fault error when executing the line "RowsReturned = mysql_num_rows( Result );".
//this code snippet contains only the relevant code
MYSQL_RES *Result;
long RowsReturned;
MYSQL_RES *MY... | From the mysql documentation:
mysql_store_result() returns a null pointer if the statement didn't return a result set (for example, if it was an INSERT statement).
You are updating so you have a NULL as results.
Try something like this:
Result = mysql_store_result( Connection );
if (Result) {
RowsReturned = mysql_... |
1,696,086 | 1,696,174 | What's the best way to get the length of the decimal representation of an int in C++? | What's the best way to write
int NumDigits(int n);
in C++ which would return the number of digits in the decimal representation of the input. For example 11->2, 999->3, -1->2 etc etc.
| Straightforward and simple, and independent of sizeof(int):
int NumDigits(int n) {
int digits = 0;
if (n <= 0) {
n = -n;
++digits;
}
while (n) {
n /= 10;
++digits;
}
return digits;
}
|
1,696,225 | 1,696,249 | Null Pointer to Object problems | Hi can someone tell why in Linux and windows the same problem occurs :
#include <iostream>
using namespace std;
class A
{
private:
int _dmember;
public:
void func()
{
cout<<"Inside A!! "<<endl;
cout<<_dmember; // crash when reach here.
}
};
int main ()
{
A* a= NULL;
a->func(); // pri... | This is undefined behaviour. You must never call functions on a null pointer.
With that out of the way, let's answer the question I think you're asking: why do we get partway into the function anyway?
When you are invoking UB, the compiler is free to do anything, so it's allowed to emit code that works anyway. That's w... |
1,696,300 | 1,696,309 | How to compile C++ under Ubuntu Linux? | I cut&pasted the below code from a previous question into a file called "avishay.cpp" and then ran
gcc avishay.cpp
only to get the following error messages from the linker. What went wrong, what should I have done?
carl@carl-ubuntu:~/Projects/StackOverflow$ gcc -static avishay.cpp
/tmp/cccRNW34.o: In function `__sta... | You should use g++, not gcc, to compile C++ programs.
For this particular program, I just typed
make avishay
and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.
|
1,696,671 | 1,696,720 | How to detect programmatically count of bytes allocated by process on Heap? | How to detect programmatically count of bytes allocated by process on Heap?
This test should work from process itself.
| A speculative solution: redefine new and delete operators.
On each new operator call, a number of bytes to allocate is passed. Allocate a bit more memory and store the amount of bytes allocated within. Add this amount to global variable that holds the heap size.
On delete operator call, check the value you stored bef... |
1,696,683 | 1,696,721 | Explicitly rounding numbers to more than 7 decimal places in C++ | Here is my code:
double round( char* strNumber, int decPlace);
int main()
{
int decimal;
char initialNumber[256];
cout << "Enter decimal and number " << endl;
cin >> decimal;
cin >> initialNumber;
cout << setprecision (15) << round ( initialNumber,decimal ) << endl;
return 0;
}
dou... | As others have said, the cast to int won't work with large numbers. You could consider using floor instead, and keeping the number to be rounded in a double:
#include <cstdlib>
#include <cmath>
double round( char* strNumber, int decPlace)
{
double number = std::atof(strNumber);
double expo = std::pow(10.0,decP... |
1,696,769 | 1,696,875 | Force showing system tray notification balloons | My application (C++ WinAPI) creates an icon in the system tray. I have set a tooltip text for this icon, so that when a user places a mouse cursor over the icon, this text shows.
But I want to programmatically show different balloon notications when certan events occur and at the same time keep that behavior of showing... | You can add the balloon using the .szInfo (message) and .szInfoTitle (title) members of the NOTIFYICONDATA structure that you send to Shell_NotifyIcon(). The mouse-over tooltip text is set in .szTip so this is independent of the balloon - as long as you keep .szTip to the tooltip you want you can do as much NIM_MODIFY ... |
1,697,153 | 1,697,202 | Which database should I use to store records, and how should I use it? | I'm developing an application that will store a sizeable number of records. These records will be something like (URL, date, title, source, {optional data...})
As this is a client-side app, I don't want to use a database server, I just want the info stored into files.
I want the files to be readable from various langua... |
I am seeing two possibilities: sqlite
and BerkeleyDB. As my use case is
clearly not relational, I am tempted
to go with BerkeleyDB, however I don't
really know how I should use it to
store my records, as it only stores
key/value pairs.
What you are describing is exactly what relational is about, even if y... |
1,697,607 | 1,697,615 | Naming confusion? Is having objects named FlowerGroup and FlowerGroups confusing? | I'm writing a program and I seem to be creating alot of objects where one object will be the singular form and then the collection is the plural form. eg
SalesGroup
SalesGroups
Is this confusing for other programmers to read my code?
| should not be confusing, in fact I find it pretty informative and clear; unless you have multiple kinds of collections (lame example: suppose you have an array but also a map of SalesGroup, then SalesGroups would not be the best choice but you'd rather pick SalesGroupArray, SalesGroupMap etc.)
|
1,697,609 | 1,697,947 | Refactoring function calls while reducing code duplication of resulting class definitions | I have a header file with about 400 function declarations and its corresponding source file with the definitions.
In order to replace the implementation with a mock at runtime, I want to replace the implementation with calls to an object that will contain the implementation instead (pointer to implementation - pImpl).
... | What about something like this:
//=======================================
// Macro definition of method list
//=======================================
#define METHOD_LIST(ABSTRACT) \
virtual void Foo1() ABSTRACT; \
virtual void Foo2() ABSTRACT; \
virtual void Foo3() ABSTRACT
//=============================... |
1,697,683 | 1,697,735 | Horner's rule in C++ | While trying to evaulate polynomials using Horner's Rule I have a sample code segment like so:
int Horner( int a[], int n, int x )
{
int result = a[n];
for(int i=n-1; i >= 0 ; --i)
result = result * x + a[i];
return result;
}
I understand that a is an array of coefficients and that x is the value ... | n is the degree of the polynome (and a polynome of degree n, aside from 0 which is kind of special, has n+1 coefficients, so size of array = n+1, n = size of array - 1)
|
1,697,852 | 1,697,861 | C/C++/Objective-C text recognition library | Does anyone know of any free/open-source text recognition libraries in C/C++/Objective-C? Basically something that can scan an image, and read out all of the plain text.
| The most famous one is Tesseract OCR developed initially by Motorola and later become open source. It is also promoted by Google.
There are a few more, perhaps not as famous as Tesseract:
http://en.wikipedia.org/wiki/OCRopus
http://jocr.sourceforge.net/
|
1,697,931 | 1,703,466 | How to use "billboards" to create a spherical object on the screen | I am tasked with making a sun/moon object flow across the screen throughout a time-span (as it would in a regular day). One of the options available to me is to use a "billboard", which is a quad that is always facing the camera.
I have yet to use many direct x libraries or techniques. This is my first graphics pro... | Okay im not a direct x expert so i am going to assume a few things.
First i am assuming you have some sort of DrawQuad() function that takes the 4 corners and a texture inside your rendering class.
First we want to get the current viewport matrix
D3DMATRIX mat;
hr = m_Renderer->GetRenderDevice()->GetTransform(D3DTS_VI... |
1,697,965 | 1,697,972 | initializer-string for array of chars is too long | I keep getting this error: initializer-string for array of chars is too long
Even if I change num and length to 1, it still gets the error:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int num = 11;
const int length = 25;
char array[num][length] = { "Becky Warre, 555-1223"... | I think it's because there aren't any commas in your array initialization...
char array[num][length] = { "Becky Warre, 555-1223",
"Joe Looney, 555-0097",
"Geri Palmer, 555-8787",
"Lynn Presnell, 555-1212",
"H... |
1,698,010 | 1,698,024 | C++ Templated return | I have a program which is built on "Entities", which hold "Components" (composition FTW).
Components may include many different types including scripts, assets, etc. I would like to build an Entity function called
Entities have a map of strings, and actual Components, such that the Components can be searched for by ty... | Does your function create components? Then it is a factory. You could wrap it in that template in order to save clients the (potentially erroneous) casting.
The type of the function template would look like this:
template< typename T >
T* GetComponent(const char*); // presuming it returns a pointer
and it would be c... |
1,698,265 | 1,699,628 | Unexpected results using istringstream for string to double conversion in C++ | I'm currently trying to take a string ("0.1") and convert it to a double using C++ in Xcode on 10.6 with gcc4.2.
I'm using a function I pinched from another question, but when I try to use the function, my input according to gdb is (string)"0.1", but my output is (double)2.1220023981051542e-314.
Here is my snippet copi... | This may be caused by STL Debug mode. Remove the _GLIBCXX_DEBUG macros in your target's Preprocessor Macros build setting.
C++ Debug builds broke in Snow Leopard X-Code
|
1,698,294 | 1,698,326 | What is best practice for C++ Public API? | What is best practice for C++ Public API?
I am working on a C++ project that has multiple namespaces, each with multiple objects. Some objects have the same names, but are in different namespaces. Currently, each object has its own .cpp file and .h file. I am not sure how to word this... Would it be appropriate to crea... | It is sometimes convenient to have a single class in every .cpp and .h pair of files and to have the namespace hierarchy as the directory hierarchy.
For instance if you have this class:
namespace stuff {
namespace important {
class SecretPassword
{
...
};
}
}
then it will be in two files:
/stuf... |
1,698,388 | 1,698,413 | illegal reference to non-static member 'Sun::m_SunTexture' | I am not overly competent in C++ and this compiler error is just making no sense to me. The following line calls the compiler error shown in the title:
m_SunTexture = LudoTextureManager::GetInstance()->GetTextureData(hardcoded.c_str()).m_Texture;
where m_SunTexture is defined in my header file as
IDirect3DTexture9 *... | I'm guessing that the first line of code is in a static function, which is referring to the non-static member "m_SunTexture".
See this for more information. Essentially, static functions don't have a "this" pointer, so referring to non-static members (which belong to each instance of the class) doesn't make any sense.
|
1,698,660 | 1,698,665 | When I change a parameter inside a function, does it change for the caller, too? | I have written a function below:
void trans(double x,double y,double theta,double m,double n)
{
m=cos(theta)*x+sin(theta)*y;
n=-sin(theta)*x+cos(theta)*y;
}
If I call them in the same file by
trans(center_x,center_y,angle,xc,yc);
will the value of xc and yc change? If not, what should I do?
| Since you're using C++, if you want xc and yc to change, you can use references:
void trans(double x, double y, double theta, double& m, double& n)
{
m=cos(theta)*x+sin(theta)*y;
n=-sin(theta)*x+cos(theta)*y;
}
int main()
{
// ...
// no special decoration required for xc and yc when using references
... |
1,698,796 | 1,698,813 | Problem reading and writing from same file within same program... C++ | I'm working on a program, that needs to load data from a text file upon starting and save data to THE SAME text file upon exit. I have the load working, and i have the save working, but for some reason I cant seem to have them both work within the same program.
This doesnt work...
ifstream loadfile("test.txt");
ofstrea... | ofstream savefile("test.txt");
is equivalent to:
ofstream savefile;
savefile.open("test.txt", ios::out|ios::trunc);
That is, you're truncating the file as you open it. So, move the initialization of savefile to happen after you're done with your load call (I'd suggest doing it as late as possible, because if you cra... |
1,698,838 | 1,698,908 | What is wrong with this c++ typedef? | This is a piece of my code, I have more class like MathStudent, ArtStudent, etc. which inherits Student class. When I tried to compile, it says "forbids declaration of `vector' with no type," what is the problem here?
thanks
class Student {
public:
typedef vector<Student> Friends; // something wrong here?
vir... | One problem with the typedef is that class Student is an abstract class, so it cannot be default constructed, which is required for types that vectors can be composed of.
Another issue (say you removed the fact that class Student is abstract) might be that the class isn't fully defined. You can, in fact, declare a typ... |
1,699,015 | 1,699,051 | C++ Template specialization to provide extra member function? | how do I provide extra member function for specialized template in a non-inline way?
i.e.
template<typename T>
class sets
{
void insert(const int& key, const T& val);
};
template<>
class sets<bool>
{
void insert(const int& key, const bool& val);
void insert(const int& key){ insert(key, true); };
};
But whe... | That's because it is not a function of your template so don't use "template<>". It works for me after removing "template<>" as below:
void sets<bool>::insert(const int& key)
{
insert(key, true);
}
My system FC9 x86_64.
The entire code:
template<typename T>
class sets
{
public:
void insert(const int& key, c... |
1,699,057 | 1,699,141 | Why are two different concepts both called "heap"? | Why are the runtime heap used for dynamic memory allocation in C-style languages and the data structure both called "the heap"? Is there some relation?
| Donald Knuth says (The Art of Computer Programming, Third Ed., Vol. 1, p. 435):
Several authors began about 1975 to call the pool of available memory a "heap."
He doesn't say which authors and doesn't give references to any specific papers, but does say that the use of the term "heap" in relation to priority queues i... |
1,699,307 | 1,699,318 | How to deal with initialization of non-const reference member in const object? | Let's say you have a class
class C
{
int * i;
public:
C(int * v):i(v) {};
void method() const; //this method does not change i
void method(); //this method changes i
}
Now you may want to define const instance of this class
const int * k = whatever;
... | Your example doesn't fail, k is passed by value. The member i is 'implicitly constant' as direct members of C can't be changed when the instance is constant.
Constness says that you can't change members after initialization, but initializing them with values in the initialization list is of course allowed - how else wo... |
1,699,438 | 1,699,461 | C++ Find the number of elements in a range from an STL::multimap | I have a STL::multimap and I search it with equal_range to return an upper and lower bound. Can I find the number of elements in this range without iterating through them all and counting them one by one?
#include <iostream>
#include <map>
using namespace std;
int main () {
multimap<int,int> mm;
pair<multimap... | Use std::distance algorithm to find the distance between the iterators. Like:
int ct1 = std::distance(ret.first, ret.second);
|
1,699,532 | 1,699,539 | How to convert C++ class/struct to a primitive/different type/class/struct? | I have the following class CppProperty class that holds value:
template<typename TT>
class CppProperty
{
TT val;
public:
CppProperty(void)
{
}
CppProperty(TT aval) : val(aval)
{
}
CppProperty(const CppProperty & rhs)
{
this->val = rhs.val;
}
virtual ~CppProperty(vo... | You'd need a conversion operator:
operator const TT&(void) const
{
return val;
}
operator TT&(void)
{
return val;
}
There is a brief tutorial on conversion operators here. In short, when the compiler tries to convert a type, it will first look at the right-hand side for an operator that will convert it to th... |
1,699,608 | 1,699,624 | How to get OS information whether it be LINUX or WINDOWS? | I'm running "QUdpSocket::ShareAddress" on my QT application but ShareAddress is ignored by windows. So I'm trying to solve this problem by identifying OS at run time.
I heard a couple of information about window version indentifier but I couldn't see any solution to solve my problem.
If there is any of advice, it woul... | #include <QtGlobal>
...
#ifdef Q_OS_MAC
// mac
#endif
#ifdef Q_OS_LINUX
// linux
#endif
#ifdef Q_OS_WIN32
// win
#endif
See QtGlobal documentation for further information.
|
1,699,704 | 1,700,899 | boost::multi_index_container with random_access and ordered_unique | I have a problem getting boost::multi_index_container work with random-access and with orderd_unique at the same time. (I'm sorry for the lengthly question, but I think I should use an example..)
Here an example: Suppose I want to produce N objects in a factory and for each object I have a demand to fulfill (this deman... | (I had to use an own answer to write code-blocks - sorry!)
The composite_key with used_time and parts (as Kirill V. Lyadvinsky suggested) is basically what I've already implemented. I want to get rid of the lexicographical compare of the parts-vector.
Suppose I've stored the needed_demand somehow then I could write a... |
1,699,840 | 1,700,080 | MSVC: what compiler switches affect the size of structs? | I have two DLLs compiled separately, one is compiled from Visual Studio 2008 and one is a mex file compiled from matlab.
Both DLLs have a header file which they include. when I take the sizeof() the struct in one DLL it returns 48, and in the other it returns 64.
I've checked the /Zp switch and in both compilations it ... | Ok, so this is possibly the most obscure thing ever.
It turns out that matlab add /D_SECURE_SCL=0 to the compilation which disables something called 'secure iterators'
This in turn causes a difference of 16 bytes in the size of std::vector
|
1,700,079 | 1,700,227 | Howto create combinations of several vectors without hardcoding loops in C++? | I have several data that looks like this:
Vector1_elements = T,C,A
Vector2_elements = C,G,A
Vector3_elements = C,G,T
..... up to ...
VectorK_elements = ...
#Note also that the member of each vector is always 3.
What I want to do is to create all combination of elements in Vector1 through out VectorK.
Hence in the end... | This will do the trick:
void printAll(const vector<vector<string> > &allVecs, size_t vecIndex, string strSoFar)
{
if (vecIndex >= allVecs.size())
{
cout << strSoFar << endl;
return;
}
for (size_t i=0; i<allVecs[vecIndex].size(); i++)
printAll(allVecs, vecIndex+1, strSoFar+allVecs... |
1,700,299 | 1,700,365 | Mutex in shared memory when one user crashes? | Suppose that a process is creating a mutex in shared memory and locking it and dumps core while the mutex is locked.
Now in another process how do I detect that mutex is already locked but not owned by any process?
| If you're working in Linux or something similar, consider using named semaphores instead of (what I assume are) pthreads mutexes. I don't think there is a way to determine the locking PID of a pthreads mutex, short of building your own registration table and also putting it in shared memory.
|
1,700,428 | 1,700,496 | Transition from MFC to QT | Currently all our GUI components are written in MFC. Our build environment is:
VC 6
Windows XP
I have no idea whether:
1) We can replace all MFC components with Qt, without changing build environment ?
2) Qt will work with VC6 as any other library?
You answers will help me in getting started, In the mean time I hav... |
If we can replace all MFC components with QT, without changing build environment ?
Yes, you even get a MFC/Qt migration framework cf qt.nokia.com/products/appdev/add-on-products/catalog/4/Windows/qtwinmigrate/
Will Qt work with VC6 as any other library ?
VC6 is more than 10 years old!
Qt supports VC6 until vers... |
1,700,651 | 1,711,949 | How to use speech recognition with/on video file? | How can I code speech recognition engine (Using Microsoft Speech SDK) to "listen" a video file and save the detection into a file?
| This is very similar to this question and has a very similar answer. You need to separate out the audio portion, convert it to WAV format, and send it to an inproc recognizer.
However, it has the same problems that I described before (requires training, assumes a single voice, and assumes the microphone is close to th... |
1,701,022 | 1,701,267 | Boost Multi-Index : Composite key of vector and int for hashed indices | as I've just learned in in my other question, I could use a composite_key for a struct, which has a std::vector and an integer. Now my question is: Can I use this somehow to work with hashed_indecies?
Here an example similar to THIS:
struct unique_property
{
//the pair of int and std::vector<int> shall be unique
in... | Use code snippet from your suggestion here. It should work. I've added my comments there.
|
1,701,055 | 1,701,272 | What is the maximum length in chars needed to represent any double value? | When I convert an unsigned 8-bit int to string then I know the result will always be at most 3 chars (for 255) and for an signed 8-bit int we need 4 chars for e.g. "-128".
Now what I'm actually wondering is the same thing for floating-point values. What is the maximum number of chars required to represent any "double" ... | The standard header <float.h> in C, or <cfloat> in C++, contains several constants to do with the range and other metrics of the floating point types. One of these is DBL_MAX_10_EXP, the largest power-of-10 exponent needed to represent all double values. Since 1eN needs N+1 digits to represent, and there might be a neg... |
1,701,067 | 1,701,083 | How to check that an element is in a std::set? | How do you check that an element is in a set?
Is there a simpler equivalent of the following code:
myset.find(x) != myset.end()
| The typical way to check for existence in many STL containers such as std::map, std::set, ... is:
const bool is_in = container.find(element) != container.end();
|
1,701,149 | 1,701,167 | Simple C++ logger by using singleton pattern | Due to the flooding examples of implementing logger using Singleton pattern, I have just written a simple C++ logger in the same approach for my program. However, since the famous double-checked locking approach is known to be no more thread-safe, I wonder if I should:
1) Forget about the use of Singleton pattern in th... | Use Meyers Singleton. If you are using using gcc at least initialization is thread-safe.
class Singleton{
Singleton(){
//This is threadsafe in gcc, no mutex required
}
static Singleton * instance(){
static Singleton myinstance;
return &myinstance;
}
};
gcc guards static locals construction ... |
1,701,416 | 1,701,456 | Initialization of reference member requires a temporary variable | struct Div
{
int i;
int j;
};
class A
{
public:
A();
Div& divs;
};
In my constructor definition, I have the following implementation
A::A(): divs(NULL)
{}
I get the following error:
Error72 error C2354: 'A::divs' : initialization of reference member
requires a temporary variable
| A reference must be initialised to refer to something; it can't refer to nothing, so you can't default-construct a class that contains one (unless, as others suggest, you define a global "null" value). You will need a constructor that is given the Div to refer to:
explicit A(Div &d) : divs(d) {}
If you want it to be a... |
1,701,869 | 1,701,919 | Unit testing. File structure | I have a C++ legacy codebase with 10-15 applications, all sharing several components.
While setting up unittests for both shared components and for applications themselves, I was wondering if there are accepted/common file structures for this.
Because my unit tests have several base classes in order to simplify projec... | Out of sight, out of mind; if you keep the test files together with the code files it may be more obvious to the developers that when they update a code file they should update the tests as well.
|
1,702,600 | 1,702,636 | Is it possible to progressively alpha-blend between two textures in one location created with D3DXCreateTextureFromFileInMemoryEx? | I have two textures that are both .jpg, which represent a sky (one during the day, one at night). My question is, is it possible for me to fade one texture into the other? They are created with D3DXCreateTextureFromFileInMemoryEx. How can I perform this kind of transition? I don't wish to create two objects, just c... | You have quite a few options here -
You can use both textures with texture blending to transition from one texture to the other.
However, if you're doing this over a long period of time, you may want to precompute a third texture (the blended state) and just use it as a single texture. Occasionally, recompute the "new... |
1,702,673 | 1,702,709 | retrieving type returned by function using "typeof" operator in gcc | We can get the type returned by function in gcc using the typeof operator as follows:
typeof(container.begin()) i;
Is it possible to do something similar for functions taking some arguments, but not giving them? E.g. when we have function:
MyType foo(int, char, bool, int);
I want to retrieve this "MyType" (probably u... | In C++ the return value's type is not part of the method signature. Even if there is a way to get the return type of a method, you would have to deal with the possibility of getting multiple methods back and not knowing which one went with the return type you want.
|
1,702,929 | 1,703,154 | String initialization with pair of iterators | I'm trying to initialize string with iterators and something like this works:
ifstream fin("tmp.txt");
istream_iterator<char> in_i(fin), eos;
//here eos is 1 over the end
string s(in_i, eos);
but this doesn't:
ifstream fin("tmp.txt");
istream_iterator<char> in_i(fin), eos(fin);
/* here eos is at this same positio... | I don't think you can advance the end iterator to a suitable position: to advance the iterator means to read input, also both iterators are referencing the same stream - therefore advancing one iterator means to advance the second. They both end up referencing the same position in the stream.
Unless you are willing to ... |
1,703,006 | 1,703,285 | 3d Alternative for D3DXSPRITE for billboarding | I am looking to billboard a sun image in my 3d world (directx 9).
Creating a D3DXSPRITE is great in some cases, but it is only a 2d object and can not exist in my "world" as a 3d object. What is an alternative method for billboarding, similar to d3dxsprite? How can I implement it?
The only alternative I have curren... | Taking the center of your object vCenter. The object has a width and height of (w,h).
Firstly you need your camera to billboard vector. This is calculated as vCamToCen = normalise( vCamera - vCenter ).
You then need an appropriate rough up vector. This can be extracted from the view matrix (handily described here, i... |
1,703,011 | 1,718,162 | Data Destruction In C++ | So, for class I'm (constantly re-inventing the wheel) writing a bunch of standard data structures, like Linked Lists and Maps. I've got everything working fine, sort of. Insertion and removal of data works like a charm.
But then main ends, my list is deleted, it calls it's dtor and attempts to delete all data inside ... | Looking at your ListNode class it is obvious that there is an ownership mismatch. It is a good rule of thumb for design that not only should every allocation be matched by a matching de-allocation but that these should be performed by at the same layer in the code or ideally by the same object. The same applies to any ... |
1,703,017 | 1,703,057 | Passing another class amongst instances | I was wondering what is the best practice re. passing (another class) amongst two instances of the same class (lets call this 'Primary'). So, essentially in the constructor for the first, i can initialize the outside instance (lets call this 'Shared') - and then set it to a particular value whilst im processing this cl... | As I understand it:
You have a class A
You have a class B
For all members of class A there is a single instance of class B
You did not mention if any parameters from the A constructor are used to initialize B!
What happens to the parameters of the second A that are used for B?
So we will assume that B is default cons... |
1,703,322 | 1,703,521 | Serialize Strings, ints and floats to character arrays for networking WITHOUT LIBRARIES | I want to transmit data over the network, but I don't want to use any foreign libraries (Standard C/C++ is ok).
for example:
unsigned int x = 123;
char y[3] = {'h', 'i', '\0'};
float z = 1.23f;
I want this in an
char xyz[11];
array.
Note:
To transmit it over network, I need Network Byte order for the unsigned int (ht... | Ah, you want to serialize primitive data types! In principle, there are two approaches: The first one is, that you just grab the internal, in-memory binary representation of the data you want to serialize, reinterpret it as a character, and use that as you representation:
So if you have a:
double d;
you take the addr... |
1,703,452 | 1,703,940 | C++, Boost regex, replace value function of matched value? | Specifically, I have an array of strings called val, and want to replace all instances of "%{n}%" in the input with val[n]. More generally, I want the replace value to be a function of the match value. This is in C++, so I went with Boost, but if another common regex library matches my needs better let me know.
I f... | I don't beleive boost::regex has an easy way to do this. The most straightfoward way that I can think of would be to do a regex_search using the "(%{[0-9]+}%)" pattern and then iterate over the sub-matches in the returned match_results object. You'll need to build a new string by concatenating the text from between eac... |
1,703,649 | 1,703,778 | Adding functionality to a handle wrapper | I have a C++ RAII class for managing Win32 HANDLEs using boost::shared_ptr<> that looks a bit like this:
namespace detail {
struct NoDelete { void operator()( void* ) {}; };
}; // namespace detail
template< typename HANDLE_TYPE, typename HANDLE_DELETER >
class CHandleT
{
public :
explicit CHandleT( HANDLE_TYPE han... | I won't get into discussion on boost::shared_ptr or any smart ptr. And here is a few reasons why, from different angles between the lines, and why smart pointers can always and always be made redundant or beaten out.
Code does seem to emulate the CLR and NT model in which case there are predefined semantics by the OS f... |
1,703,844 | 1,703,966 | Making an object orbit a fixed point in directx? | I am trying to make a very simple object rotate around a fixed point in 3dspace.
Basically my object is created from a single D3DXVECTOR3, which indicates the current position of the object, relative to a single constant point. Lets just say 0,0,0.
I already calculate my angle based on the current in game time of the ... | So are you trying to plot the sun or the moon?
If so then one assumes your celestial object is something like a sphere that has (0,0,0) as its center point.
Probably the easiest way to rotate it into position is to do something like the following
D3DXMATRIX matRot;
D3DXMATRIX matTrans;
D3DXMatrixRotationX( &matRot, ang... |
1,703,941 | 1,704,025 | Initializing array of objects with data from text file | I’m getting system error when I try to compile the code below on Visual C++ 2008 Express. What I’m trying to do is to initialize array of objects with data read from file. I think there is something wrong inside the while loop, because when I initialize these objects manually without the while loop it seems to work. ... | It looks like you are trying to write to bookList[3] in the loop. You will loop through three times filling your array incrementing indexOfArray each time. This will leave indexOfArray at 3 -- your condition as it is written will allow indexOfAray to be incremented to 3. Then if you have a newline after the "14.56" in ... |
1,703,979 | 1,704,309 | Which C++ logical operators do you use: and, or, not and the ilk or C style operators? why? | leisure/curiosity question as implied in the title.
I personally prefer the new operators as to make code more readable in my opinion.
Which ones do use yourself? What is your reason for choosing one over the other one?
also Emacs highlights those operators differently so I get more visual feedback when looking at the... | I won't use the alternative operators as they cause more confusion then clearity in my opinion.
If i see an alphabetical name i expect a namespace, class, variable, function or a function style operator - the common operators divide this intuitively into sequences for me. The alternative style just doesn't fit into the... |
1,704,164 | 1,704,217 | OpenGL / C++ / Qt - Advice needed | I am writing a program in OpenGL and I need some sort of interfacing toolbar. My initial reactions were to use a GUI, then further investigation into C++ I realized that GUI's are dependent on the OS you are using (I am on Windows). Therefore, I decided to use QT to help me.
My Question is if I am taking the best/appro... | Using Qt is coherent for your problem: it provides good integration of OpenGl through the QtOpenGL module.
Derive your display classes from QGLWidget (until Qt 4.8) or from QOpenGLWidget (since Qt 5.4) and implement virtual methods paintGL() etc.
You will have access to the Qt's signal and slot system so that you will... |
1,704,165 | 1,704,358 | Is there a way to improve the speed or efficiency of this lookup? (C/C++) | I have a function I've written to convert from a 64-bit integer to a base 62 string. Originally, I achieved this like so:
char* charset = " 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int charsetLength = strlen(charset);
std::string integerToKey(unsigned long long input)
{
unsigned long long n... | I agree with Rob Walker - you're concentrating on improving performance in the wrong area. The string is the slowest part.
I timed the code (your original is broken, btw) and your original (when fixed) was 44982140 cycles for 100000 lookups and the following code is about 13113670.
const char* charset = "0123456789abc... |
1,704,353 | 1,704,441 | Template lookup in class? | It's hard to get a word for this. Sometimes I see a class like this:
template <typename T>
class Wrapper
{
public:
Wrapper(const T& t) : t_(t) {}
Wrapper(const Wrapper& w) : t_(w.t_) {}
private:
T t_;
}
As far as I can tell this is legitimate code. However, why is the copy constructor allowed to accept a c... | It is explicitly specified by the language standard in 14.6.1/1:
Within the scope of class template,
when the name of the template is
neither qualified nor followed by <,
it is equivalent to the name of the
template followed by the
template-parameters enclosed in <>.
This was re-worded (through the concept... |
1,704,880 | 1,707,081 | Custom system tray icon "balloon tooltips" for Qt? | I know that in the .NET framework there are a handful of alternative third-party controls for normal system tray icon "balloon tips", that allow you to change the colors and add some styling to the balloon.
I was wondering if there is something similar for Qt, which allows for better customization of the look, style, a... | You should have a quick glance at the "Qt Style Sheets" examples in QtAssistant. It provides strong and many ways to alter widgets looks and feel... Maybe you'll find something interesting there !
Otherwise, you could have a look at QSystemTrayIcon & QBalloonTip. Maybe by reimplementing those classes...
Hope this help ... |
1,704,892 | 1,704,903 | Are class variables included in the 7 +- 2 guideline? | I'm wondering in regards to the guideline stating that classes should have around 7 variables +-2, are class variables (class constants) included in this?
Ex:
class Foo
{
static const int SOME_THING;
static const double SOME_OTHER;
static const int BLAH;
int m_ThisVariable;
double m_ThatVariable;
... | Anyone who honestly thinks that you can arbitrarily define how many member variables a class should have has not written a lot of code or are extremely arrogant. I know it just a guideline, but honestly, if the class is well defined, conforms to the general OOP guidelines of single responsibility, and is easy to mainta... |
1,704,895 | 1,705,053 | Access violation when calling external function (C++) from Delphi application | I've an external DLL written in C++. The piece below declares a struct type and a function, which, being given a pointer, fills a variable of this type:
enum LimitType { NoLimit, PotLimit, FixedLimit };
struct SScraperState
{
char title[512];
unsigned int card_common[5];
unsigned int card_play... | The main problem id that C++ CString and Delphi String are incompatible types.
If you want to pass data in this manner, you should use either fixed length character arrays or C-Style null terminated strings (PChar in Delphi).
C++ would be something like:
char Dealer[100][10];
Please edit if wrong - it been many years... |
1,705,147 | 1,705,166 | Struct initialization of the C/C++ programming language? | I could do struct initialization with code:
struct struct_type_id struct_name_id = { value1, value2, value3 };
but could not with:
struct struct_type_id struct_name_id;
struct_name_id = { value1, value2, value3 };
why I could do it with the former,but could not with the latter with gcc,g++,vc2008,vc6?In other words,w... | The first statement creates a variable initialized to the given values, i.e., these values are built in memory and stored directly in the program executable in that variable address (for globals) or ready for memory copy (for stack variables).
The second statement of the second block is very different. Although it look... |
1,705,247 | 1,705,259 | A case where named constants are not needed over magic numbers | Obviously the point of using named constants over magic numbers is for code clarity and for not having to go through code changing numbers throughout.
However, what do you do if you just have a number used just once in a function? Say you have a short member function that uses an object's velocity (which we'll say won'... | Just move it up:
void do_something(void)
{
const float InitialVelocity = 5.0f;
something = InitialVelocity;
// etc.
}
|
1,705,374 | 1,723,192 | How to capture a string into variable in a recursive function? | I tried to print all the possible combination of members of several vectors. Why
the function below doesn't return the string as I expected?
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
string EnumAll(const vector<vector<string> > &allVecs, size_t vecIndex, string
... | Here is an alternate solution. This does not expect you to pass anything but the initial vectors:
int resultSize( vector< vector<string> > vector ){
int x=1;
for( int i=0;i<vector.size(); i++ )
x *= vector[i].size();
return x;
}
vector<string> enumAll(const vector< vector<string> > allVecs )
{
//__ASSERT( allVec... |
1,705,582 | 1,705,603 | Private member function that takes a pointer to a private member in the same class | How can I do this? (The following code does NOT work, but I hope it explains the idea.)
class MyClass
{
....
private:
int ToBeCalled(int a, char* b);
typedef (MyClass::*FuncSig)(int a, char* b);
int Caller(FuncSig *func, char* some_string);
}
I want to call Caller in some way like:
Caller(ToB... | You're most of the way there. You're missing the return type from the typedef, it should be
typedef int (MyClass::*FuncSig)(int, char*);
Now, you just need to use it properly:
int Caller(FuncSig func, int a, char* some_string)
{
return (this->*func)(a, some_string);
}
You want to pass around plain FuncSig instan... |
1,705,614 | 1,705,622 | Visual C++ saying void function needs to return a value | Visual C++ is saying my void function needs a return value
I compiled this on my mac, and it worked perfectly, but now I am trying to compile this with Visual c++ (using windows 7)
Heres the build log:
Command Lines Creating temporary file
"c:\Users\Jonathan\Documents\Visual
Studio
2008\Projects\magicsquare\Debu... | Your function is returning a (void **) which is a pointer to a void pointer. To make a void function simply declare it as:
void check(int** matrix, int size);
Your original code will compile with a warning in C but not in C++. Try this in Visual Studio 2008. Rename your file extension to .c instead of .cpp to force C ... |
1,705,724 | 1,705,754 | For C/C++, When is it beneficial not to use Object Oriented Programming? | I find myself always trying to fit everything into the OOP methodology, when I'm coding in C/C++. But I realize that I don't always have to force everything into this mold. What are some pros/cons for using the OOP methodology versus not? I'm more interested in the pros/cons of NOT using OOP (for example, are there opt... | Of course it's very easy to explain a million reasons why OOP is a good thing. These include: design patterns, abstraction, encapsulation, modularity, polymorphism, and inheritance.
When not to use OOP:
Putting square pegs in round holes: Don't wrap everything in classes when they don't need to be. Sometimes the... |
1,706,188 | 1,706,307 | query about a multithreading program | this might a simple query.
when we are creating a thread we are passing the (void *)t as an argument to a function PrintHello.we are copying the value in the pointer threadid(typacasting it to long) in tid which is a long variable again.i am confused with the parameter passing.
is this a pass by reference or pass by v... | What you are doing is pass by value. It is fine as long as sizeof(T) <= sizeof(void*) for the type T you are trying to pass.
If that is not the case, you should to create a T on the heap as it might be out of scope when the created thread tries to access it:
T* t = new T(someValue);
rc = pthread_create(&threads[t], NU... |
1,706,207 | 1,717,945 | CUrl PUT with xml data | I'm facing a problem with curl as I am unable to issue a PUT request with inline XML data, I'm not sure how its done but I hade a couple of goes on it with different techniques. First I tried using the CURLOPT_UPLOAD as its the default CURL option for PUT and tried to append the xml data manually:
typedef map<strin... | When using CURLOPT_UPLOAD, you are appending the XML to the headers of the request rather then to the body where it belongs. You need to use CURLOPT_READDATA (with CURLOPT_READFUNCTION if your XML is not in a file) to provide the XML data when curl asks for it, and also use CURLOPT_INFILESIZE/CURLOPT_INFILESIZE_LARGE ... |
1,706,346 | 19,004,720 | __FILE__ macro manipulation handling at compile time | One of the issues I have had in porting some stuff from Solaris to Linux is that the Solaris compiler expands the macro __FILE__ during preprocessing to the file name (e.g. MyFile.cpp) whereas gcc on Linux expandeds out to the full path (e.g. /home/user/MyFile.cpp). This can be reasonably easily resolved using basename... | Using C++11, you have a couple of options. Let's first define:
constexpr int32_t basename_index (const char * const path, const int32_t index = 0, const int32_t slash_index = -1)
{
return path [index]
? ( path [index] == '/'
? basename_index (path, index + 1, index)
: basename_in... |
1,706,675 | 1,707,039 | file scope and static floats | I've run into an interesting problem in an AI project of mine. I'm trying to format some debug text and something strange is happening. Here's a block of code:
float ratio = 1.0f / TIME_MOD;
TIME_MOD is a static float, declared in a separate file. This value is modified based off of user input in another class ... | I think there is some confusion with the word "static". We have a keyword static that does different things in different contexts and we use the word "static" to name one of three classes of "storage durations". In some contexts static does not control the storage duration of objects but only "linkage" which is probabl... |
1,706,762 | 1,707,671 | Which VC++ runtime version do I choose - static or dynamic? | I'm developing a 64-bit in-proc VC++ ATL COM server that basically just redirects all calls to an out-proc COM server. So my COM server basically does nothing.
Initially it used the C++ runtime in a DLL (/MD compiler switch). I've noticed that when I deploy it on a clean 64-bit Win2k3 regsvr32 fails with an error: Load... | As far as I know the Static runtime is deprecated in VS since VS2005.
The problem is that the Visual C Runtime is a side by side dll. That is it must be loaded from the c:\windows\winsxs directory. This is why placing it in the same directory is no longer works.
The correct solution is to install the correct CRT redi... |
1,706,776 | 1,706,780 | Avoid std::bad_alloc. new should return a NULL pointer | I port a middle-sized application from C to C++. It doesn't deal anywhere with exceptions, and that shouldn't change.
My (wrong!) understanding of C++ was (until I learned it the hard way yesterday) that the (default) new operator returns a NULL pointer in case of an allocation problem. However, that was only true unti... | You could overload operator new:
#include <vector>
void *operator new(size_t pAmount) // throw (std::bad_alloc)
{
// just forward to the default no-throwing version.
return ::operator new(pAmount, std::nothrow);
}
int main(void)
{
typedef std::vector<int> container;
container v;
v.reserve(v.max_s... |
1,707,062 | 1,707,672 | How to stop application from executing | I am working on a project to prevent applications from being launched from removable devices.
Does anyone out there know how i can do this? Preferrably in C++ on the Windows platform.
My aim is to prevent execution of the exe file even if the user double clicks it or even if he tries to launch it from the command line... | Assuming that you wish to stop ANY process launching from a removable drive, this seems to be an application for a shell hook. I wrote the following code over the last half-hour, and it seems to test out OK. Bear in mind that writing a hook is a non-trivial process, and a global hook requires that a DLL be written. Thi... |
1,707,164 | 1,719,116 | passing pointers or integral types via performSelector | I am mixing Objective-C parts into a C++ project (please don't argue about that, its cross-platform).
I now want to invoke some C++ functions or methods on the correct thread (i.e. the main thread) in a cocoa enviroment.
My current approach is passing function pointers to an objective-c instance (derived from NSObject)... | As answered by smorgan here, NSValue is designed as a container for scalar C & Objective-C types:
- (void)test:(NSValue*)nv
{
FnPtr fn = [nv pointerValue];
// ...
}
// usage:
NSValue* nv = [NSValue valueWithPointer:fn];
[someInstance performSelector:@selector(test:) withObject:nv];
|
1,707,302 | 1,707,513 | Ensuring pointer is not deleted | I've stumbled onto something I can't figure out, so I think I'm missing something in the greater C++ picture.
In short, my question is: how to keep a mutable, non-deletable, possibly NULL instance of an object in a class.
The longer version is:
I have the following scenario: a bunch of classes (which I can change sligh... | I've traditionally seen these kind of scenarios implemented using a shared_ptr/weak_ptr combo. See here.
The owner/deleter would get a
boost::shared_ptr<T>
Your class would get a
boost::weak_ptr<T>
To reassign the weak ptr, simply reassign the pointer:
void MyClass::Reassign(boost::weak_ptr<T> tPtr)
{
m_tPtr = ... |
1,707,575 | 1,707,619 | C++: static function wrapper that routes to member function? | I've tried all sorts of design approaches to solve this problem, but I just can't seem to get it right.
I need to expose some static functions to use as callback function to a C lib. However, I want the actual implementation to be non-static, so I can use virtual functions and reuse code in a base class. Such as:
class... | Are any of the parameters passed to the callback function user defined? Is there any way you can attach a user defined value to data passed to these callbacks? I remember when I implemented a wrapper library for Win32 windows I used SetWindowLong() to attach a this pointer to the window handle which could be later retr... |
1,708,222 | 1,723,864 | How do I get the PowerBuilder graphicobject for a given HWND handle? | In my (PowerBuilder) application, I'd like to be able to determine the graphicobject object which corresponds to a given window handle.
Simply iterating over the Control[] array and comparing the value returned by the Handle() function for each of the child controls doesn't work, since not all objects in my application... | Is it a requirement to determine the object from the handle, or do you just want to identify an object, for example to know where the code you need to modify is? I made a tool that does the latter, but it uses object focus, rather than window handles.
(added 2010-06-21) For windows that aren't children of the main win... |
1,708,317 | 1,708,759 | CertCreateCertificateContext returns ASN1 bad tag value met | I'm loading a .p7b certificate file into memory and then calling CertCreateCertificateContext on it, but it fails with the error "ASN1 bad tag value met.".
The call look like this:
m_hContext = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pbCertEncoded, dwCertEncodedLen);
This returns NULL and ... | Try to open your certificate by some asn.1 editor.
Probably your certificate has been exported incorrectly or size of the certificate you pass to the api is wrong... Rather the second one option (incorrect cert construction or passing).
I found here the info that the encoding you try to use is not fully supported (see ... |
1,708,458 | 1,708,845 | Template metaprogram converting type to unique number | I just started playing with metaprogramming and I am working on different tasks just to explore the domain. One of these was to generate a unique integer and map it to type, like below:
int myInt = TypeInt<AClass>::value;
Where value should be a compile time constant, which in turn may be used further in meta programs... | The closest I've come so far is being able to keep a list of types while tracking the distance back to the base (giving a unique value). Note the "position" here will be unique to your type if you track things correctly (see the main for the example)
template <class Prev, class This>
class TypeList
{
public:
enum
... |
1,708,867 | 1,709,065 | check type of element in stl container - c++ | how can i get the type of the elements that are held by a STL container?
| For containers in general it will be X::value_type. For associative containers it will be X::mapped_type (X::value_type corresponds to pair<const Key,T>). It is according to Chapter 23 of C++ Standard.
To check that types are equal you could use boost::is_same. And since C++11 — std::is_same.
|
1,709,093 | 1,725,141 | Intercepting messages from a child of a child with MFC | I have a CListCtrl class and at the moment when a user selects one of the sub items I am displaying a CComboBox over the subitem which the user can then make a selection from.
However I have a problem. When the user has made a selection i need the combo box to disappear (ie intercept CBN_SELCHANGE). The problem is th... | You can subclass CComboBox such that it will handle CBN_CLOSEUP message.
Your custom Combo will know about the manager i.e. the object that created it in the first place and will have to destroy it upon close up (top level window or whatever, should be provided as an argument to your custom combobox constructor)...
So ... |
1,709,194 | 1,715,756 | MySQL/C++ and Prepared Statements: setInt always 0 | I'm using the MySQL Connector/C++ library to insert values into a database table. I'm following the examples at
http://dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html
almost exactly. However, I can't seem to get prepared statements to work with value placeholders.
sql::mysql::MySQL_Driver* driver = s... | Recompiling the C++ connector from source fixed this problem.
Probably a compiler setting in their pre-built binary that didn't agree with my project. I will talk to MySQL about this.
Thanks for the assistance.
|
1,709,478 | 1,709,553 | Overloading *(iterator + n) and *(n + iterator) in a C++ iterator class? | (Note: I'm writing this project for learning only; comments about it being redundant are... uh, redundant. ;)
I'm trying to implement a random access iterator, but I've found very little literature on the subject, so I'm going by trial and error combined with Wikpedias list of operator overload prototypes.
It's worked ... | First, you need an operator *(void) const.
[Edit: based on your existing operator, the following should do:
char &operator *(void) const {
// bounds checking
return *p;
}
]
Second, you need an operator+(int, exscape::string::iterator). A fairly common way to write this would be (in the iterator class):
friend ... |
1,709,574 | 1,711,984 | Combine multiple videos into one | I have three videos:
a lecture that was filmed with a video camera
a video of the desktop capture of the computer used in the lecture
and the video of the whiteboard
I want to create a final video with those three components taking up a certain region of the screen.
Is open-source software that would allow me to do t... | It can be done with ffmpeg; I've done it myself. That said, it is technically complex. That said, again, it is what any other software you might use is going to do in its core essence.
The process works like this:
Demux audio from source 1 to raw wav
Demux audio from source 2
Demux audio from source 3
Demux vi... |
1,709,718 | 1,710,287 | Am I using a global state here, is there any better way to do this? | I am modifying some legacy code. I have an Object which has a method, lets say doSomething(). This method throws an exception when a particular assertion fails. But due to new requirement, on certain scenarios it is okay to not throw the exception and proceed with the method.
Now I am not calling this method directly ... | You certainly should be doing this with a function argument, not a member - the choice of whether to ignore the checks is a property of the function invocation, not of the object.
Using persistent state to hold a temporary condition will give you two main problems:
exception safety - if the function throws an unhandle... |
1,709,941 | 1,709,972 | In what order are the aggregated classes deleted? | Let's say I have a basic class A that aggregate B and C:
class A
{
B _b;
C _c;
}
in what order are _b and _c going to be deleted?
I've read somewhere that it's the reverse order of their allocation.
So I guess in this little example _c is deleted before _b, right?
Now if I have a A constructor that lo... | They are destroyed (not deleted) in the reverse order that they were created. It is this that also requires that regardless of how the constructor is written that all the members must be constructed in a consistent order. If each constructor could define the order that the members were constructed, each class instanc... |
1,710,118 | 1,710,174 | Adding folders to the sidebar of a CFileDialog | Is there any way to add folders to the sidebar in an MFC CFileDialog? (You know, the bar with shortcuts to "Recent Documents", "My Documents", etc. on the left side of the dialog.) Note that I do not mean that I want the user to have to hack the registry or something to permanently add folders to the sidebar system-wid... | Since Vista there is the IFileDialog which have the AddPlace(...) method.
You will need to write a wrapper that will use CFileDialog (On XP) or IFileDialog (Vista and up).
|
1,710,305 | 1,718,101 | Determine thread which holds the lock on file | I know there is no WINAPI which would do it, but if a thread is hung and holds an open handle of file. how do we determine the thread id and Terminate it within our processes.
I'm not talking about releasing file locks in other processes but within my own process.
it could also be possible that thread has crashed / ter... | You cannot determine which thread holds an open handle to a file. Nearly all kernel handles, including file handles, are not associated with a thread but only with a process (mutexes are an exception - they have a concept of an owning thread.)
Suppose I have the following code. Which thread "owns" the file handle?
vo... |
1,710,307 | 1,710,453 | How to add a .o on a static library with Eclipse? | I have a .h and a .o that I need to add to a static library in Eclipse. I'm able to add it to an application with the Linker options, but for a static library, I haven't found where to add it in the settings.
| G'day,
I know it sounds clunky, but you might have to come out of Eclipse and use ar directly. For example:
ar -rv my_lib.a new_obj.o
ranlib
Running ranlib is probably not required anymore with more recent implementations of ar but it's best to run it anyway to make sure that the table has been updated.
HTH
|
1,710,376 | 1,710,398 | Convert files of any types to a file with c strings | Please suggest a small command-line utility (for Windows) to convert files from particular directory to a valid c file. Maybe it can be done just with batch commands?
The resulting file should look like this:
static const unsigned char some_file[] = {
/* some_file.html */
0x2f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x7... | Bin2h will do this.
Bin2h - Win32 binary to C header file
converter
A Win32 command-line utility for
converting a binary file into a C
header file, representing the contents
of that file as a block of data.
I don't believe the input file has to be a binary file.
|
1,710,447 | 1,710,462 | String in scientific notation C++ to double conversion | I've got a database filled up with doubles like the following one:
1.60000000000000000000000000000000000e+01
Does anybody know how to convert a number like that to a double in C++?
Is there a "standard" way to do this type of things? Or do I have to roll my own function?
Right now I'm doing sth like this:
#include <s... | Something like this? This would be the "C++" way of doing it...
#include <sstream>
using namespace std;
// ...
string s = "1.60000000000000000000000000000000000e+01";
istringstream os(s);
double d;
os >> d;
cout << d << endl;
Prints 16.
|
1,710,660 | 1,710,819 | Know any good c++ support vector machine (SVM) libraries? | Do you know of any good c++ svm libraries out there
I tried libsvm http://www.csie.ntu.edu.tw/~cjlin/libsvm/ but so far I'm not flabbergasted.
I have also heard of SVMLight and TinySVM. Have you tried them ? Any new players ?
Thanks !
|
SVMTorch (support vector machines for large-scale regression problems) implemented in the torch machine learning library.
mySVM - based on the optimization algorithm of SVM-Light.
A comprehensive list of SVM libraries can be found here.
|
1,710,828 | 1,711,559 | C#: problem loading C++ DLL | In my code, I can load "MessageBoxA" from user32.dll and use it, but if I try to load and use a function from my DLL, I get a crash.
My C# code:
[DllImport("SimpleDLL.dll")]
static extern int mymean(int a, int b, int c);
[DllImport("user32.dll")]
static extern int MessageBoxA(int hWnd,
... | Turns out my C# app was 64-bit (which is C# visual studio default) and my C++ DLL was 32-bit (which is C++ visual studio default).
Thanks for the tip to check the exception type, it was a badimageformatexception.
Sorry - total C# newbie!
|
1,711,058 | 1,711,090 | sizeof(*this) in header only constructor implementation | Whilst the 'standards' are to prefer a sizeof(typename), are there any instances where the sizeof(*this) is more error-prone or somehow undesirable?
I cannot see any at the first glance, but if yes, why with a short explanation would be helpful.
| The only reason I can think of to avoid sizeof(*this) is that it could be misunderstood as the size of the actual object (e.g., a derived class).
|
1,711,161 | 1,711,197 | Destructor of a concrete class | Guideline #4 link text, states:
A base class destructor should be
either public and virtual, or
protected and nonvirtual.
Probably I'm missing something, but what if I just create a concrete class, that is not designed to be used as base class.
Should I declare it's destructor public and virtual? By this I'm impl... | The link text specifically says"A base class destructor should be"...
The guidelines are only meant for a class which is designed to be used as a base class. If you are making a single, concrete class that will not be used as a base class, you should leave the public constructor non-virtual.
|
1,711,426 | 1,722,766 | Design methods for multiple serialization targets/formats (not versions) | Whether as members, whether perhaps static, separate namespaces, via friend-s, via overloads even, or any other C++ language feature...
When facing the problem of supporting multiple/varying formats, maybe protocols or any other kind of targets for your types, what was the most flexible and maintainable approach?
Were... | Reading through the already posted responses, I can only agree with a middle-tier approach.
Basically, in your original problem you have 2 distinct hierarchies:
n classes
m protocols
The naive use of a Visitor pattern (as much as I like it) will only lead to n*m methods... which is really gross and a gateway towards ... |
1,711,490 | 1,961,432 | Returning a C++ class to Java via JNI | I'm currently using both C++ and Java in a project and I'd like to be able to send an object which is contained in C++ to my Java interface in order to modify it via a GUI and then send the modification back in C++.
So far I've been returning either nothing, an int or a boolean to Java via the JNI interface. This time ... | Here's the solution I opted to use:
First, I would create a similar object in Java. Then, from C++ I would instanciate it and pass it all the values.
(C++)
clazz = env->FindClass("java/lang/Integer");
jmethodID method = env->GetMethodID(clazz, "<init>", "(I)V");
return env->NewObject(clazz, method, (jint)anInteger);
B... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.