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
5,534,636
5,541,731
ID3DX11Texture2D pixel data
I'm trying to get the back buffer pixel data in DX11 in order to save it to a file. Is there any way to get the pixel data of a ID3D11Texture2D without having to create a view for it and then get the resource from the view ? Thanks.
I found what I need: ID3D11DeviceContext::CopyResource.
5,534,759
5,534,818
C++: With CRTP, class defined in the derived class is not accessible in the base class
Here is the (simplified) base class: template <class T> class SharedObject { protected: QExplicitlySharedDataPointer <typename T::Data> d; }; And here is the derived: class ThisWontCompile : public SharedObject <ThisWontCompile> { private: friend class SharedObject; struct Data : public QSharedData { ...
This actually isn't related to the accessibility and friendship, it's related to the use of CRTP. Consider the following example that also exhibits the problem: template <class T> struct Base { typedef typename T::Data Data; }; struct ThisWontCompile : public Base<ThisWontCompile> { struct Data { }; }; The p...
5,534,788
5,534,873
Reading in from a file while debugging
I have SOME_TEXT.TXT in the Debug folder for my project. When I manually go to the Debug folder and run the application, I get the expected output and all is glorious. However, when I Debug the app within Visual Studio txtFile.is_open() fails and my output doesn't work. I've looked around in the other directories an...
You can control the working directory your program will run at in properties in the context menu of your project. Then in the "Debug" tab. This directory defaults to the output directory of the executable. Note that the output directory for release and debug are different. They are typically called "Debug" and "Release...
5,535,115
5,535,150
Should programs check for failure on WinAPI functions that "shouldn't", but can, fail?
Recently I was updating some code used to take screenshots using the GetWindowDC -> CreateCompatibleDC -> CreateCompatibleBitmap -> SelectObject -> BitBlt -> GetDIBits series of WinAPI functions. Now I check all those for failure because they can and sometimes do fail. But then I have to perform cleanup by deleting the...
Yes. You never know when a promised service will surprise by not working. Best to report an error even for the surprises. Otherwise you will find yourself with a customer saying your application doesn't work, and the reason will be a complete mystery; you won't be able to respond in a timely, useful way to your cust...
5,535,162
5,542,240
How to do a static assert that a pointer cast is trivial?
Let's say I have these types: struct A { int a; }; struct B { int b; }; struct C : public A, public B { int c; }; A C* pointer can be cast to A* pointer without adjusting the actual address at all. But when C* is cast to B*, the value must change. I'd like to ensure that two related types I have can be c...
Based on a suggestion from MSalters, and an answer from C++, statically detect base classes with differing addresses?, here is the closest thing to an answer I can come up with. It's probably gcc-specific, and requires knowing some member of the base class: #pragma GCC diagnostic ignored "-Winvalid-offsetof" // To ...
5,535,181
5,535,396
QTableView with icons in rows
I have a QTableView showing rows of a database table. In this table I have a column called data type and I have icon images for each type. How can I add these icons in front of each data type? Here's a part of my code as requested by justanothercoder. QString msgQueryString = "select MESSAGE_ID, DATA_TYPE from SER_MESS...
Set the DecorationRole of your items to the QPixmap you want and it should work. edit: I guess that the icon depends on the value in the data type column. int rowCount = serendibMsgTableModel->rowCount(); for(int row = 0; row < rowCount; row++) { QModelIndex index = serendibMsgTableModel->index(row, 1); QVaria...
5,535,271
5,536,704
changing value of a tag through XML parser
I am new to XML. I want to change the value of a tag in an xml file. I am using Xerces c++ library for this purpose. Can anyone tell me how to do it ?
load the XML document: xmlDoc=loadXMLDoc("temp.xml"); get the tag "tag1" you want to write (first one):DOMNode x=xmlDoc.getElementsByTagName("tag1")[0]; get the value node: DOMNode y=x.childNodes[0]; change the value of this node: y.nodeValue="New Value";
5,535,547
5,535,715
What's the best IPC method for intra-machine process communication in Win32?
I need to implement inter-process communication system for processes (in machine-wide) in Win32 using native C++ (.NET is not applicable). For more detail, I'm considering message routing system between the processes using binary formatted messages. Message sending/receiving must be asynchronous. TCP socket could be on...
If you have some time to spare, and if you like risk and experimentation, you can use the undocumented Windows feature: Local Procedure Call. It's been there forever, and it's probably the fastest, because it's the foundation for all others.
5,535,863
5,535,899
Where is the undefined behavior when using const_cast<>?
If I do: const char* const_str = "Some string"; char* str = const_cast<char*>(const_str); // (1) str[0] = "P"; // (2) Where (which line) exactly is the undefined behavior ? I've been searching a lot for this on SO but haven't found any explicit and precise answer (or at least, none that I could understand). Also rel...
Line (2) has undefined behaviour. The compiler is at liberty to place constants in read-only memory (once upon a time in Windows this would have been a "data segment") so writing to it might cause your program to terminate. Or it might not. Having to cast const-ness away when calling a poorly-defined library function (...
5,535,996
5,546,365
Wrapping std::vector of boost::shared_ptr in SWIG for Python
EDIT: Solved, my mistake; explained in my answer. I have this: std::vector < boost::shared_ptr < Entity > > entities; and I try to expose it through SWIG like this: %include "boost_shared_ptr.i" %include "std_vector.i" %shared_ptr(Entity) %include <Entity.h> namespace std { %template(EntityVector) vector<boost::...
SWIG seems to wrap global variables of type std::vector into tuples. The solution is to move entities into a class, and access it through an instance of that class. Example: class Globals { public: std::vector < boost::shared_ptr < Entity > > entities; }; extern Globals globals;
5,536,336
10,183,096
"Custom intrinsic" function for x64 instead of inline assembly possible?
I am currently experimenting with the creation of highly-optimized, reusable functions for a library of mine. For instance, I write the function "is power of 2" the following way: template<class IntType> inline bool is_power_of_two( const IntType x ) { return (x != 0) && ((x & (x - 1)) == 0); } This is a portabl...
Even VC 2005 is capable of producing code with sbb instruction. for C code bool __declspec(noinline) IsPowOf2(unsigned int a) { return (a>=1)&((a&(a-1))<1); } compiles to the following 00401000 lea eax,[ecx-1] 00401003 and eax,ecx 00401005 cmp eax,1 00401008 sbb eax,eax 0040...
5,536,368
5,536,551
Error with variable array size using the visual C++ compiler (Visual Studio 2010). How to circumvent this issue?
I am experiencing some troubles compiling a c++ file that worked well as a previous build under GCC. The issue is, I am using vectors of variable array size: unsigned int howmany; std::vector<int>* array_adresses[howmany]; I am currently using the Visual-Studio 2010 C++ compiler to built Matlab 64-bit Mex-Files. S...
howmany needs to be constant, and needs to be a defined amount, like so: const unsigned int howmany = 5; std::vector<int>* array_adresses[howmany]; Or you can define it dynamically like this: unsigned int howmany = 5; std::vector<int>* array_adresses = new std::vector<int>[howmany];
5,536,462
5,541,241
Does COleException::GetErrorMessage always return the error text in English?
What would happen if the user's computer has a non-English , for example French? Would the text be in French then? I'm asking this because this is the behaviour of FormatMessage, unless the dwLanguageId parameter is specified to LANG_ENGLISH instead of LANG_NEUTRAL.
It depends which specific exception class is in use. There is nothing in the base CException class that sets or formats the error message. However, some of the CException-derived classes do call FormatMessage when returning their error messages. For example, COleException::GetErrorMessage calls FormatMessage(FORMAT_ME...
5,536,759
5,538,447
condition variable - why calling pthread_cond_signal() before calling pthread_cond_wait() is a logical error?
It's written in POSIX threads tutorial https://computing.llnl.gov/tutorials/pthreads/ that it is a logical error. my question is why it is a logical error? In my program i need to use these signals, however i cannot guarantee that there will be a thread that will be in _cond_wait state. I tried to test it and nothing h...
The answer of blaze comes closest, but is not totally clear: conditional variables should only be used to signal a change in a condition. Thread 1 checks a condition. If the condition doesn't meet, he waits on the condition variable until the condition meets. Because the condition is checked first, he shouldn't care ...
5,536,779
5,536,807
Cannot assign the value of INT_MIN to a long long
signed long long value = -2147483648; cout << ((signed long long)value); outputs 2147483648 (no minus sign), why?
signed long long value = -2147483648; 2147483648 cannot be represented in a 32-bit signed integer, so it is converted to an unsigned, then unary minus is applied (which doesn't change anything), and then it is assigned to the signed long long. Use -2147483648LL
5,536,798
5,536,912
How to generate top level include file
How to generate top level include file which includes all other header files from all subdirectories? I am working on a large project with many subdirectories and many header files in those subdirectories. Subdirectories contain more subdirectories and those subdirectories have more header files. It is a big tree like ...
find . -name '*.h' | sed -e 's/\.\///' -e 's/^/#include "/' -e 's/$/"/' >> master.h Find all .h files strip the leading "./" add #include " at the beginning of line add " at the end of line redirect to master.h But I'm not sure this is such a good idea. I'd rather include only the necessary headers and keep the numbe...
5,536,849
5,539,611
MAPiEx - Extended Mapi Wrapper C# Help - Attachments?
I'm trying to expose the attachment functionality in my c# code from MapiEx.dll using DllImport: [DllImport("MAPIEx.dll", CharSet = ExtMAPIProfileWrapper.DefaultCharSet)] protected static extern void MessageSetSenderName(IntPtr pMessage, string strSenderName); [DllImport("MAPIEx.dll", CharSet = ExtMAPIProfileWrapper.D...
I think it's MessageAddAttachment.
5,536,895
5,540,738
Static assertion for atomic read/write of value
Is there a way to check if the reading/writing (load/store) of a value is atomic? I have specialized versions of concurrent containers than can only work with such values and I would like to add a static assert to prevent accidental misuse. For all the fundamental types on x86_64 this is true, but it may not be true fo...
The C++0x draft has a section with macros in the <atomic> header, which indicates that there is no easy and portable way to check this otherwise. 29.4 Lock-free property [atomics.lockfree] #define ATOMIC_CHAR_LOCK_FREE implementation-defined #define ATOMIC_CHAR16_T_LOCK_FREE implementation-defined #define ATOMIC_...
5,536,947
5,567,535
QGraphicsScene and QGraphicsWidget (reusable and embeddable)
I should start by saying I've tried to look at this problem from all POVs. I've also asked on freenode and I was suggested some things, yet in the end it turned out those suggestions could not possibly work. It looked to me as though those making suggestions don't really know how the class hierarchy and the concepts hi...
Based on your description, I would recommend to implement the three basic concepts as: 1) "grid" widget inherits from QGraphicsWidget as it supports adding layouts. If you go along with QGraphicsItem, you will need to re implement the layout mechanism which is really painful. The grid creates "grid" block depending on ...
5,537,016
5,537,053
How to use Boost.Asio c++?
I would try to use the library to use socket Boost.Asio c++ on multiple platforms. I downloaded the latest version here: http://sourceforge.net/projects/boost/files/boost/1.46.1/ but now what do I use in my code? I have compile it? include just enough? Can you tell me the steps?
How you use it depends on what you want to do, ;-). The documentation is found here: http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio.html You will find lots of examples that should suite your needs. For building, you should note that the library dependancies depend upon whether you are running on windows or li...
5,537,054
5,537,165
Include file into entire project
is there any way to include one file into entire project? I want to have some globals and macros accessible from any file in project, but i do not really write #include in every file TY
Use Visual Studio project settings: Projekt Properties->Configuration Properties->C/C++->Advanced->Forced Include Files This will use the specified include files in every source file. MSDN Forced include Alternativ: If you use precompiled headers you could also add your globals/macros to the stdafx.h
5,537,276
5,537,295
why sizeof(13.33) is 8 bytes?
When I give sizeof(a), where a=13.33, a float variable, the size is 4 bytes. But if i give sizeof(13.33) directly, the size is 8 bytes. I do not understand what is happening. Can someone help?
Those are the rules of the language. 13.33 is a numeric literal. It is treated as a double because it is a double. If you want 13.33 to be treated as a float literal, then you state 13.33f. 13.33 is a double literal. If sizeof(float) == 4, sizeof(13.33f) == 4 should also hold because 13.33f is a float literal.
5,537,334
5,537,468
c++ encrypt a text with a key received over packet? keyczar?
I'm storing a client's password in his device and there are times when clients need to send their password to server. When a client connects to me(server), I give him a key that will be used for encryption. I want a client to send a encrypted password by the key. Server will decrypt the password with the key(whic...
If you are sending the key to the user immediately before the user uses it to encrypt his or her password, you might as well be sending the password in the clear. (You're sending all the data required to reconstruct the cleartext password, anyway.) A better method would use TLS to encrypt the entire conversation using ...
5,537,344
5,537,357
How to locate prompt in console application?
Is there a way to place the prompt programmaticaly in a console application? I'm using Visual Studio 2008. Thanks
Do you mean moving the blinking thingy? If so I think SetConsoleCursorPosition is what you want. Console Functions reference page http://msdn.microsoft.com/en-us/libr...73(VS.85).aspx
5,537,378
5,537,509
Duplicate c++ template instantiations
Is it possible for the compiler to duplicate instantiations of a same template across several translation units? For instance, if you have a.cpp which use a std:vector<int> inside a function, and same thing for b.cpp, is there a risk of having two times std::vector<int> in the final binary?
As sharptooth says, the final binary will only contain one instantiation. But the templates will still be instantiated everytime they are encountered in a compilation unit. If you want some compilation speed, in C++0x we get the extern templates. It works like normal extern variables, in that it has to be specified in ...
5,537,533
5,537,605
Template Functions and Const/NonConst Reference Parameters
New to C++ and learning from books so I can be quite pedantic or miopic in my reasoning. In the case of template functions, I have read that when a parameter is passed by Reference, only conversions from Reference / Pointer to NonConst to Reference / Pointer to Const are alllowed. That means I believe that template <t...
The call compare( ci1, ci1 ); yields T as type const int (in your preferred notation). The effective function signature is then int compare( int const&, int const& ) You can use typeid(x).name() the check out what types you actually have. Note: with g++ that yields some ungrokkable short forms, which you then need to...
5,537,808
5,538,378
bug in opengl c++ code, probably related to cood system
I have put all the necessary files[temp link removed] if you need to have a look. mavStar.exe is my program. The function currently I‘m trying to debug is : void drawOG() { int curr,right,back,bottom; //Does NOT draw the right most,back most,bottom most layer at the moment //Does NOT draw face between stat...
There is a much easier way to draw the faces you want by using: glPushMatrix(); glBegin(GL_QUADS); //Draw the 16 vertices with their normals. glEnd(); glPopMatrix(); For example if you want the front: glPushMatrix(); glBegin(GL_QUADS); glColor3f(1.0f,1.0f,1.0f); glNormal3f(0.0,0.0,1.0); glVertex3f( position[0], ...
5,537,818
5,538,043
Word language detection in C++
After searching on Google I don't know any standard way or library for detecting whether a particular word is of which language. Suppose I have any word, how could I find which language it is: English, Japanese, Italian, German etc. Is there any library available for C++? Any suggestion in this regard will be greatly a...
I assume that you are working with text not with speech. If you are working with UNICODE than it has provided slot for each languages. So you can identify that all characters of particular word is fall in this language slot. For more help about unicode language slot you can fine over here
5,538,165
5,543,394
How to omit private non-virtual methods from class definition?
Lets say I have something like the following: a.hpp: class B; class A { private: std::unique_ptr<B> b_; } a.cpp: #include <something_complicated.hpp> struct B { something_complicated x; } something_complicated& A::get_complicated() { return b_->x; } Unfortunately, in this case, a.cpp will fall to compile becau...
I am afraid there is a misunderstand on what belong to the class, and what does not. Not all methods that act on the internals of the class should be class methods, after all, we have friend functions already. I know that many people declare the helper methods as private functions, however doing so introduces needless ...
5,539,219
5,539,539
CUDA - operations on single elements of a matrix - getting ideas
I'm about writing a CUDA kernel to perform a single operation on every single element of a matrix (e.g. squarerooting every element, or exponentiation, or calculating the sine/cosine if all the numbers are between [-1;1], etc..) I chose the blocks/threads grid dimensions and I think the code is pretty straightforward a...
If you have defined the grid so that threads read along the major dimension of the array containing your matrix, then you have already guaranteed coalesced memory access, and there is little else to be done to improve performance. These sort of O(N) complexity operations really do not contain sufficient arithmetic inte...
5,539,249
5,539,423
Why can't "transform(s.begin(),s.end(),s.begin(),tolower)" be complied successfully?
Given the code: #include <iostream> #include <cctype> #include <string> #include <algorithm> using namespace std; int main() { string s("ABCDEFGHIJKL"); transform(s.begin(),s.end(),s.begin(),tolower); cout<<s<<endl; } I get the error: No matching function for call to transform(__gnu_cxx::__normal_iter...
Try using ::tolower. This fixed the problem for me.
5,539,518
5,540,204
OpenGL Camera vectors
I have a very rudimentary camera which generates 3 vectors for use with gluLookAt(...) the problem is I'm not sure if this is correct, I adapted code from something my lecturer showed us (I think he got it from somewhere). This actually works until you spin the mouse round in circles than camera starts to rotate around...
Don't accumulate the transforms in your vectors, store the angles and generate the vectors on-the-fly. EDIT: Floating-point stability. Compare the output of a and b: #include <iostream> using namespace std; int main() { const float small = 0.00001; const unsigned int times = 100000; float a = 0.0f; ...
5,539,557
5,542,020
Boost and Python 3.x
How does boost.python deal with Python 3? Is it Python 2 only?
Newer versions of Boost should work fine with Python V3.x. This support has been added quite some time ago, I believe after a successful Google Summer of Code project back in 2009. The way to use Python V3 with Boost is to properly configure the build system by adding for instance: using python : 3.1 : /your_python31_r...
5,539,652
5,539,892
Using a Class Variable vs Sending Local Variable to Functions/Methods
When is it good form to push a local variable to a function/method as a parameter, rather than using a class variable in place of the function/method variable. For instance, I can have a function: int DoSomething(int var) { if(var == -1) return 0; } or I can have a class variable "_var" and use it in the same ...
The only answer out of the blue, for a any generic case is: it depends on your specific case. Data members, static members and function arguments all serve different purposes. Of course, there are some key tips we can give for what types of signs you should look for choosing one or the other. Typical cases: Data mem...
5,539,978
5,544,483
Dynamic XML code generation in C++
I would like to transform some C++ objects of classes of my own into XML code. I guess there are several libraries which provide C++ to XML-mapping, but I would like to keep the library overhead simple and craft something of my own. What would be an appropriate approach to generate XML building? In Java there are annot...
RapidXML is also pretty easy to use and can create dynamic xml for you.
5,539,985
5,540,527
Is it possible to build an Objective-C++ implementation from a C++ header?
I have a C++ framework I would like to use in Objective-C++. I'm working in XCode4 and targeting an iPad deployment. So given this (pseudocode) C++ header: class A { public: virtual int doSomething(int i) = 0; private: int _i; } For this specific instance, I need to have doSomething dispatch something via Gra...
You can use a C++ framework in Objective C++ as it is. Just include the .h files, and start instantiating classes. To make sure your sources compile as ObjC++ as opposed to ObjC, make sure your sources have the .mm extension. Objective C++ is a weird beast - it has two class/object systems running side by side. You can...
5,540,008
5,540,343
Need a regular expression to extract only letters and whitespace from a string
I'm building a small utility method that parses a line (a string) and returns a vector of all the words. The istringstream code I have below works fine except for when there is punctuation so naturally my fix is to want to "sanitize" the line before I run it through the while loop. I would appreciate some help in usin...
[^A-Za-z\s] should do what you need if your replace the matching characters by nothing. It should remove all characters that are not letters and spaces. Or [^A-Za-z0-9\s] if you want to keep numbers too. You can use online tools like this one : http://gskinner.com/RegExr/ to test out your patterns (Replace tab). Indeed...
5,540,091
5,540,406
Accessing a global static variable from another class
I am working with code that has a global static variable (which is an object) and I need access to it from another class. I have always avoided global variables/functions in general so in this situation I am not sure how to go about it properly. Just to clear my understand of things, in a global static variable has in...
You can decide on a master version of the container in one .cpp file, and have a function return a reference or pointer to that. Then don't bother with the other copies. Wrapper.h anArray<someObject>& Objects(); Wrapper.cpp #include "someHeader.h" anArray<someObject>& Objects() { return SomeNameSpace::variable;...
5,540,708
5,540,854
Convolution with separable kernel
I'm looking at the CUDA SDK convolution with separable kernels, and I have a simple question but can't find an answer: Do the vectors, whose convolution gives the kernel, need to have the same size? Can I first perform a row-convolution with a vector 1x3 and then a column convolution with another one 5x1 ? Or they bot...
Yes, the vectors can be different sizes. The only consequence is that you'll get a rectangular matrix that is not square.
5,540,745
5,544,330
Creating menu bar in mobile 6.x
I am trying to create a menu bar in mobile 6.x and here is the code I am using: Resource.h #pragma once #include <aygshell.h> #define IDI_APP_ICON 1 #define IDR_MENU 100 #define IDS_APP_TITLE 101 #define IDS_EXIT 102 #define IDS_SEARCH 103 #define IDS_SETTINGS 104 #define IDS_HELP 105 #define ID...
I found the answer. It turns out that SHMENUBAR is not defined by the resource compiler and if you create your project using wizard, if will add #define SHMENUBAR RCDATA to the project. all I had to do was to replace the SHMENUBAR with RCDATA.
5,540,751
5,541,108
C++, Eclipse CDT code analysis?
Are there any good plugins for static code analysis for Eclipse CDT? I found two so far: Cppcheck plugin, but this still needs the original cppcheck executable CppChecker, but this didn't work (it didn't do anything) Are there any more that are better? Or how do I get CppChecker to do something (or is it a static cod...
There is another called "Codan," stands for CODe ANalysis. It can be reviewed at this wiki, with links to the tool: http://wiki.eclipse.org/CDT/designs/StaticAnalysis I cannot answer whether this is the better than your list, but at least it's another option you can review. Eclipse integration seems to be its only req...
5,540,816
5,540,843
How to initialize static members in derived classes?
Well, apparently, I cannot. But that's my problem. Maybe it's a design issue and I'm getting the whole thing wrong. I would like to have a class member initialized differently within each derived class. Imagine I have an object of type Device. This Device is just an interface used by the application code, because the a...
Should the name property not be a class member? Each family device should, most likely, have it's own, private static member. You could use a virtual method to return the proper name on a device instance.
5,541,054
5,542,132
How to correctly read data when using epoll_wait
I am trying to port to Linux an existing Windows C++ code that uses IOCP. Having decided to use epoll_wait to achieve high concurrency, I am already faced with a theoretical issue of when we try to process received data. Imagine two threads calling epoll_wait, and two consequetives messages being received such that Lin...
If you have multiple threads reading from the same set of epoll handles, I would recommend you put your epoll handles in one-shot level-triggered mode with EPOLLONESHOT. This will ensure that, after one thread observes the triggered handle, no other thread will observe it until you use epoll_ctl to re-arm the handle. I...
5,541,256
5,541,657
debugging an inproc com server running in dllhost.exe
I am writing an inproc com dll that runs in the dllhost.exe surrogate, but I am running into an issue debugging it. if there were multiple dllhost.exe's running at once, it would be annoying to find the right one to attach a debugger to. Is there an easy way to identify yours if a lot are running? Thanks
Process explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653) has convenient feature that allows you to look at which processes have loaded which DLLs. You can also do a search for DLLs in all running processes. Sysinternals also has a command line utility called ListDLLs (http://technet.microsoft.com/en...
5,541,374
5,542,435
Boost uBLAS matrix/vector product
can someone please provide an example of how to use uBLAS product to multiply things? Or if there's a nicer C++ matrix library you can recommend I'd welcome that too. This is turning into one major headache. Here's my code: vector<double> myVec(scalar_vector<double>(3)); matrix<double> myMat(scalar_matrix<double>(3,3...
I haven't looked that much at Boost uBLAS, but Eigen sure is nice, and has good performance as well.
5,541,392
5,541,621
What happens to Dispatch Pointer after crash
Assume that I have two processes, A and B. Process A instantiates an IDispatch object in process B (Process A loads the proxy stub, marshalling is done through it). During this, process B crashes and the IDispatch object goes down with it. Process A still has a pointer to something, but when it tries to call a function...
You'll normally get RPC_E_SERVERFAULT. This is unpleasant behavior, the server is usually toast after this. A fix is available in Vista and up with IGlobalOptions. Check this blog post for details.
5,541,488
5,541,997
C++ new() crashing before calling ctor
thank you for looking at my problem. I have an object that is being dynamically created in my program. The creation is part of a loop and the first iteration works fine. Upon creation, my object base class adds itself to a map. Here is some sample code : public class Base { Base() { // Add itself to a map...
Has Data::objects been initialized prior to the creation of ANY of the usages of Base? You are not guaranteed that the class object objects had been initialized whenever you have more than one translation unit (read, .cpp file) in the final link target, unless you've gone to special effort to ensure it. Most people sol...
5,541,501
5,542,825
Rotating a model in GLM
hey ive been working with GLM and i have been noticing that im not able to find a function to rotate the model. There isnt much to this question, but im wondering if theres a way to rotate a GLM model, or rotate and single model in my opengl program. if so then can you give some pointers?
You don't explicitly rotate models, you apply a rotation to the modelview matrix. Read up on how the OpenGL matrix stack works, and on how to use glMatrixMode and glRotate here. It is the same in later versions of OpenGL, except in those, you implement the matrix stuff yourself and do the transform in a shader rather t...
5,541,506
5,567,830
High performance low latency C++ custom string class
My goal is to find the fastest C++ library for casting int to string, vice versa, and parsing. Anyone that has experimented with performance of C++ will quickly realize that the string class of STL has terrible performance compared to say STL int arithmetic operations. Some sample benchmarks from my 3.3 GHz Intel, GCC...
You didn't provide much information about your servers, but have a look at these libraries from AMD and Intel: AMD String Library Intel Integrated Performance Primitives Both use SSE extensions to speed up string operations. As far as I can see, they have no atoi(), but you could use the libraries to locate the decimal...
5,541,560
5,541,568
integer constant is too large for "long" type
Possible Duplicate: long long in C/C++ Writing a simple program for a project Euler problem. Refuses to compile because "integer constant is too large for "long" type", even though it should be well within the size limits of an unsigned long long. Using the dev-c++ compiler. code in question: #include <iostream> bo...
Try an "ULL" suffix: 600851475143ULL
5,541,814
5,541,846
Similar conversion in overloading wstring and wchar_t *
I have following code: inline bool match(const std::wstring & text1, const std::wstring & text2) { return match(text1.c_str(), text2.c_str()); } inline bool match(const std::wstring & text1, const wchar_t * text2) { return match(text1.c_str(), text2); } inline bool match(const wchar_t * text1, const std::wstr...
The fourth overload needs to be moved to the top of the list so it appears first. The first three overloads all try to call the fourth overload, but it hasn't been declared yet, so it isn't found during overload resolution. std::wstring does have a converting constructor that allows a const wchar_t* to be implicitly c...
5,541,935
5,542,021
C++: factory design, can't push_back on vector
I am currently designing a video game in c++ for a school project. We were advised to use an abstractfactory desing to create our objects. When playing the game I'd like to store the objects (player, enemy, weapons etc.) in one vector of entitie (superclass) pointers. I define my levels in a class GameLogic, but when I...
You are trying to add a SpeedPowerUp to a vector of Entitie. You probably want to make sure your SpeedPowerUp actually inherits from Entitie.
5,541,952
5,541,992
Whats the difference between Reference and Pointer return types in C++
If I were to create a simple object in C++, what is the difference between returning an address of the member vs. returning a pointer. As far as I'm aware, C++ doesn't have automatic garbage collection so it wouldn't be keeping a reference count. So why would someone do it this way: class CRectangle { public: strin...
The & (in this context) doesn't mean "address of". A function declared as string& getName( ); returns a reference, not a pointer. A reference is essentially an alias for another object. So in this case, it doesn't return a copy of the object's name, or a pointer to the name, but a reference to the name itself. So any c...
5,541,967
5,542,050
Alternative Method from c to c++
Is there an alternative way of rewriting this same script in C++ w/o using the scanf or printf functions? Thanks! #include <stdlib.h> #include <stdio.h> int main( int argc, char * argv[], char* env[]) { char quer[222]; printf("Content-type: text/plain\n\n"); scanf("%s",quer); printf("%s\n...
#include <iostream> #include <string> int main() { std::cout << "Content-type: text/plain\n\n"; std::string quer; std::getline(std::cin, quer); std::cout << quer << '\n'; }
5,541,975
5,542,066
What does "1.$" mean?
I'm printing a variable using cout in Visual C++ 2010 and it shows "1.$". What does it mean? Google does not allow searches with $ so I couldn't find the meaning. EDIT: The code is like this: double func(...); std::cout << func(...); I haven't modified cout's defaults
Its an infinite value with the precision set small: #include <iostream> #include <limits> int main() { std::cout << std::numeric_limits<double>::infinity() << "\n"; std::cout << std::numeric_limits<double>::quiet_NaN()() << "\n"; std::cout << std::setprecision(2) << std::numeric_limits<double>::infinity() ...
5,542,037
5,542,161
Avoiding overflow in integer multiplication followed by division
I have two integral variables a and b and a constant s resp. d. I need to calculate the value of (a*b)>>s resp. a*b/d. The problem is that the multiplication may overflow and the final result will not be correct even though a*b/d could fit in the given integral type. How could that be solved efficiently? The straightf...
If there isn't a larger type, you will either need to find a big-int style library, or deal with it manually, using long multiplication. For instance, assume a and b are 16-bit. Then you can rewrite them as a = (1<<8)*aH + aL, and b = (1<<8)*bH + bL (where all the individual components are 8-bit numbers). Then you kn...
5,542,134
5,543,312
Guarantees on memory ordering and proper programming practice
With respect to the ordering I describe below I have some related questions. Given these ordering guarantees I don't need explicit fences in many places. However, how can I express the "fence" to the compiler, in particular GCC? That is, the guarantee of program order only applies so long as the optimizer doesn't reo...
Mastery of these kinds of operations is essential for building SMP operating systems and for communicating with certain kinds of hardware. The Linux kernel documentation provides an excellent overview of the subject along with the specific solutions used by the kernel. I highly recommend taking a look at their memory-b...
5,542,151
5,542,244
Simpler "Preventing derived classes" in C++
Going under the assumption that there is a legitimate reason for preventing derivation from some class, Bjarne gives a solution here for the answer to "Can I stop people deriving from my class?" However, I thought of: class final { protected: final() { } // line 3 }; class B : private virtual final { }; cla...
The solution is rather bad, it could be improved with CRTP (adobe does so) but it won't be a complete solution. The problem with your code is that another programmer that does not want to break your contract (she is a good person) but does not know that she should not derive from your class might want to lock others fr...
5,542,577
5,542,630
C++ thread waiting times
Is there a way to get the time a thread has been WAITING during its life (in C++/windows)? (I've asked before about the working time, but getting the waiting time would be much better :) ) Using GetThreadTimes is not enough for me because I need a high resultion (way better than 100 microsec, more towards 5-10 microsec...
Call GetThreadTimes(). Add together kernel time and user time. Subtract creation time from now. Subtract value found in step 2 from that found in step 3 and you have your answer.
5,542,614
5,542,638
Trouble with LNK 2019 unresolved externals
Okay, as mentioned, I am having two unresolved external errors. There are no intellisense errors and such, just this two linker errors. Here is the code. include "stdafx.h" include < iostream > using namespace std; class circle; //forward declaration class square { public: square create_square(circle user...
You declared a circle destructor, and a square destructor - but you didn't implement them. Additionally, you should prefer const references over pass by value: square create_square(circle const & user_circle); You get the error at this point because you're passing a circle by value - which means a temporary will be cr...
5,542,681
5,542,812
Boost smart pointers: Can I express it in a more concise way?
today I've been working with Boost::shared_ptr, and I have a question. vector<shared_ptr<KlasaA> > vec; vec.push_back(shared_ptr<KlasaA>(new KlasaB)); vec.push_back(shared_ptr<KlasaA>(new KlasaC)); vec.push_back(shared_ptr<KlasaA>(new KlasaC)); vec.push_back(shared_ptr<KlasaA>(new KlasaA)); for (vector<shared_ptr<Klas...
You could use Boost.Foreach library. Then it will look pretty concise and clear: BOOST_FOREACH( boost::shared_ptr<KlasaA> v, vec ) { std::cout << v->foo(10) << std::endl; }
5,543,049
5,543,082
C++ using STL List, how to copy an existing list into a new list
Right now I'm working with a copy constructor for taking a list called val of type char, and I need to take all the elements of a string v that is passed into the copy constructor and put them into the val list. Public: LongInt(const string v); Private: list<char> val; So here in the public section of the LongInt cla...
In your LongInt constructor just use the iterator, iterator list constructor: LongInt(const string v) : val(v.begin(), v.end()) { } That being said, have you considered actually using string or possibly deque<char> to manipulate your sequence rather than list? Depending on your needs, those alternatives might be better...
5,543,331
5,543,351
Invalid use of incomplete type struct, even with forward declaration
I'm aware of circular dependencies, but even with forward declarations I get this area. What am I doing wrong? // facility.h class Area; class Facility { public: Facility(); Area* getAreaThisIn(); void setAreaThisIsIn(Area* area); private: Area* __area; }; // facility.cpp #include "facility.h" #includ...
For Facility* f = new Facility(); you need a full declaration, not just forward declaration.
5,543,407
5,683,713
Connecting IMPEG2DEMULTIPLEXER and ffdshow Directshow Filter
Essentially I am building a HDV capture graph. I have the graph functioning in graph builder and it works well. The graph builder graph can be seen here. In code the graph so far should go HDV Camera -> Demultiplexer -> FFDshow. But I get a VFW_E_NO_ACCEPTABLE_TYPES "There is no common media type between these pins." e...
The problem was found to be in the declaration of the AM_MEDIA_TYPE structure passed to the output pin on creation. The structure I used: AM_MEDIA_TYPE mt; ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE)); mt.majortype = MEDIATYPE_Video; mt.subtype = MEDIASUBTYPE_MPEG2_VIDEO; mt.formattype = FORMAT_MPEG2Video; mt.cbFormat = siz...
5,543,444
5,543,659
Preallocate memory for vector of strings (C++ vector<string>)
In C++, is there a clever (i.e. fast) way to pre-allocate memory for a vector of strings so that each element has some minimum size? The naive way I have is as follows: vector<string> my_string_vector; my_string_vector.resize(1000); for (unsigned int ui=0; ui<1000; ui++) my_string_vector[ui].reserve(1024); Many tha...
There's no fast way to do it. You can get fewer lines of code, but you're still going to make one call to reserve for each std::string in the std::vector. I believe EASTL or Boost.Pool may help, if you're willing to go that route.
5,543,465
5,543,640
template specialization
template<class T> struct ISocket { void connect(){} void raw_socket(){} }; template <class SocketType, class Arg1,class Arg2> struct ISocket< SocketType(Arg1,Arg2) > { typedef SocketType socket_type; typedef Arg1 arg_type; typedef Arg2 arg_type2; socket_type* raw_socket_; ISocket():raw_s...
First, ref_raw_socket_->connect();. You don't have a member ref_raw_socket_, only raw_socket_. Second, you initialize it to a temporary SocketType(). After your constructor, that object is destroyed, not there anymore, and your pointer is now a dangling pointer and it is undefined behaviour if you use it. Third, what d...
5,543,797
5,543,876
Creating a set<char> in C++
I am coding this thing and it would be helpful to have a static const set<char> containing some elements that won't change. class MyClass { private: static const set<char> mySet = ?? } How can I do this? It would be nice if you could create them from a string, like mySet("ABC"), but I can't get the syn...
Something like this will work just fine: // my_class.h class MyClass { static const std::set<char> mySet; }; // my_class.cpp const char *tmp = "ABCDEFGHI"; const std::set<char> MyClass::mySet(tmp,tmp+strlen(tmp));
5,543,956
5,655,407
How can I reduce the output from VS2010 project builds?
VS2010, 100+ projects in solution. I'm tired of seeing the 115+ lines of the "Project Performance Summary", "Target Performance Summary", and "Task Performance Summary" sections after each project is built. It shows up in the Output window -and- in the log file. There is nothing useful (to me) in those lines (usually...
Oops. I wasn't logged in when I posted or when I answered. And no my browser has lost the cookie or whatever that let it remember me. Otherwise, I would have editted the answer above. (Seems I'm doing everything wrong here.) I wanted to post the solution to the above problem. Hans was correct that the installation...
5,544,145
5,544,242
C++ Variable Memory Allocation
These are mostly compiler design questions. When your compiler compiles this, for example: int * pData = new int[256]; How is the memory allocated on-the-fly? Does the compiler make a call to an OS routine that allocates memory for you or is a function compiled that allocates the memory for you? Also, when you write so...
For the first question: When the new operator is encounter by the compiler like in your example: int * pData = new int[256]; It effectively emits code which looks like this: int *pData = reinterpret_cast<int*>(::operator new(256 * sizeof(int))); // the compiler may also choose to reserve extra space here or elsewhere ...
5,544,318
5,544,373
Overloading == operator C++
i did an overloading of the + operator but now i wanna do overloading of == operator of 2 lengths (may or may not be the same length) and return the respective results. How do i do it? Do i need to use bool for ==? //what i did for overloading + operator to get new length out of 2 different lengths Length operator+ (co...
For the simple case, use bool operator==(const Length& other) const. Note the const - a comparison operator shouldn't need to modify its operands. Neither should your operator+! If you want to take advantage of implicit conversions on both sides, declare the comparison operator at global scope: bool operator==(const Le...
5,544,384
5,544,393
Adding to the location of a pointer in C++
I have int foo which has the address of an integer in it. How do I add to the integer that foo is pointing to in one line? Solution: (*(int *)foo)+=1 This is how I handled it.
To add to the value the pointer is pointing to: int * pointer; int value; (*pointer) += value; // parans for clarity, not necessarily needed
5,544,445
5,544,486
libpng warning: Incompatible libpng version in application and library
I have an application which depends on a plethora of libraries (don't we all). Most of these libraries are installed via the package manager. For the ones which are not, I have re-compiled them but I still get the same libpng incompatibility error. libpng warning: Application was compiled with png.h from libpng-1.2.44 ...
It looks like your application is dynamically linking a .so library file installed somewhere other than the header you're using. You can ldd <binary> to figure out which .so your binary is picking up, and then grab the header file from that directory (unless it's a system directory) instead of the one you're using. You...
5,544,550
5,545,612
RNG crashing c++ program
I am currently coding a roguelike, and naturally am using a lot of random number generation. The problem I'm running up on is that if I "overheat" rand(); my program will crash. If i'm only generating 20 or so ints per frame, it's fine... but when the amount of random numbers goes into the hundreds, the program crashes...
A few comments and ideas on how to narrow down the source of the issue: It almost certainly is not the srand() or rand() functions causing the crash/lock up. Chances are that one, or more, combinations of random numbers is getting your engine into a state where something bad happens. The first step should be to duplic...
5,544,625
5,544,661
C++ : Appending text in form
I've been away from C++ for a while and it may just be me being stupid, but why does this give me an error (error below code). Code: // NetworkServer.cpp : main project file. #include "stdafx.h" #include "Form1.h" #include <winsock2.h> #include <iostream> using namespace std; using namespace NetworkServer; [STAThread...
Form1 is a type name, you need an object. I can't see the context of the code but as long as this code is written inside a method of the Form1 class then this-> will work. public ref class Form1 : public System::Windows::Forms::Form { //... public: void setUsers() { array<String^>^ connectedUsers = gcne...
5,544,790
5,544,839
How to get directory of a file which is called from command line argument?
For example, I am calling my executable in ubuntu: ./foo temp/game1.txt temp/game2 txt I am using realpath() to find the path to the game1.txt. Using it however will give me the full path including the game1.txt name. For example, it will come out as /home/*/Download/temp/game1.txt I want to erase game1.txt on that st...
Don't really know Linux, but a general way for your second question: #include <string> #include <iostream> int main(){ std::string fullpath("/home/*/Download/temp/game1.txt"); size_t last = fullpath.find_last_of('/'); std::string path = fullpath.substr(0,last+1); std::cout << path; } See on Ideone.
5,545,003
5,545,093
Generating parsers for binary structured data; metaprogramming or external scripts?
I'm writing a server that interfaces with a proprietary protocol. Currently most of the code consists of packet handlers that parse all of the fields of a packet, while making sure that the size of the data available is at least the minimum remaining size after each field. In addition to that, the packet handlers also ...
I've gone the route of creating my own language and tooling for binary structured data multiple times in the past, but that was in part driven by the need to support multiple target languages from the data definitions (at the time, C# and C++); I also created a third target to produce HTML reference documentation from ...
5,545,236
5,545,272
Enumerated Type Width?
Quick question. How wide are enumerated types? Are they of the minimum width required to represent the enumeration or are all enums ints? If they're ints, can you change the width of enums or would you have to type cast for each occurrence?
(This is for C++) From the standard: The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall ...
5,545,514
5,545,562
Convert char* to abitrary numeric type without using stringstream
I'd like to be able to convert a char* to an arbitrary numeric type T Similar to below, but without using the stringstream library, and obviously that one uses the string type which I don't want to use either. How would I go about doing this? e.g. template<class T> T string_as_T( const string& s ) { // Convert fro...
Traits? template<class T> char* fmt(T value) { throw new /*some exception, or return null*/; } char* fmt<int>(int value) { return "%d"; } // forgive rusty specialization syntax // write fmt<double>, char, float, long, etc template<class T> T string_as_T( const char* s ) { T val; sscanf(s, fmt(val), &...
5,545,516
6,279,314
Borderless window in clutter(mm)
I'm trying to use cluttermm to create a borderless window (for example, something like this). In other words, I want to draw a rectangle on screen and some text on it, but NOT in a window, and NOT with borders. Is clutter a really bad choice for this, or how can I do this? Thanks!
Clutter itself doesn't offer any API to do this, and defers to the platform's API to control the actual window. you can use Clutter-GTK and the GtkWindow API to remove the decoration from the window embedding the stage.
5,545,570
5,545,653
const string vs. #define
i need to share some strings in my c++ program. should i use #define or const string? thanks mystring1.h #define str1 "str1" #define str2 "str2" Or mystring2.h extern const string str1; extern const string str2; mystring.cpp const string str1 = "str1"; const string str2 = "str2";
Prefer the second option. If you use the first option (preprocessor), you are limiting your flexibility with the object. Consider the following... You won't be able to compare strings this way: if (str1 == "some string") { // ... }
5,545,641
5,546,202
error C1083: Cannot open include file: 'stdafx.h': No such file or directory in VS 2005
I am new to visual studio.I have created a simple console application and then selected an empty project of c++. I have pasted the code form http://www.cprogramming.com/tutorial/opengl_first_windows_app.html it is giving the following error error C1083: Cannot open include file: 'stdafx.h': No such file or directory...
Fall in the pit of success by using an appropriate project template. Which is Win32 + Win32 Project, don't tick the "Empty project" option on the property page. You'll get pre-generated code for a Win32 application, take a look at it since you might want to keep parts of it. Or just delete it all past the #include f...
5,545,689
5,545,769
Boost regex runtime error
I'm trying to use some code that I wrote on another computer that splits a string into tokens. This code compiles fine. The code also works as intended on some other computers. I've managed to reduce the code down to the following: #include <string> #include <boost/regex.hpp> typedef std::vector<std::string> token_t ;...
Since you're not using shared_ptr in your code, and I can see no other stuff that looks wrong AND it works on other machines, I'd say it's probably a bug in Boost.Regex. I bet the other machines have other versions of boost installed? If I had to guess I'd try changing the std::cout << *iter++ << std::endl; line first....
5,545,834
5,545,891
C++ : Writing to a console which opened a form
I have a console which opens a window. How do I write to this console, using values that I am getting from controls on the form? For example such as text fields?
To access the console under windows, you have to link your program as a console-application. In Visual C++ you can configure this in the Project Settings under Configuration Properties/Linker/System/Subsystem = Console. Linking your application as a concole-application does not mean you can't open a window. It just mea...
5,545,866
6,176,204
CMFCCaptionBar with multiple buttons?
I made a subclass of CMFCCaptionBar in what has so far been a vain attempt to make it do something more useful than just having a single icon, single text field, and single button while still maintaining the same look, feel, and other GUI functionality. Reference: http://msdn.microsoft.com/en-us/library/bb983960%28v=vs...
As far as I know, you can try to use a CMFCRebar and a CMFCToolbar instead. See the RebarTest demo for details
5,545,867
6,242,673
How to implement an FPS camera without GLU on OSX (Or cross platform) c++
I'm trying to get an FPS style camera working, while following along from the examples in the openGL SuperBible book. It was all going very well until I ran into the problem where you end up having roll happen, when you really only want pitch and yaw. Similar question This question is basically asking the same thing, b...
Thanks for everyones answers but the problem I had was this. In the openGL super bible, I was using their built in frame of reference class, and the problem I had was two functions, one called rotate, and rotateWorld. I needed to use rotate for up/down movement, and rotateWorld for left right movement. This made the ca...
5,545,897
5,545,925
Multiple Inheritance with clashing methods
I am writing some templated pure virtual base classes that are multiply inherited and discovered a minor oddity in the process. The crux of it is, if you define the same method in two base classes, inheriting from both compiles and works fine and it appears that you only need a single definition in the derived class. I...
The functions have different signatures (one takes an int, and one takes a float), and as such are not really "the same". The template magic obfuscates that a little bit, but it's the same as if you had foo(int) and foo(float) - those are two different functions. You could have foo(int) const and foo(int), those would ...
5,546,197
5,546,271
null shared_ptr can access to member functions
I can access member functions of a null shared_ptr object : #include <memory> #include <iostream> class A { public: int getNum() {return 1234;} }; int main() { std::shared_ptr<A> pA(nullptr); std::cout << pA->getNum() << std::endl; } returns 1234 while I was expecting an exception. Same result happens f...
Technically, what you did here does entail undefined behavior. However, because your getNum method is not virtual and makes no use whatsoever of this, it happens not to crash this time. To see why, imagine that the compiler internally rewrote your program like so: class A { }; int A_getNum(A* this) { return 1234; }...
5,546,425
5,546,523
Access violation reading location 0xcdcdcdcd. C++
Essentially what I'm trying to do at this point is build a program to allow you to pick from 3 different classes (Tank, Mele, Ranged) when you pick the class you would then give it a name of 20 or fewer chars. After picking 5 classes and giving each champ a name it would print out the name and health of each class you ...
The variable char name[20] is not valid after leaving the first for() You should copy the value of the array in the constructor to an array inside Champion or dynamically allocate memory for the name. This is one option: #include <stdio.h> #include <string.h> class Champion { char name[20]; public: Champion(con...
5,546,426
5,546,655
Syntax Highlighting in Arbitrary File Types
I'm using Code::Blocks for a project that uses templated classes, and I'm separating the implementation from the declaration with .tpp files. However, Code::Blocks doesn't recognize that .tpp is a C++ file, so syntax highlighting does not work. How can I add the association?
Maybe this site can help you: http://wiki.codeblocks.org/index.php?title=Creating_a_custom_lexer_for_Code::Blocks_editor
5,546,536
5,547,103
Question about functors
The correct answer for this is D, but what I'm confused about is when exactly is the add operation in class dunno taking place? How are the numbers being added? Consider the following partial C++ code: #include <vector> #include <iostream> using namespace std; template<class Iter, class Formatter> void mystery(Iter ...
When we call mystery() | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ^ ^ | | front end front is from v.begin(); end is from v.end() (note: this is one past the end) followed by a -- operator that moves it back one. Now we start the loop: w...
5,546,588
5,546,623
Any non-(char*) proper way to initialize void* from const string in C++
I was given with a MSVC project that doesn't worked with gcc. Particularly this error is interesting: void * str; str = "data"; // error str = (char*)"data"; // working Error is: Error: invalid conversion from ‘const void*’ to ‘void*’, so g++ (gcc 4.x) treats the string as const void, but how that MSVC tre...
You've pretty much answered your own question. MSVC++ is, for compatibility's sake, allowing the same license that plain C does, to treat string literals as having type char * rather than const char *. To make it work with gcc without fixing the types, you need to write (char *)"data" everywhere you have bare "data"....
5,546,631
5,574,404
Web-CAT CxxTest Eclipse GUI for test results not showing up
I am trying to execute test cases using CxxTest framework on Eclipse. After following instructions on this website - http://web-cat.cs.vt.edu/eclipse/cxxtest/ I am able to build the test case, but when I run it, it doesn't show the GUI (green/red bar) as shown in the article. I checked CxxTest guide, it mentioned abou...
I found the solution to seeing GUI results by adding a view tab using IN ECLIPSE Window-> Show view -> Other -> CxxTest.
5,546,706
5,546,757
Stack implemented with dynamic array
Suppose we implement a stack using a dynamically allocated array. If the array fills, we are faced with a dilemma. From among the following choices, select the one that best describes our strategy for handling a filled array. (a) We declare a new array, twice as big as the original, and copy the data into the new ...
Say your stack was 128 elements and you ended up having to store 4096 elements in it. How many times would you have to resize the array when doubling vs. extending it by a constant 128 items each time?
5,546,725
5,546,744
How to write user input to a text file using fputs in C++
I am not the best programmer with c++ but I am trying to learn. I am trying to take user input and write it into a text file (without overwriting the old one) but I can't figure out where to plugin the variable (int). Here is my code so far... int main() { int i; cout << "Please enter something: "; cin >> i; ...
I think this would do: { string i; // dont forget to #include <string> cout << "Please enter something: "; cin >> i; FILE * pFile; pFile = fopen ("C:\\users\\grant\\desktop\\test.txt","a"); if (pFile!=NULL) { fputs("C++ Rocks!", pFile); fputs(i.c_str(), pFile); } fclose (pFile); getch();...
5,546,787
5,546,813
C++ spaces mark end of input in cin?
I'm just learning some stuff about cryptography and I made a cool program to encrypt any message by rotating the letters through the alphabet a given number of letters...anyway...I have it all set up but I can't give it multiple words to encrypt because it ends the input after one word...(using cin)...how would I get c...
How about std::getline()? http://www.cplusplus.com/reference/iostream/istream/getline.html Example: #include <iostream> #include <string> using namespace std; string line; getline( std::cin, line );
5,546,905
5,552,544
android + pthread + c++ = SIGSEGV
The following code compiles and runs on standard linux: #include <iostream> #include <pthread.h> using namespace std; class Foo { public: Foo(); void go_thread(); void stop_thread(); private: static void* worker( void* param ); pthread_t m_pt; }; Foo::Foo() { m_pt ...
The issue seems to be combining iostream with pthread. I went through and replaced all couts with printf()s, removed the using clause, and removed the iostream header. The code compiled and ran with no issue on the device. I wonder if this is something Google should be made aware of? The final (working) code looks l...
5,546,957
5,547,111
C++ Template Design Question
I have a model written in C++ which is based on run-time polymorphism and virtual functions. The model works completely fine as is. I'd like to investigate converting this to templates and compile-time polymorphism. The reasons are that: Only one class in the model is truly dynamic at run-time, the rest are compile...
Static and dynamic polymorphism do not mix well, and where they interact with one another, some form of branching is required to turn run-time information into a choice among statically configured variants. You could use a simple type generator to at least reduce the repetition of your physics model: template< class P...
5,546,985
5,547,239
How can i create watchdog timer using c++ and boost
What is the best and shortest way to create a WatchDogTimer class, which can wait some time and then died? So when I'm doing something like WatchDogTimer wdt (10); wdt will be available only in next 10 seconds. How can I do this? ps: yeah, I saw that thread, but it did not actually help.
Create an object on the heap with new and hand it to a shared_ptr. Then hold that shared pointer only from a thread that sleeps for 10 seconds before exiting. Make sure the thread is the only instance of shared_ptr and all other references are weak_ptrs. After the 10 seconds weak_ptr::get() will return null.
5,547,079
5,548,130
simple getopt implementation in C++
I am implementing project specific "getopt" in C++. For this I implemented a class that looks like this: class MyGetOptions { private: typedef std::map<std::string, bool> optionsTbl; optionsTbl m_optionsTbl; int m_currentArg; // Prohibit copy and assignment. MyGetOptions ( const M...
Instead of using global variables, I prefer to use return values with combination with "?" like as below else if ((option.compare("?") == 0) && (getOptStatus == 0)) { // if ? and return value 0 means finds a string in argv that is not // registered with add options. continue; } else if ((option.compare("?")...
5,547,201
5,547,555
What is the fastest way to draw formatted text in the Win32 API?
I am implementing a text editor in C++ just using the vanilla Win32 API and I'm trying to find the best way to implement syntax highlighting. I know that there are existing controls out there like scintilla, but I'm doing this for fun so I want to do most of the work myself. I also want it to be fast and lightweight....
Both DrawText and TextOut are wrappers for ExtTextOut, so ExtTextOut is the low-level API. In my experience, ExtTextOut is pretty fast, so I doubt you'll see any performance issues with ExtTextOut itself. However, creating/selecting fonts can be a source of performance issues, so if you are switching back and forth b...