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,443,543 | 3,443,590 | Chaining methods and temporary variables, please clarify | Greetings, everyone!
I have a class that receives a pointer to a "circle" (for example) and then adjusts its attributes via some "chaining" methods. Something like this:
class CCircleSetter
{
public:
explicit CCircleSetter( CCirclePtr circle ) : m_circle(circle)
{
}
CCircleSetter & Radius( int radius )
... | No, that's fine in this very specific case, because the temporary will be destroyed AFTER the whole line will execute, but in general is very bad to hold references to temporaries.
|
3,443,544 | 3,443,579 | What are some *slick* UI libraries/frameworks/tools for, non-MFC, Win32 C++ apps? | What is a really good Windows, C++, UI library, framework, or tool that will allow me to very simply and easily add a slick look & feel to my native C++ win32 application?
Also;
Slick means skinnable with window background images, fancy buttons, shadows, all that jazz.
This is non-MFC
Supporting Windows XP and beyond
... | Qt has all you are asking for.
|
3,443,660 | 3,443,674 | Is there any way to set parameter default as function of previous parameter? [C++] | I assume not, but I just wanted to check - is there any way in C++ to do something like the following? Obviously when I try the below I get a scope-based error about bar.
void foo(Bar bar, int test = bar.testInt) { ... }
| If there is a value of test that is invalid, you could detect that:
void foo(Bar bar, int test = -1) { //assuming -1 is invalid
if(test == -1) test = bar.testInt;
//...
}
If not, you could always use overloaded functions:
void foo(Bar bar, int test) {
//...
}
void foo(Bar bar) {
foo(bar, bar.testInt)... |
3,443,751 | 3,443,774 | Converting a set of booleans to a number | This is the code I am going to use to take a set of three booleans and convert it into an int for a switch statement:
int bits = 0;
bool a = true, b = false, c = true; // 101 = 5
bits = bits | a << 2;
bits = bits | b << 1;
bits = bits | c;
cout << bits;
I have eight cases based on the combined state of these three ... | If you are using C++, you could use bitset<N>.
|
3,443,836 | 3,443,931 | sockaddr_in6 not declared? | I'm trying to port an ipv4 server/client to ipv6, but the compiler says SOCKADDR_IN6 is not declared in the scope. SOCKADDR_IN is declared but not SOCKADDR_IN6. <Winsock2.h> is included.
Any one have any ideas why it would be undeclared?
| Microsoft's documentation for sockaddr_in6 says that it is defined in the ws2tcpip.h header, probably you need to include that.
On Linux you'd need different includes, sys/socket.h and netinet/in.h.
|
3,443,881 | 3,443,895 | HELP! will this code cause memory fault after C++ object is out of scope? (STL problem) | I just came across a piece of code written by my ex-colleague few years ago. Honestly, I'm not an C++ expert, so I am seeking help.
The code looks like this:
std::vector<OBJ> objects;
void initobjs()
{
for (int i=0; i<10; i++)
{
OBJ obj;
obj.type=i;
obj.len=16;
objects.push_ba... | Your concern can be made even more local: obj ends at the bottom of the for-loop.
That said, a container makes a copy of its argument*, and does not store any reference or pointer to the "original" value.
*Hence all containers require their elements be copy-constructible and copy-assignable.
|
3,444,057 | 3,444,065 | vector<T>::iterator - invalid? |
Possible Duplicate:
g++ “is not a type” error
The following does not compile:
1 template<typename T>
2 void foo(std::vector<T>::iterator & i)
3 {
4 }
On Visual Studio, I get the following errors:
>(2) error C2065: 'i' : undeclared identifier
>(4) warning C4346: 'std::vector<_Tp>::iterator' : dependen... | std::vector<T>::iterator is a type that is dependent on a template parameter, namely T. Therefore, you should prefix with it typename:
template<typename T>
void foo(typename std::vector<T>::iterator & i)
{
}
Here's an explanation.
|
3,444,106 | 3,444,194 | Static function pointer member in a class template | How can I use a static function pointer member in my class template?
I'm working with C++ in Visual Studio, and my code looks similar to the following:
template<typename T>
class ClassTemplate
{
public:
static T* CallIt() { return ClassTemplate<T>::mFunctionPointer(); }
private:
static T* (*mFunctionPointer)()... | Change the position of the * so that it's
template<typename T>
T* (*ClassTemplate<T>::mFunctionPointer)() = NULL;
otherwise you are trying to define a namespace-level variable mFunctionPointer as a pointer-to-member of class ClassTemplate.
|
3,444,160 | 3,444,251 | Vector declaration type in c++ | Please can anybody explain to me what this means?
vector<int> myvector(4,99);
| A a(x,y); creates an object called a, calling a constructor of A with two parameters matching the types of x and y, or any convertible types.
So this:
vector<int> myvector(4,99);
Matches this constructor:
explicit vector( size_type num, const TYPE& val = TYPE() );
// `TYPE` is a `typedef` assigned to the parametrized... |
3,444,312 | 3,445,026 | How to execute an untrusted Lua file in its own environment from the C API | I want to execute an untrusted .lua file in its own environment by calling lua_setfenv() so that it cannot affect any of my code.
The documentation for that function though only explains how to call a function, not how to execute a file.
Currently to run the file I use:
int error = luaL_loadfile(mState, path.c_str()) |... | See the discussion at the Lua User's Wiki of sandboxing, and the more general topic of script security. There are a number of subtle and not so subtle issues with this kind of thing. It can be done, but protecting against code such as for i=1,1e39 do end requires more than just restricting what functions are available ... |
3,444,403 | 3,444,474 | Winsock - stop accepting new connections yet keep comm with existing connections | I have a Winsock based server application which uses Windows Winsock I/O Completion Ports.
As such, each connection accepted is associated with the listening socket to start receiving notifications (read, write, close etc').
The listening socket has a backlog of 100 pending connections.
All is good.
At some point I wan... | You can simply close the listening socket. The accepted connections have their own sockets and they will not be affected by closing the listening socket.
For example, in the Microsoft documentation there is a sample server application where basic socket usage is demonstrated. There the listening socket is closed before... |
3,444,798 | 3,444,998 | c++ gdi drawing ellipse problem | ok i can draw ellipse the problem is this, im trying to draw one ellipse but change its x value to different one. like this i draw one ellipse and the x value is 1 after ten seconds i want it the x value to be 10 but it seems that im creating new ellipse with x value 10. here is my code
while(sd==1)//sd equal 1
{
... | If you want to make an animation you are better setting a timer.
Using InvalidateRect as a way to generate WM_PAINTs seems overkill, it will do much more thant that. Instead you can draw directly in OnTimer call, since it is outside a WM_PAINT you will need to get a device context with GetDC.
For example if you can ha... |
3,445,032 | 3,445,218 | Creating a zip archive in C++ | Is there a simple way to create a zip archive in C++? I'm writing a GPL app and I looked in to minizip but it seems too complicated. Is there a simple library to do this? I already have the files on the disk, I just want to make a zip from them.
| Use zlib as a compression library in your C++ app (zlib.net). I've used it before and I believe it's the best option. If you look around you may also find some C++ wrappers that simplify the code.
|
3,445,312 | 3,445,371 | swprintf and vswprintf not declared? | I am trying to compile Botan on Windows with MinGW, and am receiving the following error during compilation:
c:\qt\2010.04\mingw\bin\../lib/gcc/mingw32/4.4.0/include/c++/cwchar:159: error:
'::swprintf' has not been declared
c:\qt\2010.04\mingw\bin\../lib/gcc/mingw32/4.4.0/include/c++/cwchar:166: error:
'::vswprintf' ha... | Try putting in
#undef __STRICT_ANSI__
before including stdio.h
|
3,445,348 | 3,445,357 | C++ Template Default Constructor | I got a little problem with templates:
template <typename T>
T Func(){
std::string somestr = "";
// somestr = ...
if (somestr != ""){
return boost::lexical_cast<T>(somestr);
}
else{
T ret; // warning: "ret may be uninitialized in this function"
return ret;
}
}
If this f... | ret might be uninitialized because T might be a POD type or another type that has no user-declared constructors.
You can invoke the default constructor (and value-initialize any POD type object) like so:
T ret = T();
return ret;
or, more succinctly,
return T();
This assumes that T is default-constructible. If you ma... |
3,445,460 | 3,445,513 | Need help creating a 24 minute day clock | I need help with some code that i am writing for a small text rpg. Its basically a clock that simulates a day, which will be 24 minutes instead of 24 hours. 1 second will equal one minute, and 1 minute will equal one hour. The clock will start from 12:00 and go to 12:00. I need ideas on how to write this code.
This is ... | Just get the current time, convert to seconds, then multiply by sixty. Finally, convert back.
Example:
myrealtime_s = hours*60*60+minutes*60+seconds;
myfaketime_s = myrealtime_s*60;
myfaketime_seconds = myfaketime_s % 60;
myfaketime_minutes = (myfaketime_s/60) % 60;
myfaketime_hours = (myfaketime_s/(60*60)) % 24;
my... |
3,445,595 | 3,445,643 | How does a smaller pipe speed up data flow? | Have a 1MB pipe:
if (0 == CreatePipe(&hRead,&hWrite,0,1024*1024))
{
printf("CreatePipe failed\n");
return success;
}
Sending 4000 bytes at a time (bytesReq = 4000)
while ((bytesReq = (FileSize - offset)) != 0)
{
//Send data to Decoder.cpp thread, converting to human readable CSV
if ( (0 == WriteFile(hWrite,
... | Less waiting.
If the pipe buffer is too big, then one process writes all the data and closes it's end of the pipe before the second process even begins.
When the pipe is too big, the processes are executed serially.
|
3,445,693 | 3,445,716 | Is it safe to return local CStringW to the caller? | I have a function defined a local variable typed in CStringW, is it safe to return this object to the caller by value, not by reference?
| Yes, it should be ok. CString internally uses a buffer with reference counting and does copy-on-write, so that when you create a copy of CString and then destroy the original object, everything should "just work".
|
3,446,004 | 3,446,094 | GCC Inline-assembly: call dword ptr | If I have the following code in Windows VC++:
DWORD somevar = 0x12345678;
_asm call dword ptr [somevar]
How can I make the same thing in GCC inline-assembly, with AT&T syntax?
__asm__ __volatile__ (
"call dword ptr [%%edx]" : :
"d" (somevar)
);
I've tried something like this, but it generates an "junk" error.... | You don't use DWORD PTR or anything like this with the AT&T assembler syntax. The operand length is usually taken from the register name (there's an option of provide a suffix with the mnemonic), which in turn comes from the size of the C operand you give to asm(). This is a very nice property of the inline assembler b... |
3,446,075 | 3,446,889 | c++ gdi animation not working | im trying to create ball animation using gdi but i can't get it working.
i created a ball using this
Graphics graphics(hdc);
Pen pen(Color(255, 0, 0, 255));
graphics.DrawEllipse(&pen, sf , 0, 10, 10);
i have while loop that loops and adds 1 to sf value basicly like this sf++;
than i try to repaint the windo... | In order to achieve animation I would suggest you use a timer. For example:
int OnCreate(HWND window, WPARAM wParam, LPARAM lParam)
{
SetTimer(window, TIMER_ID, 1000, 0);
return 0;
}
now window will receive WM_TIMER messages every second (1000ms). You should handle them:
int OnTimer(HWND window, WPARAM wParam, L... |
3,446,182 | 3,446,225 | Parameters assignment with default values for a function | I have thread spawning function which accepts many parameters which have default values in the declaration.
int spawn( funcptr func, void arg = 0,int grp_id = 1,const charthreadname);
I want to initialize first parameter func and the last parameter thread name and remaining variables assigned their default values.
spaw... | You can't.
Other languages support things like spawn(myfunc, , , "MyThread"), but not C++.
Instead, just overload it to your liking:
inline int spawn( funcptr func, const char*threadname) {
return spawn(func, 0, 1, threadname);
}
|
3,446,281 | 3,446,293 | free c++ compiler for mac not using xcode | Are there any free c++ compilers for macs that do not need xcode?
| If you install the Developer Tools (which include Xcode), you get GCC installed as well. You can use it from the command line.
gcc -o myprogram main.cpp
|
3,446,409 | 3,446,437 | vector with constant size | I am looking for a C++ data type similar to std::vector but without the overhead related to dynamic resizing. The size of the container will remain constant over its lifetime. I considered using boost::array, however, that is not appropriate because it requires the size of the array to be known at compile time, which i... | Measure if the dynamic resizing has really any performance impact before using anything non-standard.
Tip: With vector.reserve there will never be any array-reallocation.
|
3,446,422 | 3,446,427 | free c++ compiler for mac with open source license | Are there any free c++ compilers for macs whose license is open source?
(basically one of these http://www.opensource.org/licenses/category)
I don't have the DVD that came with my current OS, and it won't run the version of xcode I already have.
| GCC and Clang+LLVM are both open source C++ compilers.
|
3,446,447 | 3,446,807 | how to get median value from sorted map | I am using a std::map. Sometimes I will do an operation like: finding the median value of all items. e.g
if I add
1 "s"
2 "sdf"
3 "sdfb"
4 "njw"
5 "loo"
then the median is 3.
Is there some solution without iterating over half the items in the map?
| I think you can solve the problem by using two std::map. One for smaller half of items (mapL) and second for the other half (mapU). When you have insert operation. It will be either case:
add item to mapU and move smallest element to mapL
add item to mapL and move greatest element to mapU
In case the maps have differ... |
3,446,856 | 3,446,871 | Can I write an interface for a template class in C++ | I have an interface and a couple of implementations of a class that stores serialized objects. I'd like to make the implementation classes into template classes so I can use them with more than one type of object, but I'm getting compiler errors.
#include <iostream>
template<typename T>
class Interface{
public:
... | template<typename T>
class Implementation : public Interface<T> {
// ^^^
|
3,446,955 | 3,447,396 | "real time" update a Qt TextView | I have a Qt application with an embedded script/jit. Now I'd like to receive the output from the script on an QTextEdit (more specific QPlainTextEdit). For this purpose callbacks are being issued. The problem I'm facing is that whatever I try the output to the TextEdit is either delayed until the script has finished or... | Just to sketch a soluting using threads, which I have used numerous times for logging purposes and which works as desired:
Define your thread class:
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QObject *parent=0) : QThread(parent) {}
signals:
void signalLogMessage(const QString &logMessage);
...
}... |
3,446,957 | 3,446,992 | Is std::swap atomic in C++0x due to rvalue references? | Since we have rvalue references in C++0x it seems to me that it should be possible to implement std::swap as an atomic operation with CAS. Is this the case in the new standard, and if not why?
| It is not atomic. Atomic operations are not cheap and 99% of the time you do not need the atomicity. There are (IIRC) some other means to get atomic operations but std::swap() is not one of them.
|
3,447,165 | 3,448,894 | How to find active QMainWindow instance? | Greetings all,
In my QT Application I have several QMainWindow instances.
I keep track of opended QWindow objects in a Application Context object;
At onepoint ,when a Menu item is clicked , I want to go through all this QWindows and check which Window is active and
execute some operations.
Please refer to following cod... | If you have multiple main windows, I think you also have multiple menus? If so, I would associate the slot reacting to the menu action with the mainwindow, either make it a slot of the mainwindow or a slot of an object that knows the corresponding main window.
You can also identify the active window before the messageb... |
3,447,183 | 3,486,606 | MultiByteToWideChar API changes on Vista | I want an option to convert a string to wide string with two different behaviors:
Ignore illegal characters
Abort conversion if illegal character occurs:
On Windows XP I could do this:
bool ignore_illegal; // input
DWORD flags = ignore_illegal ? 0 : MB_ERR_INVALID_CHARS;
SetLastError(0);
int res = MultiByteToWideC... | I think what it does is replacing illegal code units by the replacement character (U+FFFD), as mandated by the Unicode standard. The following code
#define STRICT
#define UNICODE
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <iomanip>
void test(boo... |
3,447,487 | 3,447,516 | Atomically std::vector::push_back() and return index | I need to create a function which appends a value to a vector and returns the index of the value that was just appended.
Example:
int append(std::vector<int>& numbers, int number){
int retval = numbers.size();
// what if some other thread calls push_back(number) in between these calls?
numbers.push_back(number);
... | std::vector has no built in thread support. You could use boost::mutex to extend it:
int append(std::vector<int>& numbers, int number){
boost::mutex::scoped_lock slock( my_lock );
int retval = numbers.size();
numbers.push_back(number);
return retval;
}
You need to protect any read/write operation in such way. ... |
3,447,541 | 3,447,559 | Function Definition within Header File because Function is used from different Projects | Is it appropriate to give the Definition of a small Function -- which is used by two projects and has up to 10 lines of code -- into a Headerfile?
It is because i can put the Headerfile into the include-Directory, which is shared by both Projects. Otherwise i have to maintain the same cpp-Files in each Project Source D... | You can put it in a header, but you need to define it as inline:
inline void f() {
// stuff
}
This will prevent multiple-definition errors if the header is included in two different translation units in the same project. Note that this does not mean that the compiler will necessarily inline the function code at th... |
3,447,566 | 3,447,625 | dijkstra's algorithm - in c++? | for the past four days I am trying to understand the dijkstra's algorithm. But I can't. I have a vector of points. From that I created a cost matrix. But I don't know how to make the dijkstra's algorithm. Sources are available in net, but I am not from Computer science background, So I can't understand them. I am tryin... | I advise you to look at TopCoder tutorial that have very pragmatic apporach.
You will need to find out how STL priority queue works and make sure you don't have any negative edge weights in your graph.
Decent full implementation can be found here. You will have to add Path vector to it and implement RecoverPath method ... |
3,447,773 | 3,447,800 | Access specifiers in C++ | I've the below code,
template< typename T >
class T1 {
public:
T i;
protected:
T j;
private:
T k;
friend void Test();
};
The above code has a template class T1 with three members i,j and k and a friend function Test(),
I just want to know that which member/s of T1 will be available in function Test()... |
I just want to know that which member/s of T1 will be available in function Test()?
i,j and k
|
3,447,804 | 3,447,835 | vector of pointer to object - how to avoid memory leak? | How do we ususaly deal with a vector whose elements are pointers to object? My specific question is the comment at the end of the code supplied below. Thanks.
class A
{
public:
virtual int play() = 0 ;
};
class B : public A
{
public:
int play() {cout << "play in B " << endl;};
};
class C : public A
{
public:
... | Yes, you have to do that to avoid memory leak. The better ways to do that are to make a vector of shared pointers (boost, C++TR1, C++0x, )
std::vector<std::tr1::shared_ptr<A> > l;
or vector of unique pointers (C++0x) if the objects are not actually shared between this container and something else
std::vector<std::un... |
3,447,812 | 3,449,361 | POINTER_32 - what is it, and why? | I have just been given the task of updating a legacy application from 32-bit to 64-bit. While reviewing the extent of the task, I discovered the following definition immediately before the inclusion of external (eg. platform) headers:
#define POINTER_32
I cannot find what uses this definition or what effect it has, bu... | This is a macro that's normally declared in a Windows SDK header, BaseTsd.h header file. When compiling in 32-bit mode, it is defined as you showed. When compiling in 64-bit mode it is defined as
#define POINTER_32 __ptr32
which is an MSVC compiler extension to declare 32-bit pointers in a 64-bit code model. There... |
3,447,894 | 3,448,380 | Video upsampling with C/C++ | I want to upsample an array of captured (from webcam) OpenCV images or corresponding float arrays (Pixel values don't need to be discrete integer). Unfortunately the upsampling ratio is not always integer, so I cannot figure myself how to do it with simple linear interpolation.
Is there an easier way or a library to do... | Well, I dont know a library to to do framerate scaling.
But I can tell you that the most appropriate way to do it yourself is by just dropping or doubling frames.
Blending pictures by simple linear pixel interpolation will not improve quality, playback will still look jerky and even also blurry now.
To proper interpola... |
3,447,939 | 3,448,021 | Case sensitive string comparison in C++ | Can anyone pls let me know the exact c++ code of case sensitive comparison function of string class?
| std::string str1("A new String");
std::string str2("a new STring");
if(str1.compare(str2) == 0)
std::cout<<"Equal"; // str1("A new String") str2("A new String");
else
std::cout<<"unEqual"; //str1("A new String") str2("a new STring")
compare() returns an integral value rather than a boolean value. Retur... |
3,447,986 | 3,448,057 | Friend function and templates | My question is related to this question.
#include<iostream>
template< typename T >
class T1 {
public:
T i;
void display()
{
std::cout<<i<<"\n"<<j<<"\n"<<k;
}
protected:
T j;
private:
T k;
friend void Test( T1 &obj);
};
template<typename T>
void Test(T1<T> &obj)
{
T a=T();
obj.... | friend void Test( T1 &obj); declares a non template function.
Declare it as a template.
Try this :
....
private:
T k;
template<typename U>
friend void Test( T1<U> &obj);
};
|
3,448,014 | 3,448,168 | Visual Studio 2010 - files in folders without ../../Include.h | My physical file structure for a project I have is something like:
Source folder
Engine
Folder1
Folder2
etc.
I have some files in 'Source', some in 'Engine', some in 'Engine/Folder1', etc.
On my project, I have gone All Configurations->Source Directories and included Source, Engine, Engine/Folder2, etc. However, I... |
Is there a way to make it so I don't have to have ../Folder1/ in front of everything?
Yes, there is. The answer depends on several factors and I'm sure I'll miss a few.
Check the following:
In compiler settings check "Additional Includes" under "C/C++"
Also check in "VC++" the value for "Include Directories"
Check t... |
3,448,279 | 3,448,308 | "and"/"or" instead of "&&"/"||" in C++ code - compiler feature or programmer's fault? |
Possible Duplicate:
or is not valid C++ : why does this code compile ?
Hello.
I've recently encountered unusual C++ code written by someone else:
bool operator != (Point p1, Point p2)
{
return p1.X != p2.X or p1.Y != p2.Y or p1.Z != p2.Z;
};
as far as I can tell, or isn't declared anywhere, even as macros.
The... | It’s part of the C++ standard and works on all modern, conforming C++ compilers.
For Visual C++, this means passing the /permissive- flag to the compiler, which is recommended anyway (this flag is set by default by Visual Studio 2017 and later).
|
3,448,309 | 3,552,256 | Adding 3D effects to a 2D object - DirectX | I wrote a simple program to load a directX .x mesh file. My loaded image is displayed like this
.
But the one which the MeshViewer shows is like this
.
What should be done to get the 3D look? Which call in the DirectX library should I make?
| Are you loading the same file into the viewer as into your own application? 'Cause it actually looks like you don't have any normals in the mesh. If your using the same file as the viewer, they should be in the mesh file though.
Other than that, your lighting is incredibly bright (all values at 1.0), I would set the di... |
3,448,937 | 3,449,939 | class extending GtkWindow | i'm trying to learn c++, but i can not find if it's possible to extend a class in this way:
main.cc
#include "mWindow.h"
using namespace std;
int main( int argc, char* argv[] ) {
gtk_init( &argc, &argv );
mWindow win = mWindow();
gtk_main();
return 0;
}
mWindow.cc
#include "mWindow.h"
mWindow::mWindow(... | thanks,
I was trying to use C libraries as if they were C++.
This is how I solved with gtkmm:
main.cc
#include <gtkmm/main.h>
#include "examplewindow.h"
int main(int argc, char *argv[])
{
Gtk::Main kit(argc, argv);
ExampleWindow window;
Gtk::Main::run(window);
return 0;
}
examplewindow.h
#ifndef GTKMM_EXAMPLE... |
3,448,973 | 3,449,028 | C++: TwoDimensional Array: One dimension fixed? | I need to pass a double [][6] to a method. But I don't know how to create that two-dimensional array.
6 is a fixed size (or a "literal constant", if my terminology is right), which the method accepts. I was trying something like this, but without success...
double *data[6] = new double[6][myVariableSize];
So, the met... | I cannot tell from the question which dimension is which, but this might be worth a try:
double (*data)[6] = new double[myVariableSize][6];
|
3,449,112 | 6,032,668 | Why can't templates be declared in a function? | Reading C++ Templates: The Complete Guide and it says
Note that templates cannot be declared
in a function
It does not give explanation and/or cross reference to any other chapter in the book or external resource.
Could someone help in explaining this. Probably it is explained later in the book but not there yet.... | The problem is probably linked to the historical way templates were implemented: early implementation techniques (and some still used today) require all symbols in a template to have external linkage. (Instantiation is done by generating the equivalent code in a separate file.) And names defined inside a function nev... |
3,449,189 | 3,449,611 | How to Import a C/C++ dll to .NET application | In my new project I want to use a existing C C++ functions . For that I would need to add the C/C++ dlls to C# project.
My C/C++ projects is of type UnManaged and it is not a COM Project. I have seen few articles after from MSDN and tried:
[DllImport("user32.dll", EntryPoint="MessageBoxA")]
But I am not sure Where sho... | Please don't put your own dll's in C:\Windows\system32. If you're going to use part of Windows, like user32.dll, you don't put it anywhere, it's already there and will be found at runtime because C:\Windows\system32 is on the path. If you're going to use your own DLL, put it in the bin or bin\Debug or whatever folder, ... |
3,449,277 | 3,449,428 | Handling MouseEvents in Qt c++ | Sorry for my beginner's question...
What is the easiest way to define procedures, which are executed when MousePressEvent or MouseReleaseEvent occurs?
For now I am defining my own class (MyGraphicsView class), which inherits QGraphicsView and I am reimplementing mouse events (which are virtual functions). It works fin... | This thread on the Qt Centre forum describes quite well what your options are. Simply put:
Do what you are doing (ie subclassing and reimplementing)
Work with an event filter as described in the thread and link therein.
|
3,449,340 | 3,449,956 | Creating registry entries in Windows 2008 64bit | I wrote a bunch of unit tests to cover the windows registry reading/writing. They use the CRegKey ATL api.
These worked fine on my desktop machine of XP Pro, but when the tests came to run on the build machine - a Windows 2008 x64 Server - the tests fail with ERROR_ACCESS_DENIED when trying to create a key via Create.... | The days of programs modifying or creating global registry keys are over and done with. It still works on your XP box because you login as an administrator. Vista, Win7 and Windows 2008 have UAC to prevent anybody (ie malware) messing with the registry, even when logged on with an admin account.
You can add a manifes... |
3,449,434 | 3,484,168 | Eigen max matrix size for 32 bit applications | So, I'm finding the Eigen package crashes when I try to declare a matrix larger than 10000x10000. I need to declare a matrix like this.. about 13000x13000 elements reliably. I ran a test like:
for( int tortureEigen = 1 ; tortureEigen < 50000 ; tortureEigen++ )
{
printf( "Torturing Eigen with %dx%d..\n", tortureEige... | All the answers here are helpful!
It turns out that when compiled as a 32-bit app, Eigen will crash if you try and declare a dense MatrixXd, as I was, larger than 14000 elements or so. The crash happens with _aligned_malloc returning 0 in the Eigen alloc code (MatrixXd::resize()), meaning 1.5GB of contiguous, aligned ... |
3,449,576 | 3,449,688 | Question on how to copy a byte array buffer to a byte pointer in Visual C++ | I'm posting my first question here after having viewed many useful exchanges by others; it's very exciting! I'm thinking that this question will be fairly straightforward to answer, but I hope that someone can shed some light on it since its vexing me.
I have a function that accepts an array of bytes passed in as a ... | There are two way to go here.
1) You allocate a new buffer and populate that with the bytes. For that you need to change your function to take a double pointer like this:
int CFlirPumpDlg::ScanAndShift(BYTE **pPacketbuf)
But then, you have to allocate a new buffer instead of declaring it. Something like this:
BYTE* te... |
3,449,660 | 3,449,732 | Methods for parsing C++ defines? | I'm building a driver in C++ which relies heavily on another dll (surprise!). This dll comes with a header which contains a huge list of defines. Each define represents different return, message and error codes.
Each of these sets of defines has a prefix which differentiates it from the others. Something like:
MSG_... | I think you'll have to parse the .h file at one point or another, because once compiled, the #defines won't be anywhere in the code anymore. Parsing .h files just for the #defines isn't too hard though - just read in full lines (mind the backslash at the end), ltrim them, and if they begin with "#define " then split th... |
3,449,684 | 3,471,661 | PDFCreator will print TIFF instead of PDF | I am trying to convert a RTF document to PDF. I have this code:
// TestCOMPDF.cpp : Defines the entry point for the console application.
//
#include <windows.h>
#include <tchar.h>
#include <objbase.h>
#include <atlbase.h>
#import "MSVBVM60.DLL" rename ( "EOF", "VBEOF" ), rename ( "RGB", "VBRGB" ) //if you don't use t... | This is only a guess... I had a similar problem -- not when using PDFCreator programmatically (this is beyond my capabilities), but when using it as my standard printer to print to PDFs.
First I used it for a couple of days without any problem. Not I had installed it, but my partner. As I said... it just worked, and cr... |
3,449,820 | 3,450,064 | afx_msg term in message handler functions | Why afx_msg is used in message handler function declarations?
| I think it was used by earlier Microsoft Visual Studio IDEs to distinguish message handlers from other member functions. These days the IDE is more clever and does not need it. At least I do not remember any bad effect from not using it.
|
3,450,167 | 3,450,209 | Should I stop using auto_ptr? | I've recently started appreciating std::auto_ptr and now I read that it will be deprecated. I started using it for two situations:
Return value of a factory
Communicating ownership transfer
Examples:
// Exception safe and makes it clear that the caller has ownership.
std::auto_ptr<Component> ComponentFactory::Create... | It is so very very useful, despite it's flaws, that I'd highly recommend just continuing to use it and switching to unique_ptr when it becomes available.
::std::unique_ptr requires a compiler that supports rvalue references which are part of the C++0x draft standard, and it will take a little while for there to be real... |
3,450,222 | 3,451,549 | After in VS2010 include other library, app fail on start with error 0xC000007b | I have a problem, downloaded curl developemnt package but if i
add in my visual studio .lib file form this program fail with
0xC000007b on startup.
I trying download all complete source in this i can download simple vs6
project but without errors i convert it to visual studio 2010, i compile
this solution normally, li... | That's STATUS_INVALID_IMAGE_FORMAT, Windows isn't happy about the DLL it needs to load. That's almost always caused by trying to load a 32-bit DLL in a 64-bit program. Or a 64-bit in a 32-bit program. If you converted this VB6 code to VB.NET then you probably need to force it to run in 32-bit mode. Project + Proper... |
3,450,327 | 3,450,395 | Type equality test w/ decltype(), auto, or RTTI in C++? Does Boost have something for this? | I'm writing some code to translate a C++ type to an appropriate type for a SQL DB. I want to identify the type, and then depending on what it is, produce the appropriate SQL code. I'm not sure exactly what can be done in this regard by using RTTI, auto, or decltype. I have some ideas but I'm not sure if they're work... | You can use a simple metaprogramming function to determine (at compile time) whether two types are the same:
template <typename T, typename U>
struct same_type
{
static const bool value = false;
};
template <typename T>
struct same_type< T, T >
{
static const bool value = true;
};
Whether that actually helps yo... |
3,450,420 | 3,450,592 | bool operator ++ and -- | Today while writing some Visual C++ code I have come across something which has surprised me. It seems C++ supports ++ (increment) for bool, but not -- (decrement). It this just a random decision, or there is some reason behind this?
This compiles:
static HMODULE hMod = NULL;
static bool once = false;
if (!once++)
... | It comes from the history of using integer values as booleans.
If x is an int, but I am using it as a boolean as per if(x)... then incrementing will mean that whatever its truth value before the operation, it will have a truth-value of true after it (barring overflow).
However, it's impossible to predict the result of ... |
3,450,658 | 3,450,708 | What should I use as a buffer in C++ for receiving data from network sockets? | I'm using sockets with C++. The program simply requests an HTTP page, reads it into a buffer buf[512], and then displays the buffer. However pages can contain more data than the buffer, so it will cut off if there is no more space left. I can make the buffer size bigger, but that doesn't seem like a good solution. This... | Depends on what you intend to do with the data. If you just want to dump it to an output stream, then the proper thing to do is to do what you're doing, but do it in a loop until there's no more data to read, writing the buffer to the output stream after each read.
|
3,450,762 | 3,450,842 | Is there a standard C++ equivalent of C#'s Vector3? | Just wondering if C++ has a standard equivalent of the Vector2/3/4 (structures I think?) in C#?
Edit: For clarification a XNA C# Vector2/3/4 "structures" (I'm not entirely sure what they are) basically hold 2, 3, or 4 float values like a struct in C++ defined as:
struct Vector3
{
float x, y, z;
};
I've been basica... | Nothing standard that I know of, but here's some code to get you started
http://www.flipcode.com/archives/Faster_Vector_Math_Using_Templates.shtml
If you are using C++/CLI and targeting Windows and .NET, you can use Vector2, etc.
|
3,450,821 | 3,450,888 | How could HRESULT appear in an MIDL file? | I am developing some COM interfaces with IDL files. Some interface methods return HRESULT, but I have checked the MIDL language reference on MSDN, there's not a clue of HRESULT. So where could I find the official definition of this data type?
Update
Thanks to Shog9, I found it in wtypes.idl. I paste it here for other's... | Any practical .idl file should start with
import "oaidl.idl";
import "ocidl.idl";
Which declares essential types. Like HRESULT and VARIANT. Etcetera.
|
3,450,860 | 3,450,906 | check if a std::vector contains a certain object? | Is there something in <algorithm> which allows you to check if a std:: container contains something? Or, a way to make one, for example:
if(a.x == b.x && a.y == b.y)
return true;
return false;
Can this only be done with std::map since it uses keys?
Thanks
| Checking if v contains the element x:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Checking if v contains elements (is non-empty):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
|
3,451,099 | 3,451,191 | std::auto_ptr to std::unique_ptr | With the new standard coming (and parts already available in some compilers), the new type std::unique_ptr is supposed to be a replacement for std::auto_ptr.
Does their usage exactly overlap (so I can do a global find/replace on my code (not that I would do this, but if I did)) or should I be aware of some difference... | You cannot do a global find/replace because you can copy an auto_ptr (with known consequences), but a unique_ptr can only be moved. Anything that looks like
std::auto_ptr<int> p(new int);
std::auto_ptr<int> p2 = p;
will have to become at least like this
std::unique_ptr<int> p(new int);
std::unique_ptr<int> p2 = std::... |
3,451,218 | 3,451,353 | Invalidating set of pointers through indirection | Consider the following program. It creates a set of pointer-to-ints, and uses a custom indrect_less comparator that sorts the set by the value of the pointed-to integer. Once this is done, I then change the value of one of the pointed-to integers. Then, it can be seen the order of the set is no longer sorted (I supp... | Yes, std::set assumes elements are immutable. It's possible, if dangerous, to reorder it yourself after each change. I wouldn't recommend it, though: use another collection type.
|
3,451,280 | 3,451,700 | Opening files from Finder with a Qt-based application? | Apparently, for Cocoa applications, you're supposed to implement [[NSApp delegate] application:openFile:] or something like that to allow your application to open files double clicked in Finder.
How do you achieve this functionality using Qt, as the name of the file to be opened is not passed on the command line?
| QFileOpenEvent (Qt4/Qt5) should do the trick.
Also see https://doc.qt.io/archives/qq/qq18-macfeatures.html
|
3,451,537 | 3,451,620 | C++ cross platform code | We our going to start a new project in our small team:
It's a library which will be used by our other projects (in Linux and Windows).
It's not platform dependent logically (it's not using any system calls or anything like that).
It has to be compiled on various platforms (including Windows and Linux at least).
... | One way of increasing portability is to use the same compiler, GCC, on both platforms. If you also use the same compiler version, you will probably avoid most, if not all C++ language and Standard Library incompatibilities. You can also use the same build tools, such as GNU make, which means the build process is the sa... |
3,451,658 | 3,452,008 | Qt mouse click detection doesn't work all the time | Qt makes me question my sanity and existence. I don't know why code that works in one program that I wrote will not work in another program I wrote. The following code is identical in both programs. In P1 it works correctly by only allowing left clicks. In P2 it is exactly the same, except the left click code is does s... | From QMouseEvent::buttons() documentation:
For mouse release events this excludes the button that caused the event.
So the solution is to use QMouseEvent::button() instead:
void GLWidget::mouseReleaseEvent(QMouseEvent *event)
{
clickOff = event->pos();
// do it only if left mouse button is down
if (event... |
3,451,765 | 3,451,940 | C++ App Exceeds Memory But Doesn't Use Virtual Memory | I have an application that allocates memory with 'new' and frees them with 'delete' in some parts of the code.
The problem is that whenever it exceeds the memory limit of the system (let's say 2GB), Windows sends a Kill signal to the process.
I think it is not usual since it should use the swap space(I think in windows... | Here is how you can make it up to 3GB for a process; That is the absolute max you can have it for 32 bit windows apps. Any more than that and you are going to need to use a 64 bit version of windows.
That is a lot of memory. maybe you could consider splitting your app into multiple processes and communicating between ... |
3,451,806 | 3,674,991 | Getting error when trying to apply "ExtraSamples" tag to a TIFF file to be written | I have a program that takes an image and writes that out to a TIFF file. The image can be grey scale (8 bit), grey scale with alpha channel (16 bit), RGB (24 bit), or ARGB (32 bit). I don't have any problems writing out the images without an alpha channel, but for the images with alpha, when I try to set the extra sa... | I found the solution. The Extra_Samples field is not an uint16 but rather first a count (which is uint16) and then an array of that size (of type uint16). The call should thus look like this:
uint16 out[1];
out[0] = EXTRASAMPLE_ASSOCALPHA;
TIFFSetField( outImage, TIFFTAG_EXTRASAMPLES, 1, &out );
The reason for this i... |
3,452,019 | 3,452,291 | Help with explaining profiler results [STL] | I'm profiling a recent program that is dominated with File read. I'm kind of confused on how to interpret the results. If someone could explain to me what these top four functions are, it would help me a lot. Thanks in advance!
% cumulative self self total
time seconds seconds ... | The first and last are for exception handling; they are generated by the compiler to register objects whose destructors must be called if an exception leaves the current scope. You might be able to avoid calls to these functions if you can restructure your code to avoid throwing exceptions, or calling functions that mi... |
3,452,203 | 3,452,227 | How do I resolve link errors that appear in Objective-C++ but not Objective-C? | I'm converting my App Delegate file from .m to .mm (Objective-C to Objective-C++) so that I can access a third-party library written in Objective-C++. In Objective-C, my app delegate builds and runs fine. But when I change the extension, the project builds and I get link errors, all of which are missing symbols from a ... | Link errors with mixed C++/C or C++/Objective-C programs are usually due to C++ name mangling. Make sure you have extern "C" attached to all the appropriate declarations, and also that all of your code agrees on the linkage. That is, make sure that the function definition as well as the places where it is used can al... |
3,452,272 | 3,553,495 | Convert boost::uuid to char* | I am looking to convert a boost::uuid to a const char*. What is the correct syntax for the conversion?
| You can do this a bit easier using boost::lexical_cast that uses a std::stringstream under the hood.
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
const std::string tmp = boost::lexical_cast<std::string>(theUuid);
const char * value = tmp.c_str();
|
3,452,398 | 3,452,472 | Invalidating loop bounds | I've recently inherited a project primarily done in C++, so this is my first real exposure to it. I'm wondering if I may have a problem erasing a vector's elements from within a loop bounded by the vector's begin() and end().
Here's (essentially) what I've been trying to do:
for (vector<double>::iterator i = distance.b... | for-loop will evaluate i < distance.end() on each loop. The problem is in distance.erase, it will invalidate i, so the result of i++ is undefined.
|
3,452,434 | 3,452,719 | In which cases is alloca() useful? | Why would you ever want to use alloca() when you could always allocate a fixed size buffer on the stack large enough to fit all uses? This is not a rhetorical question...
| It could be useful if the size of the buffer varies at runtime, or if you only sometimes need it: this would use less stack space overall than a fixed-size buffer in each call. Particularly if the function is high up the stack or recursive.
|
3,452,505 | 3,452,838 | Boost Python (Suse and Ubuntu) | I created a simple .so library containing definition of a C++ class which should be accessed from Python and used for this purpose boost python library.
When I'm testing this library using x64 Ubuntu it is enough to set LD_LIBRARY_PATH with the path to boost libs before running python. It doesn't work, however, when I'... | You should never set LD_LIBRARY_PATH, see here and here.
First of all I have to assume that you installed the Boost libraries in a nonstandard location, otherwise the loader would find them automatically. If you have root access to the machine, install the libraries in a standard place (e.g. with the package manager, o... |
3,452,565 | 3,452,621 | C++ Templates and Subclasses? | So, I'm learning C++, and I've run into something which I know how to do in Java, but not in C++ :).
I have a template for a container object, which is defined as such:
template <class T>
class Container {
vector<T> contained;
public:
void add(T givenObject) {
this->contained.push_back(givenObject... | It's not possible for you to put artificial limitations on template type parameters. If the type given doesn't support the way you use it, you'll receive a compiler error. A feature called 'concepts,' which would essentially allow this, was going to be added to the next C++ standard, but it was delayed to the next-next... |
3,453,244 | 3,467,460 | How to set a CMFCPropertyListCtrl's column width? | I'm adding properties to an object of type CMFCPropertyGridCtrl like this:
myPropertyListCtrl.AddProperty(
new CMFCPropertyGridProperty(
_T("Name"),
foo.GetName())
);
The result is that only the second column is visible but not the first that should contain "Name".
I found CMFCPropertyGridCtrl::Ge... | m_nLeftColumnWidth responsible for holding the "Name" column's width is a protected member of the CMFCPropertyGridCtrl class. Create your own class, that derives from CMFCPropertyGridCtrl and you will be able to manipulate m_nLeftColumnWidth.
|
3,453,296 | 3,454,117 | How do I use TCHAR* Provided in Cmd Line Argument in Switch Statement? | Here's what I've got:
switch(argv[0])
{
case "-test1":
AfxBeginThread(method1, 0); break;
case "-test2":
AfxBeginThread(method2, 0); break;
case "-test3":
AfxBeginThread(method3, 0); break;
default:
AfxBeginThread(method1, 0); break;
}
I'm using windows so the arguments come into the array as TC... | You can't switch over values that are not constant integral values. But since argument matching isn't time critical, you can put in a couple of if's and strcmp's instead.
This code runs apparently under Windows, you're most likely forced to use TCHAR, which means that you need _tcscmp() instead of strcmp, and the good... |
3,453,402 | 3,453,642 | Incorrect vtable layout for class exported by DLL: request for clarification regarding headers and vtable construction | Although the problem at hand is solved, it has me a little confused as to what data is used to construct the vtables for a class and where the layout for the vtable is stored. If anyone can provide clarification or point me towards some information which might satiate my curiosity, I would greatly appreciate it.
Backgr... | Hmm, heavy duty implementation details of a 12 year old compiler. When you use __declspec(dllexport) on a class, the linker exports the members of the class. Not the vtable. That gets reconstructed in the client of the class when the compiler parses the class declaration in the header file. The linker fills in that... |
3,453,460 | 3,453,506 | Polygon in rectangle algorithm? | I have an algorithm which can find if a point is in a given polygon:
int CGlEngineFunctions::PointInPoly(int npts, float *xp, float *yp, float x, float y)
{
int i, j, c = 0;
for (i = 0, j = npts-1; i < npts; j = i++) {
if ((((yp[i] <= y) && (y < yp[j])) ||
((yp[j] <= y) && (y < yp[i]))... | Can't you just find the minimum and maximum x and y values among the points of the polygon and check to see if any of the values are outside the rectangle's dimensions?
|
3,453,500 | 3,453,706 | Compilation warning with Qt - Mac OS X only: <class> is already a friend of <class> | I am receiving the following warning when compiling a Qt project, but ONLY on Mac OS X with GCC. Windows with MinGW and Linux with GCC do not emit this warning.
/Library/Frameworks/QtCore.framework/Versions/4/Headers/qtextcodec.h:175: warning: 'QCoreXmlStreamWriter' is already a friend of 'QTextEncoder'
Why is this sho... | According to the Qt issue tracker. It is a bug QTBUG-8243, but nobody has provided a work around. Perhaps browsing the patch they mention might shed some light.
|
3,453,539 | 3,453,808 | Design question about protocol buffer events | I am developing a system that will provide many services, say, S1, S2, S3. Each of these services have a number of executables that will communicate using events, using protobuf.
My question is: Which one do you think is better design: (1) Combine all events for all the services (currently about 10-15) into one big my_... | I'd go with separate definition files. If anything, because you can change each service individually without having to recompile/build the entire set; you can manage change histories better in CVS or whichever source code control tool you use; and it would perhaps be easier to lookup smaller files when you are working ... |
3,453,547 | 3,453,708 | Can I teach dynamic_cast<>() new tricks? | Is there a way in C++ to construct your class such that given a pointer to your class you can instruct dynamic_cast<>() how to cast to another class for which you are wrapping the implementation? Would operator cast do the trick? Imagine I have an Abstract interface base class and derive a concreteA from this as well... | No. A dynamic cast is telling the compiler "I don't want to change this object at all, I just want to attempt to look at it as if it were this other type, but don't change it. If you have to change it, return NULL or throw an exception.". Dynamic cast is not going to attempt to perform any such conversions on your beha... |
3,453,644 | 3,453,657 | Function abruptly returns when it shouldn't | I am working on an Operating Systems assignment for one of my summer classes. The teacher has provided an object file that provides functions that mimic the behaviour of a disk device driver. We are then to write a file system API that uses the disk device driver in C.
I am working on my file system format function nam... | I think maybe you have forgotten the braces around your if statement - I imagine you meant to write this:
if (!DevFormat()) {
printf("Disk drive wasn't formatted successfully\n");
return 0;
}
Only the printf statement was inside the if block, so the return statement was executed every time regardless of the re... |
3,453,970 | 3,454,025 | Help with double-buffering | I have created an animation which works fine, but it flicks. I need help with double-buffering since I don't know anything about it.
This is the code in my onPaint():
VOID onPaint(HDC hdc)
{
Graphics graphics(hdc);
Pen pen(Color(255, 0, 0, 255));
graphics.DrawEllipse(&pen, sf , 0, 10, 10);
}
It work... | It looks like you're just prematurely copying the offscreen DC to the display. Try moving the call to BitBlt down four lines, to make it the last line before you start the clean-up, like so:
VOID onPaint(HDC hdc,HWND hWnd)
{
// this line looks a little odd :
HDC hDC = GetDC(hWnd);
// .. usually the hdc para... |
3,454,001 | 3,454,231 | macdeployqt not copying plugins | I'm developing a Qt-based application and when I use macdeployqt on the bundle, the Qt plugins are not copied to the bundle.
However, if I run it a second time, they are. Additionally, "The svg icon plugin is deployed if the application uses the QtSvg module." is not fullfilled - my application does use QtSvg but the i... | The problem lies at lines 355-365 of shared.cpp in the macdeployqt source:
while (frameworks.isEmpty() == false) {
const FrameworkInfo framework = frameworks.takeFirst();
copiedFrameworks.append(framework.frameworkName);
// Get the qt path from one of the Qt frameworks;
if (deploymenInfo.qtPath.isNull(... |
3,454,007 | 3,454,065 | C++ Sockets - Can i only send characters? | I'm using synchronised sockets with a win32 window, and using the send() and recv() function to send data over internet TCP;
what i'm wondering, how would i send some integers or even my own class/structure over the tcp socket? because the send() function only lets me send characters.
Would i just have to send characte... | It isn't sending characters in the textual sense - it's sending contiguous arrays of bytes, which it refers to using a char*. You can point to the bytes of any value type this way, so if you wanted to send an int,
int A = 5;
const char* pBytesOfA = (const char*)&A;
int lengthOfBytes = sizeof(A);
send(socket, pBytesOf... |
3,454,086 | 3,454,103 | Including header file defined by macro | I need to provide configuration file, which will describe which STL header files to include. I have found that usually it is done by defining a lot of HAVE_XXX_HEADER macros. I wonder if there's something wrong with explicitly providing header name in a macro. Then instead of testing each variant:
#if defined(HAVE_TR1_... | This is possible and legal in C99, cf ISO 9899:1999 §6.10.2 example 2. A similar example can also be found in the (draft) C++ standard, 16.2 bullet 8.
|
3,454,089 | 3,454,113 | How to create a linux user using C/C++? | I would like to build a program which takes a username as parameter and creates the user and its home folder (with some hard-coded specifications like folder, and security checks like username cannot be root or an existing user).
My application needs to create users in order to give SSH access.
The program will be exec... | Probably your best bet is to invoke useradd; it will do the right things (given appropriate parameters).
Trying to create one manually by calling the appropriate APIs is possible but not desirable.
|
3,454,302 | 3,454,462 | Bounding rectangle collision test? | I have complex polygons which I know the minimum x, minimum y, maximum x and maximum y. I also have another rectangle which I know the top left and bottom right vertices. Knowing this information, how can I know if these 2 bounding boxes are colliding? Thanks
| Try something like this:
typedef struct rect {
int top; // maximum y-coord
int bottom; // minimum y-coord
int left; // minimum x-coord
int right; // maximum x-coord
} rectangle;
// Returns 1 if the point (x, y) lies within the rectangle, 0 otherwise
int is_point_in_rectangle(rectangle r, int ... |
3,454,315 | 3,454,333 | Is it possible to pin a dll in memory to prevent unloading? | Is there some way in Windows to prevent unloading of our dll via FreeLibrary? I.e. to "pin" it in memory for the life of the process?
| Yes. Call LoadLibrary() on that DLL. That will increase the internal reference count. FreeLibrary() only unloads a DLL when its internal reference count drops to zero. If you LoadLibrary and never FreeLibrary, the DLL will be stuck in memory for the lifetime of your process.
If you're running into a situation where ... |
3,454,576 | 3,454,586 | long double vs double | I know that size of various data types can change depending on which system I am on.
I use XP 32bits, and using the sizeof() operator in C++, it seems like long double is 12 bytes, and double is 8.
However, most major sources states that long double is 8 bytes, and the range is therefore the same as a double.
How come ... | Quoting from Wikipedia:
On the x86 architecture, most compilers implement long double as the 80-bit extended precision type supported by that hardware (sometimes stored as 12 or 16 bytes to maintain data structure .
and
Compilers may also use long double for a 128-bit quadruple precision format, which is currently i... |
3,454,598 | 3,454,604 | In C++, what happens when the delete operator is called? | In C++, I understand that the delete operator, when used with an array, 'destroys' it, freeing the memory it used. But what happens when this is done?
I figured my program would just mark off the relevant part of the heap being freed for re-usage, and continue on.
But I noticed that also, the first element of the arra... | Two things happen when delete[] is called:
If the array is of a type that has a nontrivial destructor, the destructor is called for each of the elements in the array, in reverse order
The memory occupied by the array is released
Accessing the memory that the array occupied after calling delete results in undefined be... |
3,454,673 | 3,454,705 | Can __attribute__((packed)) affect the performance of a program? | I have a structure called log that has 13 chars in it. after doing a sizeof(log) I see that the size is not 13 but 16. I can use the __attribute__((packed)) to get it to the actual size of 13 but I wonder if this will affect the performance of the program. It is a structure that is used quite frequently.
I would like... | Yes, it will affect the performance of the program. Adding the padding means the compiler can use integer load instructions to read things from memory. Without the padding, the compiler must load things separately and do bit shifting to get the entire value. (Even if it's x86 and this is done by the hardware, it still ... |
3,454,686 | 3,455,060 | problem in understanding the code | i = 0;
while (fscanf(fp, "%f %f %d", &x[i], &y[i], &outputs[i]) != EOF) {
if (outputs[i] == 0) {
outputs[i] = -1;
}
i++;
}
patternCount = i;
I dont understand the meaning of this line from the above code:
if (outputs[i] == 0) {
outputs[i] = -1;
What does it represent. The Output is a matri... | outputs is defined as a one-dimensional array containing integer values..
float x[208], y[208];
int outputs[208];
Each index in the array can be seen as corresponding to a line read in the data file.
i x y outputs
--------------------------------------
0 | -8.818681 3.025210 1
1 |... |
3,454,807 | 3,454,879 | Question regarding dequeues and testing | I am preparing for an interview and I came across these questions. Can some one please help how to solve these questions.
Imagine you've 2D system which is just testing whether 2 rectangles are in collision state or not, and you supposed to make a program which takes the code of this system from its developers and tes... | For 1) You should test for overlap in the rectangles. The first test I would develop would simply start with the rectangles on top of each other and move them apart slowly until no collisions was detected. Error would most likely have to be measure either percentage of overlap or # of pixels that are overlapping. I... |
3,454,853 | 3,463,862 | Serial Port communication with Arduino and C++ | I am having a problem with a Serial Port communication between Arduino Nano and C++, even though the problem is in C++ side. Basically I want to send integers (or long,...) from the Arduino to a C++ program to be processed.
First I did a test sending information from the Arduino to the computer using Matlab. The Ardui... | As Hans Passant and dauphic pointed, it doesn't seem to be a general solution for my question. I am writing, though, the code that I was trying to avoid, just in case somebody finds it useful or face the same problem that I had:
int i = 0;
DWORD dwBytesRead = 0;
DWORD dwCommStatus = 0;
char szBuff[2] = ""; ... |
3,454,854 | 3,454,901 | How Do Vector drawing applications do this? | In Illustrator, you can drag a rectangle and it will select all objects in it. It does beyond a bounding box test since it ensures its touching an actual part of the polygon. How does it efficiently do this then? (A C or C++ implementation would be preferable)
Thanks
| If you want to check if any part of polygon P is within a rectangle R, then you can do this:
If any vertex of P is within R, then return TRUE;
If any vertex of R is within P, then return TRUE;
If any edge of P (line between adjacent vertexes) intersects an edge of R, then return TRUE.
Otherwise, return FALSE.
|
3,454,909 | 3,454,958 | Sharing data with a dynamically loaded library (dlopen,dlsym) | My main program would load a simple dynamic library called hello.so
In main
void* handle = dlopen("./hello.so", RTLD_LAZY);
In main , pass a callback function called testing (defined somewhere in main.h) and invoke the hello() from the dynamic library
typedef void (*callback)();
typedef void (*hello_t)( callback... | No, this is the preferred way of doing it, in my opinion. Any other way that I can think of involves making the DLL aware of the objects in the program it's linked with, which is most likely bad practice.
Regarding data, just a reminder though you didn't ask, it's usually best practice to copy any data that needs to be... |
3,454,954 | 3,455,012 | How are structs laid out in memory in C++? | Is the way C++ structs are laid out set by the standard, or at least common across compilers?
I have a struct where one of its members needs to be aligned on 16 byte boundaries, and this would be easier if I can guarantee the ordering of the fields.
Also, for non-virtual classes, is the address of the first element als... | C and C++ both guarantee that fields will be laid out in memory in the same order as you define them. For C++ that's only guaranteed for a POD type1 (anything that would be legitimate as a C struct [Edit: C89/90 -- not, for example, a C99 VLA] will also qualify as a POD).
The compiler is free to insert padding between ... |
3,455,253 | 3,455,497 | Find/Replace Using C++ Macro? | I have a case where I'm using a macro to generate simple subclasses. I've currently got it defined as:
#define REGISTER( TYPE, NAME ) \
struct NAME ## Class : public ParentClass \
{ \
NAME ## Class () : ParentClass ( # NAME ); \
}... | I don't think you can mainipulate the parameter NAME att all, beside concatenate it with another string. So the obivous solution is no to use a string that contains dots.
REGISTER(whateverType, SomethingwithoutDot)
I know it doesn't answer your question but it seems to me that you should take a look on the problem tha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.