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,683,048
3,683,074
Writing algorithm functions for STL
I have a std::set which is of type point struct point { int x; int y; int z; }; Suppose I want to perform three different operation on each variable in set i.e Find the smallest number from x variables. Get missing elements from y variables using set difference. Get product of all z variables. At this point, s...
Even if you get a ten-fold speed increase, if that piece of code only uses 5% of your application's time, you've just decreased the execution time to 95%. So, unless you know this is a real bottleneck in your application, don't waste time trying to optimize it. And the only way to know this is through profiling.
3,683,602
3,683,613
Single quotes vs. double quotes in C or C++
When should I use single quotes and double quotes in C or C++ programming?
In C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a' is a single a character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array). In C++ the type of a character literal is char, but note that in C, the type of a c...
3,683,680
3,684,008
Is there any good known file based key->value datastructure available in c++?
Is there any good file based key->value data-structure available in c++. similar to std::map(template based) with a insert/delete/get of O(logn).
STXXL - Standard Template Library for XXL Data Sets implements file-based containers. It's stxxl::map is quite similar to std::map, based on B+ tree with an insert/delete/get of O(logn).
3,683,740
3,683,770
Error operator new[] : function does not take 1 arguments
I have code that overloads operator new. The code below works fine under Linux (gcc4x) but not Windows (Visual C++ 2008 Express Edition) The code under Visual Studio 2008 Express Edition reports error C2660: operator new[] : function does not take 1 arguments class dummy{}; void* operator new[] (size_t size, dummy g...
You might need to #include <new>.
3,683,744
3,684,407
looking for GSM SMS component/ActiveX
I'm looking for a delphi component or ActiveX which can access to GSM devices through serial port. I need to send and receive binary data sms (8-bit coding).
nrCommLib TOxygenSMS
3,683,881
3,684,254
functions with const arguments Overloading ( Follow up)
This is a follow up of the Previous Question It got really complicated so I am starting a new thread to make my point clearer.( Didnt want to delete the previous thread because the other guys who gave valuable feedback dont not loose the reputation points they gained) Updated Code: (Complies and Works) #include <iost...
In C++, the function signatures int Test::foo (const int a) const and int Test::foo (int a) const are considered to be complete identical. The reason that the const on the parameter is disregarded is because it can not affect the caller in any way. As the parameter is passed by value, a copy is made of the value prov...
3,684,077
46,560,765
possible heap corruption (win 32, native c++)
I'm working with a single-threaded native c++ application. There is a very hard to reproduce bug that I cannot reproduce locally. I enabled full page heap and debug information in the release executable, and obtained dumps from a client (which has to use the application many days to get the bug). What the client repor...
For some closure to anyone interested: it was a dangling pointer. One year or so after posting the question, the customer changed the server hardware and kindly lent the server to us. I could easily reproduce it with live debugging on that machine and find the issue.
3,684,099
3,684,579
Simulate Fn+F11 key press
Can you tell me how I can simulate key presses Fn + F11 on a laptop? Do I have to write a driver, or something like that? The platform is Windows XP Pro SP3. Programming Language is C/C++. The purpose is create a program that allow to change enable/disable via GUI some hardware device that can turned off/on only with t...
Won't work. The Fn-F11 key combo on laptops isn't handled by the OS; it's processed in Systems Management Mode - a BIOS feature, essentially.
3,684,112
3,684,159
What is Objective C++?
What is Objective C++ and can I use this language in Xcode?
Objective-C++ is simply source code that mixes Objective-C classes and C++ classes (two entirely unrelated entities). Your C++ code will work, just as before, and the resulting executable will be linked with the Objective-C runtime, so your Objective-C classes will work as well. You can definitely use it in Xcode -- na...
3,684,183
3,684,449
Combobox style edit control in winAPI
In my winAPI project done in C++ (no MFC, no .net...), I am creating comboboxes in place of edit controls, because of the nice blue border. In many windows forms and dialogues, edit controls also have this look. There are two problems: This doesn't seem like like "proper" way to make an edit control look that way. Wha...
I think you are looking for the extended window styles; specifically WS_EX_CLIENTEDGE Specifies the 3d look. If you are using a resource (dialog) editor there is probably a flag in the control properties. If you are coding directly this is a parameter in CreateWindowEx
3,684,381
3,684,402
Writing a Prototype Constructor in C++
I am taking a quadratic expression, where y=ax^2 + bx + c with a,b,c are constants and x is a variable. Here is my class: class quadratic { public: double evaluate(const double x); void getCoefficients (double &A, double &B, double &C); void setCoefficients (const double A, const double B, const double C); private: do...
You should probably use the constructors' initializer list instead: quadratic() : a(0), b(0), c(0) { } quadratic(double A, double B, double C) : a(A), b(B), c(C) { } The above uses a part of the C++ language to initialize member variables called an initializer list. What you did for the constructor with parameters:...
3,684,475
3,684,491
Combobox hidden on resize
Whenever I resize my controls in my window, in response to a WM_SIZE message, they resize and redraw themselves fine. But my combobox control (a dropdown list) disappears whenever I give it a resize message, until I hover over it to bring it back. There are two possibilities, either it is not redrawing when I resize it...
I think the problem is probably the tab control hiding your control. You can use SetWindowPos to set its z-order with specifying SWP_NOMOVE and SWP_NOSIZE. You can also use BringWindowToTop to bring the combobox to the top of your z-order.
3,684,744
4,071,721
How to debug Android native code on a real device
I've got some trouble with the media backend (mostly Stagefrightplayer) in Android, and I'd like to understand why it throws the errors it does. The errors are usually device spesific, so debugging on an emulator wouldn't be sufficient. Example: I/AwesomePlayer( 147): mConnectingDataSource->connect() returned -1004 V...
Quite a few things you can do. If you believe the error is in the framework itself, then get the source and dig http://source.android.com/ Otherwise, the best debugger for Android is DDMS, it can work with the emulator, but also with the real device. http://developer.android.com/guide/developing/tools/ddms.html dumps...
3,684,756
3,684,862
Template+Dependent Name
$14.6.2/3 - "In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of t...
I think it is a known bug in GCC. According to the bug report, your example fails as late as GCC 4.4.0. I think that just means it hasn't been tested on a newer version though - not that it's been fixed.
3,685,161
3,686,015
QListWidget that resizes instead of scrolls
How do you change the behavior of a QListWidget so that it resizes its height instead of choosing a (seemingly arbitrary) height and adding scrollbars? See screenshot: The QListView's should fill up as much space horizontally as they can (creating as many "columns," if you will.) Then they wrap and make as many rows a...
Maybe you could this without using QListWidget. The Qt's examples contain a new layout class, QFlowLayout, which could be useful. With the following kind of widget hierarchy you could get multiple groups with labels and they all would be inside one QScrollArea. QScrollBox QVBoxLayout QLabel "Blank maps" QWid...
3,685,716
3,685,874
Where do I put third-party libraries to set up a C++ Linux development environment?
I'm not new in C++ although I'm new in Linux. I'm using CMake to precompile a cross-platform game engine with some third-party components, but I have a lot of doubts about using libraries. My question is how to work with third-party libraries and where to put them. Apt installs libs in their official place (/usr/local,...
Where to put libraries The best solution is to use your Linux distribution's packaging system (apt-get, yum, or similar) to install libraries from distro-provided packages wherever possible. If the distro's packaged libraries aren't of a recent enough version, or if you need some nonstandard build options, or if you ne...
3,686,033
3,686,129
C++/QtTestLib programatically get number of functions in class
Within my C++/QtTestLib Class, how can I get a count of the number of private functions in this class so that I can output it at runtime?
Something like this? (Not tested) QObject obj (); QMetaObject metaobject = obj.MetaObject(); int num_methods = metaobject.methodCount(); int private_methods = 0; for (int i=0; i<num_methods; i++) { if (metaobject.method(i).access() == QMetaMethod::Private) private_methods++; } where instead of just QObject you ...
3,686,210
3,686,547
C++: using a base class as the implementation of an interface
In C++ is it possible to use another base class to provide the implementation of an interface (i.e. abstract base class) in a derived class? class Base { virtual void myfunction() {/*...*/}; } class Interface { virtual void myfunction() = 0; } class Derived : public Base, public Interface { // myfunct...
If Base isn't derived from Interface, then you'll have to have forwarding calls in Derived. It's only "overhead" in the sense that you have to write extra code. I suspect the optimizer will make it as efficient as if your original idea had worked. class Interface { public: virtual void myfunction() = 0; }...
3,686,265
3,686,288
libpng: write a bigger png than 1002px
I'm currently writing a c++ program which should write me a png file as output. So I made a little code, actually works. I just took the source code from here and condesed it. My code is nopasted here. BUT: It only works if it doesn't exceed 1002 pixels in width. I am very sure the problem is somewhere around lines 29/...
Without diving into the code too deeply, there are these interesting constants: unsigned width = 1003; unsigned height = 500; int rowbytes = 4000; The last one directly controls the amount of memory allocated. Have you tried increasing this value?
3,686,449
3,686,481
const-ness as template argument
I have two structs: // ----- non-const ----- struct arg_adapter { EArgType type; // fmtA, fmtB, ... union { TypeA * valueA; TypeB * valueB; // ... more types } arg_adapter(TypeA & value) : type(fmtA), valueA(&value) {} arg_adapter(TypeB & value) : typ...
You can make it accept a metafunction and you can apply any transformation you like template<template<typename> class F> struct arg_adapter { EArgType type; // fmtA, fmtB, ... union { typename F<TypeA>::type * valueA; typename F<TypeB>::type * valueB; // ... more types }; arg_ad...
3,686,495
3,686,581
Function overloading with polymorphic templates
Why is the following code not compiling and how would it be possible to use the function from the base class? template<typename K> struct Base { K foo() { return (K)0; } }; template<typename K> struct Extension : public Base<K> { K foo(int a) { return (K)a; } }; int main() { Extension<float> e; e.foo(...
Extension::foo is hiding Base::foo. You can use a using delaration to bring it back: template<typename K> struct Extension : public Base<K> { using Base<K>::foo; K foo(int a) { return (K)a; } }; Item #33 ("Avoid hiding inherited names") in Scott Meyers's "Effective C++" is about this issue.
3,686,508
3,686,919
Box Based 3D terrain generation algorthms? (procedural generation)
I have been looking at this game called Minecraft and was intrigued by how it can dynamically generate random maps that look and feel right. What types of algorithms are used to generate terrains based on cubes like this? Thanks
Perlin noise usually works really nicely. Its also worth looking into midpoint dispacement (or the diamond square algorithm)
3,686,655
4,058,572
Optimizing this OpenGL rendering algorithm
My game draws a series of cubes from a VBO, and just translates to the cube's position each time: ... SetCameraMatrix(); SetFrustum(); //start vbo rendering glEnableClientState(GL_VERTEX_ARRAY); glBindBufferARB(GL_ARRAY_BUFFER_ARB, 1); glVertexPointer(3, GL_FLOAT, 0, 0); glColor3f(1,0.5,0); ...
If you have a lot of cubes your big problem will be the number of draw calls. Graphics cards churn through triangles at such an amazing rate that the bottleneck is often the driver doing the communication. In general, the less calls you make, the faster it will go. With this in mind, you'll be much better off chucking ...
3,686,834
3,693,330
using an external variable in C++ in a shared library - creating a shared library (dll) using MinGW g++
I am trying to create a shared library on Windows. I am able to create this shared library on linux but on windows I get linker errors. I am using the MinGW G++ 4.5 compiler. I will first present the source code to the example on linux , and then present the file which I tried to change on windows. /home/nxd/Progs/C++/...
I provided my answer in email (because the original poster repeated his question in email to a list I follow) complete with modified sample source that works as he wanted. See http://mingw-users.1079350.n2.nabble.com/using-an-external-variable-in-C-in-a-shared-library-tp5521039p5521149.html . I won't bother repeating t...
3,686,938
3,690,704
C++: how to debug a "General Protection Exception"?
i've faced an unhandled exception of "General Protection Exception". while the program runs but there is no output. i wanted to know what are general efforts i can do to debug such an Exception? thanks
Yes, if you cannot catch the problem using the debugger in Visual C++ (Professional or Express), and if it is indeed crashing the entire system, take a look at: http://support.microsoft.com/kb/315263 If it does not crash the system, and the debugger is not getting you to the point of where it occurs, you can try using ...
3,686,944
3,686,965
Can you mix free and constructor in C++?
Possible Duplicate: Is there any danger in calling free() or delete instead of delete[]? I was reading this question: In what cases do I use malloc vs new? Someone raised that one reason to use malloc was if you were going to use free. I was wondering: Is it valid to mix a free call and a constructor initialization ...
No it is invalid. There is no guarantee that new will use malloc or delete will use free. Moreover, using free instead of delete will skip my_type's destructor. If my_type itself is holding some resources, those will be leaked. Similarly, malloc will skip the constructor so the variable may be in an invalid state.
3,686,979
3,687,050
How does the [] operator work?
I'm working with C, but I think this is a more low level question that isn't language specific. How does the program correctly grab the right data with array[0] or array[6] regardless of what type of data it holds? Does it store the length internally or have some sort of delimiter to look for?
the compiler knows the sizeof the underlying datatype and adds the right byte offset to the pointer. a[10] is equivalent to *(a + 10) which is equivalent to *(10 + a) which in turn is equivalent to 10[a], no kidding.
3,687,074
3,687,096
Segmentation fault c++ templates
I wrote my first ever C++ template code on expandable array and I am getting a segmentation fault! After an hour of debugging I have realized that I need help. Something is wrong with the constructor or the destructor I think but not sure. The code is on pastie ready to be compiled. http://pastie.org/1150617 /* Expanda...
It has nothing to do with templates. It's just a problem of memory management. In the constructor of EArray, you have never initialized arr, so by default it contains some invalid pointer. But then in setElement, you used this invalid pointer arr[i] = newval;, which should cause a SegFault. It should be fixable by add...
3,687,188
3,689,724
How to get right row height in Qt for QTableView object?
From this screenshot you can see a lot of space inside the rows: I've used these functions to get resizing: resizeRowsToContents(); resizeColumnsToContents(); How can I get a better fit for cells/rows sizes?
Try these: verticalHeader()->setDefaultSectionSize(int size) horizontalHeader()->setDefaultSectionSize(int size)
3,687,279
3,690,258
Registering python callables in C++ classes
I'm writing a program in python which should be able to pass "callables" which are registered in a C++ class. So far I've written the following code: C++: class MyClass { ... public: register_callback(boost::function<void (int)> fun); }; Python/C API: class_<MyClass, boost::shared_ptr<MyClass>, boost::noncopyable>...
As you have inferred, MyClass is being passed in as a boost::python::object while register_callback wants a boost::function. Fortunately, the solution is simple enough - I think. Your code would look something like this (untested) (adapted from http://mail.python.org/pipermail/cplusplus-sig/2010-February/015199.html): ...
3,687,808
3,688,798
Can I Have Polymorphic Containers With Value Semantics in C++11?
This is a sequel to a related post which asked the eternal question: Can I have polymorphic containers with value semantics in C++? The question was asked slightly incorrectly. It should have been more like: Can I have STL containers of a base type stored by-value in which the elements exhibit polymorphic behavior?...
Just for fun, based on James's comment about a template-based system, I came up with this Vector-like implementation. It's missing lots of features, and may be buggy, but it's a start! #include <iostream> #include <vector> #include <boost/shared_ptr.hpp> template <typename T> class Vector { public: T &operator[] ...
3,687,947
3,687,972
C++: include multiple header files with same name from different namespaces
How do you solve created by including a header file with the same name as another header file already indirectly included as a result of another include? For instance: // src/blah/a.hpp #ifndef A_HPP #define A_HPP namspace blah { class A { } } #endif // src/blah/b.hpp #ifndef B_HPP #define B_HPP #includes "a.hpp"...
You solve this, simply, by not using the same #define at the top ... It would be better to use BLAH_A_HPP and FOO_A_HPP etc so that the #define also includes the namespace name. Edit: Well personally I recommend doing the following: 1) Don't name headers the same (ie use different file name ... this doesn't always hel...
3,687,960
3,689,032
HTTP requests from app disappearing between sender's network/proxy and our web host
I don't have very much information to work with here, yet. Our app sends an HTTP query to our server, and in all the cases we've used until now it has worked fine. But for one client, whose network goes through a proxy, their logs indicate that the request goes out successfully, but no reply ever returns, and our web...
I'd recommend using tcpdump or wireshark to monitor the actual traffic going in and out of your web server. Do you see their request coming through at all? If not, I'd ask them to try the same thing, both inside and outside of the firewall, to see what's happening there.
3,687,963
3,688,221
Send Events to a Windows Service from Kernel Mode
I am writing a piece of software that consists of a kernel mode driver and a user mode Windows service. The kernel driver needs to notify the service of different events and information, which the service will then process. My question is this: What is the best way to set up this communication? I know it is possible...
Why not just use ReadFile or DeviceIoControl on the service side? Simple IRP on the driver side, complete it when you have something to report. The service will need to spin up a thread or use an I/O completion callback. And CancelIo to cancel the blocking call when the service exits.
3,688,091
3,688,114
How can I assign a default value to a structure in a C++ function?
I have a structure: typedef struct { double x,y,z; } XYZ; I want to define a function like this: double CalcDisparity(XYZ objposition, XYZ eyeposition, double InterOccularDistance = 65.0) But I can't seem to find a way to assign a default value to eyeposition. How can I...
It's struct XYZ{ XYZ( double _x, double _y, double _z ) : x(_x), y(_y),z(_z){} XYZ() : x(0.0), y(42.0), z(0.0){} double x, y, z; }; so that I now have a default constructor. Then you call it like this: double CalcDisparity( XYZ objposition = XYZ(), XYZ eyeposition = XYZ(), ...
3,688,347
3,688,363
How to do my own custom runtime error class?
I'm trying to do a simple custom runtime_error. I define the class: #include <string> #include <stdexcept> namespace utils{ class FileNotFoundException: public std::runtime_error{ public: FileNotFoundException():runtime_error("File not found"){} FileNotFoundException(std::string msg):runtime_error(msg.c_str...
That's because you're throwing a pointer. Just do: throw FileNotFoundException(msg);. Whenever you use a pointer, unless you're putting it into a container/wrapper you're probably not doing the right thing.
3,688,409
3,688,682
GetDIBits and loop through pixels using X, Y
I'm grabbing a portion of the screen and scanning through the pixels for a certain color range. I looked at MSDN's Capturing an Image example and know how to use the functions. I can get the bits into an array, but I'm not sure how to do it in such a way that I can loop through it as I would an image. A pseudo-example ...
Apart from the good answers already given, here's an example of how to get a simple array structure to walk on. (You can use e.g. Goz' code for the iteration.) GetDIBits reference @ MSDN You have to select DIB_RGB_COLORS as flag for uUsage and set up the BITMAPINFO structure and the BITMAPINFOHEADER structure it contai...
3,688,649
3,689,139
Create sine lookup table in C++
How can I rewrite the following pseudocode in C++? real array sine_table[-1000..1000] for x from -1000 to 1000 sine_table[x] := sine(pi * x / 1000) I need to create a sine_table lookup table.
You can reduce the size of your table to 25% of the original by only storing values for the first quadrant, i.e. for x in [0,pi/2]. To do that your lookup routine just needs to map all values of x to the first quadrant using simple trig identities: sin(x) = - sin(-x), to map from quadrant IV to I sin(x) = sin(pi - x),...
3,688,889
3,688,917
array of C++ string types
These are my variables: const int sizeOfLicToCheckFor = 3; string licNameToCheckFor[ sizeOfLicToCheckFor ] = { "PROF", "PERS", "PREM" }; when I run my program licNameToCheckFor is only initialized with "PROF" and nothing else. What am I doing wrong?
How are you checking if it was initialized properly? Most probably you are doing that wrong because code is absolutely correct: #include <string> #include <iostream> using namespace std; int main () { const int sizeOfLicToCheckFor = 3; string licNameToCheckFor[ sizeOfLicToCheckFor ] = { "PROF", "PERS", "PREM"...
3,689,064
3,689,091
Pipes to C++ Streams
is it possible to turn pipes genereated via pipe() on a POSIX-system into std::istreams and std::ostreams? if yes, how? i would prefer to use << and >> instead of read() and write() thanks in advance
There are non-standard constructors which take file descriptor number or FILE*. See http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.5/a00074.html#a777faeb6849444b4663d1cbe543e1ae3
3,689,228
3,689,255
Is deleting an array stored as static local variable needed, and how?
I have a few arrays and a resource that needs deletion, the value of these variables are retained throughout the lifetime of the program and they are only used in a single function so it naturally fits into static variables: void func() { static GLfloat arrs[4] = {1, 1, 1, 1}; static GLUquadric* quad = gluNewQu...
No need to delete arrs[], it's not been allocated on the heap. It is not on the stack either, it's in the data segment somewhere, and part of your static program data and will go away when the process does. On the heap but generally not to worry about. This sort of allocating heap during static initialisation is not v...
3,689,239
3,689,252
Using c99 in C++'s `extern "C"` blocks
I would like to have a function written in C, but callable from C++ which takes a restricted pointer. This is only available in c99, so g++ doesn't like it, even in extern "C" blocks. How can I get around this limitation?
#ifdef __cplusplus # ifdef __GNUC__ # define restrict __restrict__ // G++ has restrict # else # define restrict // C++ in general doesn't # endif #endif
3,689,587
3,689,666
How to fix this "First-chance exception" in c/c++?
It reports An invalid handle was specified. for the code below: if(hPipe) CloseHandle(hPipe); What can I do?
I suspect you have something like this: class SmartPipe { HANDLE hPipe; public: //Functions which do something to hPipe ~SmartPipe() { if (hPipe) CloseHandle(hPipe); } }; The problem is that when SmartPipe is created, hPipe is initialized to random garbage. You have to initializ...
3,689,714
3,689,807
When should Q_OBJECT be used?
The documentation states that: The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system. But exactly what does that mean? On which QObject-derived classes can I safely omit it? Will prob...
You should use the Q_OBJECT macro for any non-templated classes that derive from QObject. Besides signals and slots, the Q_OBJECT macro provides the meta object information that is associated with given class. As stated in the documentation: we strongly recommend that all subclasses of QObject use the Q_OBJECT macro r...
3,689,782
3,689,805
In C++, is a const method returning a pointer to a non-const object considered bad practice?
In C++, is a const method returning a pointer to a non-const object considered bad practice? For example. consider the following methods: // Makes perfect sense bool isActive() const { return m_isActive; } // Makes perfect sense, both consts ensure nothing is modified const SomeObject* someObject() const { return m_so...
It depends on whether the non-const pointer is pointing to something inside the const object, or whether it is newly allocated memory that is meant to be variable. Consider something that returned a copy of a string; it's fine for the returned copy to be non-const, even if the original string is const. The ownership o...
3,689,849
3,691,405
WriteLog( ... ) function in C++
I'm trying to find a decent way to do logging from C++. My current solution is this: ostream & GetLog() { if( output == NULL ) throw error; return *output; } Where output is defined somewhere and can be a file or whatever. This is fine, but it doesn't let me do anything other than throw an error if output is not alloc...
Use log4cxx, which is a decent way to do logging from C++ that you are unlikely to be able to match in a timely way. Even if this seems like overkill now you may find that your diagnostic needs grow as your system does, making the logging component a time sink that was not envisaged at the start. I find I both save...
3,689,970
3,690,534
Avoiding glBindTexture() calls?
My game renders lots of cubes which randomly have 1 of 12 textures. I already Z order the geometry so therefore I cant just render all the cubes with texture1 then 2 then 3 etc... because that would defeat z ordering. I already keep track of the previous texture and in they are == then I do not call glbindtexture, but ...
Ultimate and fastest way would be to have an array of textures (normal ones or cubemaps). Then dynamically fetch the texture slice according to an id stored in each cube instance data/ or cube face data (if you want a different texture on a per cube face basis) using GLSL built-in gl_InstanceID or gl_PrimitiveID. With ...
3,690,136
3,690,221
Handling sequences through C++ class interfaces
Let's say I'm writing an interface for a class A that keeps a list of objects of type B, and I want to be able to manipulate that list through class A's interface. I could put add_B, remove_B, etc. methods to A's interface, but that's a lot of code duplication (this situation occurs in many classes in my programme), s...
The code below is based on the proxy design pattern. It preserves encapsulation and avoids a bulky interface in 'A' by delegating the interface to the 'proxy' object. Also note how the typedef allows freedom of changing 'list' to 'vector' or anything else. struct B{}; struct A{ struct containerproxy{ void ...
3,690,141
3,690,144
Multiple preincrement operations on a variable in C++(C ?)
Why does the following compile in C++? int phew = 53; ++++++++++phew ; The same code fails in C, why?
That is because in C++ pre-increment operator returns an lvalue and it requires its operand to be an lvalue. ++++++++++phew ; in interpreted as ++(++(++(++(++phew)))) However your code invokes Undefined Behaviour because you are trying to modify the value of phew more than once between two sequence points. In C, pre-in...
3,690,238
3,690,248
virtual keyword internals
I heard lots of times virtual function is usually implemented using a vtable. But I actually don't know actually how its implemented and how it works. edit I didn't actually get this code: How can it be rewritten. Can someone explain this in detail please. Finally, let's see how the compiler implements a call to a virt...
The common implementation is to have one pointer at the beginning of every instance of an object that points to a vtable. There is one vtable per class, so if you have a class A and class B, there will be one table for each. The vtable essentially has a bunch of function pointers, so if class A has two virtual function...
3,690,276
3,690,956
Hierarchical data in C++
How can I handle data in C++ like in newer dynamic languages, for example the arrays in PHP are quite neat: $arr = array( "somedata" => "Hello, yo, me being a simple string", "somearray" => array(6 => 5, 13 => 9, "a" => 42), "simple_data_again" => 198792, ); I am open to all suggestions.
If you know in advance what all kinds of values map is going to hold, then use boost::variant. Or else, use boost::any. With boost::any, you could later add entries with any type of value to the map. Example code with boost::variant: Creating a map: typedef boost::variant<std::string, std::map<int, int>, int> MyVari...
3,690,367
3,690,395
generate strings with all permutation of character
i have following code #include <iostream> #include <string> using namespace std; string generate(){ for (char c1='A';c1<='Z';c1++){ for (char c2='A';c2 <='Z';c2++){ for (char c3='A';c3<='Z';c3++){ for (char c4='A';c4<='Z';c4++){ return (new s...
The problem is with your expressions of this form: (new string *)(c1) The left hand side isn't a type, it's an expression. When you suffix it with another parenthesized expression it looks like a function call but that only works if the left expression is a function name or function pointer. In this case the new expre...
3,690,436
3,691,236
How are attributes parsed in Boost.PropertyTree?
Say I have this XML format: <Widget type="SomeWidget" name="foo"> <Event name="onmouseover"> dostuff(); </Event> </Widget> How do I read the attributes using Boost.PropertyTree?
If your problem is to get attributes: The attributes of an XML element are stored in the subkey . There is one child node per attribute in the attribute node. Existence of the node is not guaranteed or necessary when there are no attributes. From the doc http://www.boost.org/doc/libs/1_44_0/doc/html/boos...
3,690,504
3,707,099
Design pattern for large decision tree based AI in c++
I'm currently writing an AI for a game that is written in c++. The AI is conceptually fairly simple, it just runs through a decision tree and picks appropriate actions. I was previously using prolog for the decision engine but due to the other developers using c++ and some issues with integrating the prolog code I'm no...
Code is Data, and Data is Code. You've got working code - you just need to expose it to C++ in a way it can compile, then you can implement a minimal interpreter to evaluate it. One possibility is to take your Prolog rules and translate them in the most direct way possible to a data structure. Maybe you could design ...
3,690,506
3,690,530
Difference when omitting the C++ template argument list
When can you omit the C++ template argument list? For example in Visual Studio 2010 this piece of code compiles fine: template<class T> Vec2<T> Vec2<T>::operator+ (const Vec2 &v) const { return Vec2(x + v.x, y + v.y); } If you inline the code, it actually compiles without any argument list. But is this really the ...
Inside a class you can omit the argument on the class type: template<typename K> struct A { A<K> foo1; // legal A foo2; // also legal and identical to A<K> foo A bar(A x) {...} // same as A<K> bar(A<K> x) {...} }; Outside of a class scope you need the template arguments: // legal template<typename K> A<K> foo...
3,690,559
3,690,582
Is "for each" Microsoft specific?
Visual C++ 2010 accepts: std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); for each (auto i in v) std::cout << i << std::endl; Is this a C++11 feature or a Microsoft extension? According to Wikipedia, the syntax of C++11's for-each loop different: int myint[] = {1,2,3,4,5}; for (int& i: myint) { ...
The current standard draft does not include the for each ( auto i in v ) syntax, only the for ( auto i : myints ), so yes, it is just an extension.
3,690,859
3,690,864
C++: How do I write a function that accepts an iterator and inserts elements?
template<class Container> void BlitSurface::ExtractFrames(Container & output, int frame_width, int frame_height, int frames_per_row, int frames_per_column, bool padding) const { SDL_Surface ** temp_surf = SDL_Ex_ExtractFrames(_surface...
Use back_inserter: template<typename OutputIterator> void BlitSurface::ExtractFrames(OutputIterator it, int frame_width, int frame_height, int frames_per_row, int frames_per_column, bool padding) const { /* ... other lines unchanged ....
3,691,077
3,691,137
Should re-include stuff thats already in the project scope precompiled header?
I have a precompiled header stdafx.h which is used in all source files in my project. Thus all headers in the stdafx.h are available in all code files in the project. What I'm unsure about is whether or not to re-include stuff thats already in the precompiled header. What do you guys think? e.g. stdafx.h #pragma once ...
I would include it so that the header could be reused in a project which has different stdafx.h Another way of stating this is each header should contain all the declarations (preferably forward ones) it needs on its own There will not be any performance hit as the contents of the header will not be processed due to in...
3,691,394
3,691,639
gdb: Meaning of tstart error "You can't do that when your target is `exec'"
I would like to record the value of a local variable, t, each time that the program reaches a certain line. Accordingly, I tried: (gdb) trace stoer_wagner_min_cut.hpp :197 Tracepoint 1 at 0x4123a0: file ./boost/graph/stoer_wagner_min_cut.hpp, line 197. (gdb) actions Enter actions for tracepoint 1, one per line. End wi...
The tracepoint facility is currently available only for remote targets. You should be able to perform the tracing experiment you desire by using gdbserver. Example: $ gdbserver :0 ./a.out Process ./a.out created; pid = 21838 Listening on port 51596 In another window: $ gdb -q ./a.out Reading symbols from /tmp/a.out....
3,691,420
3,691,436
Compiler error when using integer as template parameter
What is wrong with the following piece of code? template<typename X> struct A { template<int N> int foo() const { return N; } }; template<typename X> struct B { int bar(const A<X>& v) { return v.foo<13>(); } }; #include <iostream> using std::cout...
Change return v.foo<13>(); to return v.template foo<13>(); because foo is a dependent name and you need to mention that explicitly using .template construct.
3,691,454
3,691,479
No additional dependencies required for a LIB but are required for a DLL
I have a framework (in C++) which is dependent on a few third party libraries. When I compile a static version of the library framework, no additional dependencies are needed, that is, the lib files of the third part libraries are not needed. When I compile the same framework as a DLL, additional dependencies are now n...
When you have a static library (a .lib file), which is just a collection of one or more object files (.obj), the linker just adds that code to yours in one executable. You can tell the linker to do this via a command line switch, an IDE configuration setting, or perhaps even a #pragma (specifics depend on your environm...
3,691,708
3,691,727
Iterator loop in C++
I've been googling for this for so long but I couldn't get the answer. The most of sample that I found are based on iterating with vector, map and etc.. I have the code below. multimap<int, int>::iterator it = myMuliMap.find(1); Let's say I have three pairs that has key "1". I like to get those three pair from for ...
The function you're looking for is equal_range. This returns an iterator to all pairs in the map which match the specified key auto range = myMultiMap.equal_range(1); for ( auto it = range.first; it != range.second; ++it) { ... } EDIT Version without auto pair<multimap<int,int>::const_iterator,multimap<int,int>::c...
3,691,739
3,691,799
a program to monitor a directory on Linux
There is a directory where a buddy adds new builds of a product. The listing looks like this $ ls path-to-dir/ 01 02 03 04 $ where the numbers listed are not files but names of directories containing the builds. I have to manually go and check every time whether there is a new build or not. I am looking for a way to a...
Checking for different ls output would send a message even when something is deleted or renamed in the directory. You could instead look for files with an mtime newer than the last message sent. Here's an example in bash, you can run it every 5 minutes: now=`date +%Y%m%d%H%M.%S` if [ ! -f "/path/to/cache/file" ] || [...
3,691,835
3,692,077
Why uninitialized global variable is weak symbol?
It seems uninitialized global variable is treated as weak symbol in Gcc. What is the reason behind this?
gcc, in C mode: Uninitialised globals which are not declared extern are treated as "common" symbols, not weak symbols. Common symbols are merged at link time so that they all refer to the same storage; if more than one object attempts to initialise such a symbol, you will get a link-time error. (If they aren't explici...
3,691,861
3,692,044
How do I get non-global objects to interact from within a function?
I'm trying to create a Breakout clone using C++, and so have several objects (like ball, paddle, powerupicon, block, etc). I understand that it's bad practice to have them at global scope, so they're initialized inside main(). The problem comes in with needing to do stuff with those objects from inside other functions ...
A simple (not necessarily flexible or powerful) approach is to define a base game_object class that defines your interface with game objects, and store those. Your objects inherit from it.: class game_object { public: virtual ~game_object() {} virtual void update() = 0; virtual void draw() = 0; // get...
3,691,890
3,691,910
stricmp doesn't work
i'm having a problem using stricmp in a specific function, in other functions it works perfectly, except this one. the problem is that even if it compares the same string (char*) it doesn't return 0. what might be the problem? (sorry for the mess, i'll try formatting it) that's the code: Employee* CityCouncil::FindEmp(...
Never blame a function that belongs to the C library. stricmp surely works as expected, meaning the strings are really different. There must be something wrong with the logic in this function - you should use printf statements to find out where and why the strings differ. EDIT: I put together a simple test program. Thi...
3,691,940
3,691,961
Finding the median value of an array?
I was wondering if it was possible to find the median value of an array? For example, suppose I have an array of size nine. Would it possible to find the middle slot of this array?
Assuming the array x is sorted and is of length n: If n is odd then the median is x[(n-1)/2]. If n is even than the median is ( x[n/2] + x[(n/2)-1] ) / 2.
3,692,021
3,692,064
Inheritance in C++ internals
Can some one explain me how inheritance is implemented in C++ ? Does the base class gets actually copied to that location or just refers to that location ? What happens if a function in base class is overridden in derived class ? Does it replace it with the new function or copies it in other location in derived class...
first of all you need to understand that C++ is quite different to e.g. Java, because there is no notion of a "Class" retained at runtime. All OO-features are compiled down to things which could also be achieved by plain C or assembler. Having said this, what acutally happens is that the compiler generates kind-of a st...
3,692,116
3,696,010
Named parameter string formatting in C++
I'm wondering if there is a library like Boost Format, but which supports named parameters rather than positional ones. This is a common idiom in e.g. Python, where you have a context to format strings with that may or may not use all available arguments, e.g. mouse_state = {} mouse_state['button'] = 0 mouse_state['x']...
The answer appears to be, no, there is not a C++ library that does this, and C++ programmers apparently do not even see the need for one, based on the comments I have received. I will have to write my own yet again.
3,692,227
3,692,233
It is possible to get functionality similar to .NET's LINQ in C++?
It is possible to get functionality similar to .NET's LINQ in C++? Would this require language extensions or could it be done using some very clever macros? Or even through a tool like Qt's moc (meta-object compiler)? Are there any existing LINQ implementations for C++ and if so, what are they?
Check CLinq (here and here) or Linq++ (here). Also try p-stade (here); however, it uses the STL and it doesn't have the same interface as LINQ, but it's pretty complete.
3,692,510
3,692,566
C++ - What is the purpose of function template specialization? When to use it?
Learning C++, came upon function templates. The chapter mentioned template specialization. template <> void foo<int>(int); void foo( int ); Why specialize when you can use the second? I thought templates were suppose to generalize. What's the point of specializing a function for a specific data type when you can just...
The main difference is that in the first case you are providing the compiler with an implementation for the particular type, while in the second you are providing an unrelated non-templated function. If you always let the compiler infer the types, non-templated functions will be preferred by the compiler over a templat...
3,692,544
3,692,573
What is the best way for starting graphical interfaces programming in C?
I have some knowledge in C/C++ but only using the Console. I'd like to start programming some graphical interfaces, but I don't have the minimal idea where to start. I've heard of GUI applications and DirectX applications. I'd like to know which is the best for start programming? Which libraries also is good to use a...
What's your platform? If you only care about Windows and don't mind an outdated technology, you can go to MFC way. If you want a cross-platform GUI toolkit; there are several: GTK WxWidget Qt If you want something more about drawing, instead of boring GUI forms; then you can learn either: OpenGL (cross-platform) Di...
3,692,549
3,692,683
Problems with getting glyph outline with appendBezierPathWithGlyphs
I'm working with Objective-C++. I'm trying to get the path outline of a text using NSBezierPaths appendBezierPathWithGlyphs. The problem is: the output is rather nonsense :( What I've written: String str = Ascii8("test string"); int length = str.getLength(); NSFont* font = [NSFont fontWithDescriptor: [NSFontDes...
What do you mean by “looks wrong”? Have you tried rendering the data? It’s valid. Below is your code modified to output an SVG of the curve data, which appears correct (but upside down because the coordinate convention of SVG is different). Other than that, removing some random C++, and adding transform which is undefi...
3,692,591
3,692,610
return() versus pthread_exit() in pthread start functions
The following program shows that we can use return or pthread_exit to return a void* variable that is available to pthread_join's status variable. Should there be a preference for using one over the other? Why does using return work? Normally we think of return putting a value on the stack but since the thread is comp...
(1) In C++ code, using return causes the stack to be unwound and local variables destroyed, whereas pthread_exit is only guaranteed to invoke cancellation handlers registered with pthread_cancel_push(). On some systems this mechanism will also cause the destructors for C++ local variables to be called, but this is not ...
3,692,602
3,692,902
Fastest 128 bit integer library
I am working on a CPU-heavy numerical computation app. Without going into many details, it's a computational math research project that involves computing a certain function f(x) for large integer x. Right now everything is implemented in C++ in x64 mode, using native 64-bit ints. That limits me to x<2^64~1.8*10^19. I...
You didn't mention your platform / portability requirements. If you are willing to use gcc or clang, on 64 bit platforms they have a builtin 128 bit types that come for free, __uint128_t and __int128_t. Maybe other platforms have similar type extensions. In any case it should be possible to find the corresponding gener...
3,692,633
3,692,752
design problem - inheritance with static variables
I have the following hierarchy: Graduate.cpp (abstract) College.cpp (abstract) Ecollege.cpp University.cpp (abstract) Tuniversity.cpp Huniversity.cpp class Huniversity for example represents a student that graduated from H university. each non-abstract class has to implement the following m...
class Huniversity for example represents a student that graduated from H university So why do you call this class Huniversity and not Hstudent ? I think you're mixing university and student and put them into the same class (because you also have static members representing per-university information in a class which ...
3,692,715
3,692,986
C++ Coprimes Problem. Optimize code
Hi i want to optimize the following code. It tries to find all coprimes in a given range by comparing them to n. But i want to make it run faster... any ideas? #include <iostream> using namespace std; int GCD(int a, int b) { while( 1 ) { a = a % b; if( a == 0 ) return b; b = b % a; if(...
This smells like homework, so only a hint. You don't need to calculate GCD here. If you can factorize n (even in the crudest way of trying to divide by every odd number smaller than 2^16), then you can just count numbers which happen not to divide by factors of n. Note that there will be at most 10 factors of a 32-bit ...
3,692,738
3,692,789
Floating point versus fixed point: what are the pros/cons?
Floating point type represents a number by storing its significant digits and its exponent separately on separate binary words so it fits in 16, 32, 64 or 128 bits. Fixed point type stores numbers with 2 words, one representing the integer part, another representing the part past the radix, in negative exponents, 2^-1,...
That definition covers a very limited subset of fixed point implementations. It would be more correct to say that in fixed point only the mantissa is stored and the exponent is a constant determined a-priori. There is no requirement for the binary point to fall inside the mantissa, and definitely no requirement that i...
3,692,809
3,692,979
Get typedef of current class
I'm currently using boost::intrusive_ptr together with my GUI classes. Although this is more or less a convenience question, is there a proper way to get the typename of the current class? The reason I'm asking is that I have a macro for typedef'ing the different pointer types: #define INTRUSIVE_PTR_TYPEDEFS(CLASSNAME)...
No, that's not possible to do in C++.
3,692,836
3,692,888
API Hook on a COM object function?
Greetings StackOverflowians, As discovered here, Windows 7 features a bug in which the DISPID_BEFORENAVIGATE2 event does not fire for Windows Explorer instances. This event allows shell extensions to be notified when a navigation is about to take place, and (most importantly for me) have the opportunity to cancel the ...
I've never heard of API hooking used to hook COM object functions. Member functions of COM Objects are not really that different and can actually be hooked just fine if you stick to the usual guidelines for hooking. A few years ago, I had to hook COM components of a proprietary CRM solution to connect it to a datab...
3,692,889
3,692,923
Simple user request for filename for output and input
How can I request the user to input the filename that my program needs to read from and have it output the name with .out extension instead? Example: char fileName[256]; cout << "What is the file name that should be processed?"; cin >> fileName; inFile.open(fileName); outFile.open(fileName); But I need it to save the...
To change fileName extension: string fileName; cin >> fileName; string newFileName = fileName.substr(0, fileName.find_last_of('.')) + ".out";
3,692,954
3,692,961
Add custom messages in assert?
Is there a way to add or edit the message thrown by assert? I'd like to use something like assert(a == b, "A must be equal to B"); Then, the compiler adds line, time and so on... Is it possible?
A hack I've seen around is to use the && operator. Since a pointer "is true" if it's non-null, you can do the following without altering the condition: assert(a == b && "A is not equal to B"); Since assert shows the condition that failed, it will display your message too. If it's not enough, you can write your own myA...
3,693,001
3,694,844
boost::any, variants, calling functions based on arrays of them
Given a set of functions, such as: template<class A1> Void Go(A1 a); template<class A1, class A2> Void Go(A1 a1, A2 a2); template<class A1, class A2, class A3> Void Go(A1 a1, A2 a2, A3 a3); Is it possible to take an array of some variant type and given its contents, fire the correct function? My application for thi...
Ok, I made some progress with this. If I use an array of boost::any, I can convert to and from a void * (and hence pass it as an lParam in a custom window message to a msgProc). The solution is if both sender and receiver classes have the same template parameters. That is to say, something like this (should compile a...
3,693,128
3,693,206
problem using file.seekp
i'm trying to write to append data to the end of a file, and am using the seekp(streamoff off, ios_base::seekdir dir) function but it doesn't append, somehow it writes the data in the middle of the file. i tried adding opening the file like this - file.open(resultFile,fstream::in|fstream::out); (as was suggested in oth...
What is variable pcc doing in there as referenced in your code? if((pcc->FindDepartment(dept) == NULL ) .....)) { .... } Accordingly to this documentation on C++'s file input/output here and quoted os::app All output operations are performed at the end of the file, appending the content to the current...
3,693,216
3,693,302
std intellisense in VS2010
I just noticed that eclipse has a extensive intellisense for stl. If you hover over any stl function or object you get information similar to what you would find in a c++ stl reference. This is however not the case in VS2010 and I'm wondering if there is any good plugin that might enable this? and even more far fetched...
You should look at the productivity power tools extention for vs2k10. It has many nice things, like a replacement for the Add Reference dialog box( the new one is searchable!) and one of the thing is a replacement for the standard intellisense.
3,693,279
3,719,666
online update mechanism for a c++ SERVER app
Couldn't find anything about this topic. I have a Windows TCP C++ server application which I want to update from time to time. As you obviously understand this introduces a problem - the server should be 24/7 from the users' perspective. When updating, it is also desired to keep the current TCP connections with the us...
In terms of protocol changes, I recommend you version your protocol. At the beginning of a connection between participating servers, have either the initiator or the receiver (doesn't really matter which, I think) announce the newest version of the protocol it understands, and then the other side responds in kind. They...
3,693,362
3,705,402
rearranging listview items
Say I have a listview control with several items in it. How would I allow the user to drag and drop items to rearrange them in the control. The listview control is in report view, with the full-row select extended style. Thanks in advance.
In your ListView's WM_LBUTTONDOWN handler, store the currently selected item index somewhere. In your ListView's WM_LBUTTONUP handler, use ListView_HitTest() to determine which item is under the cursor. If different than the stored index, then use ListView_DeleteItem() and ListView_InsertItem() to "move" the "dragged"...
3,693,363
3,693,377
C#'s default keyword equivalent in C++?
In C# I know you can use the default keyword to assign default values as 0 to value types and null to reference types and for struct types individual members are assigned accordingly. To my knowledge there are no default values in C++. What approach would you take to get the same functionality as the default keyword fo...
Assuming the type is default-constructible, you can use value initialization. For example, template <typename T> T get() { return T(); // returns a value-initialized object of type T } If the type is not default-constructible, typically you need to provide a default to use. For example, template <typename T> T g...
3,693,407
3,925,718
Culling techniques for rendering lots of cubes
I am working on a personal learning project to make a Minecraft clone. It is working very well aside from one thing. Similar to Minecraft, my terrain has lots of cubes stacked on the Y so you can dig down. Although I do frustum culling, this still means that I uselessly draw all the layers of cubes below me. The cubes ...
Render front to back. To do so you don't need sorting, use octrees. The leaves won't be individual cubes, rather larger groups of those. A mesh for each such leaf should be cached in a vertex buffer. When you generate this mesh do not generate all the cubes in a brute-force manner. Instead, for each cube face check if ...
3,693,454
3,693,471
How to read a file and get words in C++
I am curious as to how I would go about reading the input from a text file with no set structure (Such as notes or a small report) word by word. The text for example might be structured like this: "06/05/1992 Today is a good day; The worm has turned and the battle was won." I was thinking maybe getting the line using g...
Since it's easier to write than to find the duplicate question, #include <iterator> std::istream_iterator<std::string> word_iter( my_file_stream ), word_iter_end; size_t wordcnt; for ( ; word_iter != word_iter_end; ++ word_iter ) { std::cout << "word " << wordcnt << ": " << * word_iter << '\n'; } The std::string...
3,693,514
3,693,530
Very fast 3D distance check?
Is there a way to do a quick and dirty 3D distance check where the results are rough, but it is very very fast? I need to do depth sorting. I use STL sort like this: bool sortfunc(CBox* a, CBox* b) { return a->Get3dDistance(Player.center,a->center) < b->Get3dDistance(Player.center,b->center); } float CBox::G...
You can leave out the square root because for all positive (or really, non-negative) numbers x and y, if sqrt(x) < sqrt(y) then x < y. Since you're summing squares of real numbers, the square of every real number is non-negative, and the sum of any positive numbers is positive, the square root condition holds. You cann...
3,693,568
3,693,573
Finding width of text
I am setting the font for a control like this: HDC hdc = GetDC(NULL); int lfHeight = -MulDiv(szFont, GetDeviceCaps(hdc, LOGPIXELSY), 72); ReleaseDC(NULL, hdc); HFONT font = CreateFont(lfHeight, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Font.c_str()); SendMessage(hwnd,WM_SETFONT,(WPARAM)font,0); The control is a static. How ...
Use GetTextExtentPoint32. You'll need to select the font into the DC first.
3,693,705
3,694,321
How do I avoid invoking the copy constructor with insertion iterators
template<typename OutputIterator> void BlitSurface::ExtractFrames(OutputIterator it, int frame_width, int frame_height, int frames_per_row, int frames_per_column, bool padding) const { SDL_Surface ** temp_surf = SDL_Ex_E...
Really what you want is a move InputIterator for use with the insertion OutputIterator. Since that doesn't exist in C++03, there needs to be an alternative way to signal that a "shallow" move, not a "deep" copy, is desired. A simple state flag in the object itself won't work, because the implementation is allowed to co...
3,693,781
3,693,850
Friend functions not recognized
I have the following class with a couple friend functions: class Teleport { public: Teleport(); ~Teleport(); void display(); Location teleportFrom(int direction); friend bool overlap(Wall * wall, Teleport * teleport); friend bool overlap(Location location); friend bool overlap(Wall * wall);...
you want perhaps? class Teleport { public: Teleport(); virtual ~Teleport(); bool isTrue(); // Teleport.isTrue bool isNotTrue(); // Teleport.isNotTrue friend bool isTrue(); friend bool isNotTrue(); private: static bool veracity; }; then class Teleport { public: Teleport(); virtual ...
3,693,791
3,693,796
Can't Declare a Variable Char[]
struct Movie { char* date; char* title; char* rating; int runtime; }; typedef Movie* moviePtr; moviePtr tempDB; bool doStuff() { //... snip .,, tempDB = new Movie[tempC]; int i; ifs >> temp; while(ifs.good() && i < tempC) { tempDB[i].date = new char[strlen(temp)+1]; ...
You did not initialize i to 0, or whatever you want to start indexing at. Another note, in case of errors like seg-fault use Valgrind [valgrind.org] -- it helps spot the error in seconds. In your case an out of index memory access -- these are things Valgrind specializes in detecting.
3,693,888
3,693,905
Fill A Variable Size Array
int* HT; int HTc = 500; HT = new int[HTc] = {-1}; //Fill array with -1 I get the warning: extended initializer lists only available with -std=c++0x or =std=gnu++0x I'll assume this means it isn't compatible with the ANSI standard, which my prof. is nuts for. How else would I do this though?
Use std::fill. It would be better to use a std::vector than a c style array, but just for demonstration: #include <algorithm> int HTc = 500; int HT[] = new int[HTc]; std::fill(HT, HT+HTc, -1); // ... delete[] HT;
3,693,897
3,693,903
OpenGL ES App on iPad/X-Platform: C++ or Objective-C?
I hope this has a technical (rather than a religious) answer, but I wonder if I should use Objective-C or C++ to create an OpenGL ES Application on the iPad? As the ultimate goal would be to compile it on Windows and OS X as well, I'm inclined to use C++ (and only use ObjC for the stuff that I have to: App Delegate etc...
You can, it's called Objective-C++ and all you need to do is ensure your source files have a .mm extension for them to be treated as mixed Objective-C/C++ source files. That said, generally speaking if you're aim is cross platform GLES support, try and write it in C++ for the common things, and anything else, Objective...
3,694,067
3,694,075
Zooming in and out in Direct3D
I have a 3D scene and I want to be able to zoom in and out. What implementations are good, and which has some flaws? Will I be changing viewport, clipping panes? I totally don't know. Thanks
I think "zooming" refers to adjusting the view of a 2d image. In a 3d scene I do not know what you mean with zooming. Probably moving the camera is what you are looking for? http://www.toymaker.info/Games/html/camera.html
3,694,333
3,694,343
Why is there a delete[] in C++?
Why is there a delete[]? From my understanding its to behave differently for arrays. However, why does it really exist? There's only free in C and no free_array. Also in syntax the only difference between delete var and delete []var is the [] which has no params (I'm not telling the length of the array). So why does de...
Typically, for non-POD classes, a delete[] expression must call destructors on a variable number of class instances that cannot be determined at compile time. The compiler typically has to implement some run time "magic" that can be used to determine the correct number of objects to destroy. A delete expression doesn't...
3,694,558
3,694,571
How can i write something to file at the end of the file in c++
i'm writing something to file and it writes it in the middle of the file, is there any function that writes output to the end of the file? thanx in advance. ok this is really wierd i'm running with the visual studio debugger and i see that it writes thing to file like this : A B C D which is good, and than when i'm wri...
If you use std::ofstream and open the file in append mode (using std::ios_base::app in the mode mask) then all writes will be made at the end of the file.