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
2,846,138
2,846,148
Microsoft #include header file (.h) for "_HFILE"
I'm trying to compile some Microsoft SAPI example code in a non-Microsoft C++ Compiler, and am getting an error at this line: _HFILE m_hfilePrev; Presumably because it doesn't recognize the _HFILE #define. Does anybody know what .h file I should include for that?
It is defined in crtdbg.h typedef void *_HFILE; /* file handle pointer */
2,846,310
2,846,320
Are .dll files loaded once for every program or once for all programs?
I have a simple small question which someone who knows will be able to answer easily, I searched google but couldn't find the answer. There are many programs running at once on a computer, and my question is: when a program loads a DLL, does it actually load the DLL file or does it find the memory in which the DLL is a...
It's loaded once and all programs share the same in-memory copy of code. It's kind of complicated, but for the read-only sections of the DLL (that is, code) the operating system loader uses a technique called "memory mapping" to map the DLL into the process's address space. The pages are only loaded into physical memor...
2,846,501
2,846,514
atol(), atof(), atoi() function behaviours, is there a stable way to convert from/to string/integer?
In these days I'm playing with the C functions of atol(), atof() and atoi(), from a blog post I find a tutorial and applied: Here are my results: void main() { char a[10],b[10]; puts("Enter the value of a"); gets(a); puts("Enter the value of b"); gets(b); printf("%s+%s=%ld and %s-%s=%ld",a,b,(at...
The high-end solution to this problem, given that you also added a C++ tag, is to use Boost lexical_cast.
2,846,502
2,846,535
Build System with Recursive Dependency Aggregation
I recently began setting up my own library and projects using a cross platform build system (generates make files, visual studio solutions/projects etc on demand) and I have run into a problem that has likely been solved already. The issue that I have run into is this: When an application has a dependency that also has...
The typical way that this is handled is by having the library on which you depend tell you what it, in turn, requires and what versions it has linked against. One way of doing this is via pkg-config. For example, if you invoke pkg-config name_of_package --cflags, it will print out the necessary flags that should includ...
2,846,546
2,846,579
number of elements in a static array of a predefined size
I have an array like this: int a[100]; I am filling only the first 4 elements in this array: a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; When I do sizeof(a)/sizeof(a[0]) it returns 100. Is there a way I can get number of elements to which I have assinged a value and thus filtering out the remaining 96 unassigned eleme...
All elements must be assigned to something, thus the array always has 100 elements. If you can ensure all the elements are initialized to a special value which means "unassigned" to you (e.g. -1), you can work it out like this: // fill the array with a special value which means "uninitialized" const int special_uninit...
2,846,611
2,846,776
Visual Studio 2008 compiler macro reference or tutorial?
Does anyone know the location of a good list or tutorial showing all the compiler macros (_T etc) in use in Visual Studio 2008?
See here: a starting point for C++ specific: http://msdn.microsoft.com/en-us/library/503x3e3s(v=VS.80).aspx a general list: http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx a starting point for MFC: http://msdn.microsoft.com/en-us/library/f2dch7fb(v=VS.100).aspx
2,846,622
2,846,661
Creating a menustrip in WinAPI?
Is there a way to get a menustrip instead of an HMENU when using the WinAPI? Like menus that .Net applications use? Because the HMENU just doesn't fit my color scheme, I need a darker menu. Thanks
If you don't like the system defaults, you can owner-draw the menu. If you only need to support Windows Vista and higher, you can follow this article. Otherwise you need to call ModifyMenu() on your menu items and set MF_OWNERDRAW and everything that comes with that.
2,846,644
2,846,650
C++ Type error with Object versus Object reference
I have the following function (which worked in Visual Studio): bool Plane::contains(Vector& point){ return normalVector.dotProduct(point - position) < -doubleResolution; } When I compile it using g++ version 4.1.2 , I get the following error: Plane.cpp: In member function âvirtual bool Plane::contains(Vector&)â: ...
Your problem is that the result of point - position is a temporary object, which cannot be bound to a non-const reference. If a function does not modify an argument taken by reference, then it should take a const reference. Ergo, your dot product function should be declared as: double Vector::dotProduct(const Vector&...
2,846,844
2,854,818
Wii MotionPlus support
I am developing a PC application that interacts with the Wiimote. So far I have been using the wiiuse library, which has worked great. However, wiiuse does not support the MotionPlus extension. I have heard of extensions to implement this by Dolphin and libogc but have not managed to locate this code. Do you know of co...
I found that fWIIne has a modded version with MotionPlus support, though only in the release zip file and not the repository.
2,846,872
2,846,893
Thread-safe get (accessor method)
I'm currently using the following code for thread-safe access of a variable. int gnVariable; void getVariableValue(int *pnValue) { acquireLock(); //Acquires the protection mechanism *pnValue = gnVariable; releaseLock(); //Releasing the protection mechanism } I would like to change my API signature to a mo...
Since you gave C++ as an option, you can wrap the mutex lock/unlock. You can then return the value directly: class lock_wrapper { public: lock_wrapper() { acquireLock(); } ~lock_wrapper() { releaseLock(); } }; int getVariableValue() { lock_wrapper lw; return gnVariable;...
2,846,939
2,846,950
List<MyClass*> & array question
Assuming a definition like this, void CConfigTest::OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; TVITEM item = pNMTreeView->itemNew; // find the session of the selected item if(item.hItem != NULL) { HTREEITEM root, parent, node; ...
Lists do not support random access. You need to switch to another container type which does, or iterate over the list until you reach the element you want.
2,847,019
2,847,073
Flexible string handling in Visual Studio 2008 C++
I'm slowly starting to get the hang of the _T stuff in Visual Studio 2008 c++, but a few things still elude me. I can see the benefit of the flexibility, but if I can't get the basics soon, I think I'll go back to the standard way of doing this - much less confusing. The idea with the code below is that it scans the p...
You can use _tstring to represent and std::string with a TCHAR parameter. Also, the name of the function is _tcscmp, not _tccmp so I don't see how that code snippet could even compile? To be honest, I wouldn't bother with any of that, though. The whole TCHAR stuff was useful back when people were writing code that was ...
2,847,153
2,847,417
How to draw a web page into a memory DC?
I would like to trick Chrome in to rendering its tabs in some memory device context of mine. Is this possible at all ? Thank you !
There's a method in chrome.tabs called captureVisibleTab. What you get back is either a PNG or JPEG. http://code.google.com/chrome/extensions/tabs.html That API is available to Chrome extensions - but you can't call it from ordinary JavaScript in an unextended browser. I presume this is the technique used by "Aviary ...
2,847,310
2,847,350
C++ smart pointer for a non-object type?
I'm trying to use smart pointers such as auto_ptr, shared_ptr. However, I don't know how to use it in this situation. CvMemStorage *storage = cvCreateMemStorage(); ... use the pointer ... cvReleaseMemStorage(&storage); I'm not sure, but I think that the storage variable is just a malloc'ed memory, not a C++ class obje...
shared_ptr allows you do specify a custom deallocator. However, looking at the documentation cvReleaseMemStorage() doesn't have the right form (void f(T*)) and you need a wrapper: void myCvReleaseMemStorage(CvMemStorage* p) { cvReleaseMemStorage(&p); } shared_ptr<CvMemStorage> sp(cvCreateMemStorage(), &myCvReleaseM...
2,847,334
2,847,362
Constructor initialization list: code from the C++ Primer, chapter 16
Toward the end of Chapter 16 of the "C++ Primer" I encountered the following code (I've removed a bunch of lines): class Sales_item { public: // default constructor: unbound handle Sales_item(): h() { } private: Handle<Item_base> h; // use-counted handle }; My problem is with the Sales_item(): h() { } li...
What you have with Sales_item(): h() { } is a constructor with a data member initialization. I would have expected something like either: a) Sales_item(): h(0) { } which is a convention the authors have used repeatedly in earlier chapters, or This isn't necessary because the constructor of Handle<Item_base>() can be ...
2,847,410
2,848,961
Goal of C's "auto" keyword
What is the goal of the "auto" keyword in C? With C++ 0x it got new meaning but does it mean that my code will break if I port C code over to a C++ 0x compiler?
Bjarne Stroustrup mentions in his C++0x FAQ about auto: "The old meaning of auto ("this is a local variable") is redundant and unused. Several committee members trawled through millions of lines of code finding only a handful of uses -- and most of those were in test suites or appeared to be bugs." So I a...
2,847,488
2,847,529
Is RegSetValueEx thread safe?
I suspect that RegSetValueEx is thread safe, but would like some confirmation from the community. If called from multiple threads, will there be any side effects? The RegSetValueEx MSDN documentation doesn't mention thread safety at all.
related Q: Is the Win32 Registry ‘thread safe’?
2,847,729
2,847,747
What's the main difference between stdlib.h and cstdlib in C++?
I'm using EXIT_FAILURE macro, so I need to include stdlib.h or cstdlib. But I don't know what the difference is. Should I use cXXX style header file rather than XXX.h? Thank you.
As EXIT_FAILURE is a macro, it makes no difference which you include. The cstdlib version will put the names of all the functions into the std namespace, so you can say things like: std::exit(0); but as macros don't respect namespaces, you can't say: std::EXIT_FAILURE
2,847,734
2,847,768
Is `auto int i` valid C++0x?
In answering this question the question arose as to whether the traditional C meaning of the keyword auto (automatic storage) is still valid in C++0x now that it means type deduction. I remember that the old meaning of auto should remain where relevant but others disagreed. auto char c = 42; // either compilation erro...
No, it is not. In fact, §7.1.6.​4/3 gives the following example: auto x = 5; // OK: x has type int const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int static auto y = 0.0; // OK: y has type double auto int r; // error: auto is not a storage-class-specifier As you can see, it results in an err...
2,847,787
2,847,835
Constructor or Assignment Operator
Can you help me is there definition in C++ standard that describes which one will be called constructor or assignment operator in this case: #include <iostream> using namespace std; class CTest { public: CTest() : m_nTest(0) { cout << "Default constructor" << endl; } CTest(int a) : m_nTest(a) { cout << "In...
What is happening here depends a bit on your compiler. It could create a temporary object using the int constructor and then copy construct b from that temporary. It will most likely elide the copy constructor call however. In neither case will the assignment operator be used.
2,847,872
2,848,255
GUI system architecture?
I'm designing GUI (graphical user interface) system for a game engine (C++). Idea is to create a heirarchy of GUI controllers like Focusable, Hoverable, Dragable etc. Every GUI component can attach multiple controllers, they modify component's behaviour. I think it gives flexible system and protects from code duplicati...
Your solution is quite good, to be honest, I think it is exactly what the Decorator design pattern is about, however in C++ you have better implementation techniques at hand. You can easily use policy based design to create GUI component template class and add component behaviour trait classes as its arguments and then...
2,848,068
2,848,183
boost::regex_replace() replaces only first occurrence, why?
My code: #include <string> #include <boost/algorithm/string/regex.hpp> std::cout << boost::algorithm::replace_regex_copy( "{x}{y}", // source string boost::regex("\\{.*?\\}"), // what to find std::string("{...}") // what to replace to ); This is what I see: {…}{y} Thus, only the first occurrence replaced....
You might want to use replace_all_regex_copy() instead of replace_regex_copy()
2,848,087
2,848,109
How to clear stringstream?
stringstream parser; parser << 5; short top = 0; parser >> top; parser.str(""); //HERE I'M RESETTING parser parser << 6; //DOESN'T PUT 6 INTO parser short bottom = 0; parser >> bottom; Why doesn't it work?
Typically to 'reset' a stringstream you need to both reset the underlying sequence to an empty string with str and to clear any fail and eof flags with clear. parser.str( std::string() ); parser.clear(); Typically what happens is that the first >> reaches the end of the string and sets the eof bit, although it success...
2,848,347
2,848,571
How can I access all matches of a repeated capture group, not just the last one?
My code is: #include <boost/regex.hpp> boost::cmatch matches; boost::regex_match("alpha beta", matches, boost::regex("([a-z])+")); cout << "found: " << matches.size() << endl; And it shows found: 2 which means that only ONE occurrence is found… How to instruct it to find THREE occurrences? Thanks!
This is what I've found so far: text = "alpha beta"; string::const_iterator begin = text.begin(); string::const_iterator end = text.end(); boost::match_results<string::const_iterator> what; while (regex_search(begin, end, what, boost::regex("([a-z]+)"))) { cout << string(what[1].first, what[2].second-1); begin ...
2,848,585
2,848,628
cpp/Qt : per class debugging
I'm developing a Qt application. For each class, I'm trying to mimic the framework, such as error() and errorString() method, use of Private implementation. But I would like to add a per class debugging: Set a macro to the desired level of debug, have a macro or a function that knows the level of debug, and use qDebu...
You may write a class, for example CDebug with all needed debug methods, and use it in other classes, like: class CMyDialog : public QDialog, public CDebug {...};
2,848,809
2,848,884
Set size of scroll thumb?
I'v looked on MSDN and can't find how to do this. It lets me set the range and position but not the thumb that the user clicks and drags. Thanks
You want to set the scroll page size, so it calculates the proportional size of the bar given the range and page size. Look at SetScrollInfo and related functions.
2,848,928
2,849,024
Strange C++ thread function invocation
I have the following: class DThread { virtual void run()=0; _beginthreadex(NULL,0,tfunc,this,0,&m_UIThreadID); // class itself being passed as param to thread function... static unsigned int __stdcall tfunc(void* thisptr) { static_cast<DThread*>(thisptr)->run(); r...
Most platform-level thread APIs are bare-bones C and take a plain pointer to function to run in new thread. This means in C++ that function has to be either a free function or a static member. Neither of these give access to any class instance. The workaround for building statefull thread classes is to exploit addition...
2,849,795
2,849,818
Is there a standard C++ grammar?
Does the standard specify the official C++ grammar? I searched, but did not find it anywhere. Also, I wish to read a bit about C++ grammar in detail, like which category of grammars it falls in, etc. Any links pointing me in the right direction would be helpful. By category, I mean taken from here.
Yes, it does. The grammar is described in detail throughout the standard and is summarized in Appendix A: Grammar Summary (it's Appendix A in both the C++03 standard and the C++0x final committee draft). You can purchase the C++03 standard or you can download the C++0x FCD (it's document n3092 on that page). To answ...
2,849,827
4,539,399
Translations using Qt Linguist?
I am working on Ubuntu 9.10 aka Karmic Kola and latest version of gcc, Qt 4.6.2. I have installed the french fonts and hindi fonts for ubuntu. I changed the language and Keyboard layout accordingly so that I could type in the abovementioned languages. It worked fine. I then made a sample application and added appropria...
After banging my head many times on this problem, I decided to try translations on a newer version of Qt and VOILA it did the trick. Probably there is a bug in Qt translations module in the version I was using. Notified Qt guys about the same. Hope others will find this information valuable. Cheers!!!
2,849,901
2,849,982
empty struct definitions illegal in C but not C++?
struct t_empty { }; This appears to compile properly in C++ but not C. (at least with the TI 28xx DSP compiler, where it emits the error "expected a declaration") Is this mentioned somewhere in the C standards, or is my compiler broken?
Empty struct is a syntax error in C. The grammar of C language is written so that it prohibits empty structs. I.e. you won't find it stated in the standard explicitly, it just follows from the grammar. In C++ empty classes are indeed legal. P.S. Note, that often you might see the quote from the C standard that says "If...
2,850,142
2,850,239
How can I use boost::thread::id as key to an unordered_map?
According to the documentation, a boost::thread::id can be considered unique for each running thread and can be used in containers such as std::set and std::map (because the < operator is overridden for thread::id). My problem is that I'd like to use thread::id as a key to an boost::unordered_map, however it requires t...
You can use the streaming ability: struct Hasher { size_t operator()(const boost::thread::id& id) { std::ostringstream os; os << id; return hash(os.str()); } }; Little excerpt of the class, so that others may see what's possible: class thread::id { public: id(); bool operator==(const id& y) const; ...
2,850,157
2,866,408
How to delete ProgIDs from other user accounts when uninstalling from Windows?
I've been investigating "how should a modern windows c++ application register its file types" with Windows (see C++: How do I correctly register and unregister file type associations for our application (programatically)). And having combed through the various MSDN articles on the subject, the summary appears to be as ...
I just realized: What MS wants us to do is to have per-user override the file mapping itself - i.e. .foo -> what? NOT create any progIDs, which should only be created by the installer, which are deleted by their uninstaller, so no "dangling ProgIDs" - only "dangling file mappings" which map to a missing ProgID, which ...
2,850,312
2,850,354
Use of for_each on map elements
I have a map where I'd like to perform a call on every data type object member function. I yet know how to do this on any sequence but, is it possible to do it on an associative container? The closest answer I could find was this: Boost.Bind to access std::map elements in std::for_each. But I cannot use boost in my pro...
You can iterate through a std::map object. Each iterator will point to a std::pair<const T,S> where T and S are the same types you specified on your map. Here this would be: for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it) { it->second.Method(); } If you still want to use std::for_each,...
2,850,433
2,851,443
Using a class callback for a custom control?
I'm creating a custom control class and since I want complete control of it, I register the class and want to use the class's LRESULT CALLBACK OGLTOOLBAR::ToolProc(HWND, UINT, WPARAM, LPARAM) but it's not letting me. I'm doing: HWND OGLTOOLBAR::create(HWND parent,HINSTANCE hInst, int *toolWidthPtr) { if (toolhW...
If ToolProc isn't a static member, you can't pass a member function pointer as a callback like that, assuming you want ToolProc to be a non-static function, you can create a static member function, and use the GetWindowLong/SetWindowLong and the GWL_USERDATA area, to store a pointer to the current object(this), and hav...
2,850,613
2,850,729
Reading lines from a file using std:: istream_iterator. Who?
Possible Duplicate: How do I iterate over cin line by line in C++? I need to read all lines from a file: std::ifstream file("..."); std::vector<std::string> svec( (std::istream_iterator<std::string>(file)), (std::istream_iterator<std::string>()), ); but it is read as words.
I believe the issue is that the input methods for std::string will read until a space character is found, then terminate. Have you tried using std::getline inside a loop? Check out the C++ FAQ.
2,850,646
2,860,583
Fill container with template parameters
I want to fill the template parameters passed to a variadic template into an array with fixed length. For that purpose I wrote the following helper function templates template<typename ForwardIterator, typename T> void fill(ForwardIterator i) { } template<typename ForwardIterator, typename T, T head, T... tail> void f...
There is no need to count the number of types in a parameter pack manually, thats what the sizeof... operator is for. Additionally i'd make the iterator type for fill() deducible, there is no need to specify it explicitly: template<typename T, typename FwdIt> void fill(FwdIt it) { } template<typename T, T head, T... t...
2,850,815
2,851,586
What is the inet_addr function equivalent in C#
i need to know how to use an IP address like inet_addr("192.168.0.2"); in C++ where this returns DWORD. My wrapper in C# treats this field as an Int? Can anyone help on this misunderstanding?
You should use the IPAddress class. It will hassle you a bit because it tries to prevent you from taking a dependency on IP4 addresses. The Address member is declared obsolete. Here is the workaround: using System; using System.Net; class Program { static void Main(string[] args) { var addr = IPAddress....
2,851,100
2,851,191
Why do I get errors when using unsigned integers in an expression with C++?
Given the following piece of (pseudo-C++) code: float x=100, a=0.1; unsigned int height = 63, width = 63; unsigned int hw=31; for (int row=0; row < height; ++row) { for (int col=0; col < width; ++col) { float foo = x + col - hw + a * (col - hw); cout << foo << " "; } cout << endl; } The...
Unsigned integers implement unsigned arithmetic. Unsigned arithmetic is modulo arithmetics. All values are adjusted modulo 2^N, where N is the number of bits in the value representation of unsigned type. In simple words, unsigned arithmetic always produces non-negative values. Every time the expression should result in...
2,851,202
2,851,312
callback for each for loop iteration
a bit of a naive question, but nonetheless. I am trying to break up a for loop in which a 2d Matrix is being read. I would like to write a callback function to consume row-wise/col-wise chunks per row/col iteration. Any hints on how to tie up the callback function with iteration? bool ReadMatrix(const int** array) { ...
My first take would be for your callback to take the array, a row index, a row span, and column index and a column span. class functor { public: void operator()(int data[][], size_t row_idx, size_t row_span, size_t col_idx, size_t col_s...
2,851,217
2,851,489
Basic C++ class how to implement with Objective C
I have some problems with implementing class which written in C++, because I not familiar with c++ .. if someone could help with implementing it in Objective C #ifndef ENTITY_H #define ENTITY_H class BaseGameEntity { private: int m_ID; static int m_iNextValidID; void SetID(int val); public: Base...
This is rougly equivalent to that C++ class: // In BaseGameEntity.h #import <Cocoa/Cocoa.h> @interface BaseGameEntity : NSObject { NSInteger m_ID; } - (id)initWithID:(NSInteger)ID; - (void)update; // must be defined by subclasses - (NSInteger)ID; @end // In BaseGameEntity.m #import "BaseGameEntity.m" @implemen...
2,851,326
2,891,403
Getting QT to respond to power-events (sleep/hibernate)
I'm trying to develop software that is intelligent wrt sleep events (cleanly closing network connections, making sure data restart locations are set properly, etc). Are there mechanisms in QT (4.6) currently that facilitate me responding to system power events?
I dont think there's a native to qt and multi platform way for these but there are propably some ways and api's to do things you are looking for. Posix signals might provide something to notify your app about ongoing system events. Also you might want to look QDbus stuff, some cases dbus will broadcast system events.. ...
2,851,384
2,851,407
stl priority queue based on lower value first
I have a problem with stl priority queue.I want to have the priority queue in the increasing order,which is decreasing by default.Is there any way to do this in priority queue. And what is the complexity of building stl priority queue.If i use quick sort in an array which takes O(nlgn) is its complexity is similar to ...
Use a different comparator as the 3rd template argument of std::priority_queue. priority_queue is a container adaptor that works on any sequence you define. The performance of insertion is equal to the std::push_heap operation and takes logarithmic time. So the complexity to sorting after all insertions are done isn't ...
2,851,517
2,851,552
Naming a typedef for a boost::shared_ptr<const Foo>
Silly question, but say you have class Foo: class Foo { public: typedef boost::shared_ptr<Foo> RcPtr; void non_const_method() {} void const_method() const {} }; Having a const Foo::RcPtr doesn't prevent non-const methods from being invoked on the class, the following will compile: #include <boost/shared_p...
The name of a typedef does not represent the syntactical construct used to define its type. The typedef name should convey some of its desired meaning. For example, the Standard defines the names of iterators over const T as const_iterator, even though the iterator itself is not const (you can still increment it). In f...
2,851,616
2,851,688
Template meta-programming with member function pointers?
Is it possible to use member function pointers with template meta-programming? Such as: class Connection{ public: string getName() const; string getAlias() const; //more stuff }; typedef string (Connection::*Con_Func)() const; template<Con_Func _Name> class Foo{ Connection m_Connect; public: Foo(){ ...
Check out this discussion on the subject of pointers-to-nonstatic-members as template parameters. It looks like there are issues with the VC++ implementation.
2,851,868
2,852,641
Multiset container appears to stop sorting
I would appreciate help debugging some strange behavior by a multiset container. Occasionally, the container appears to stop sorting. This is an infrequent error, apparent in only some simulations after a long time, and I'm short on ideas. (I'm an amateur programmer--suggestions of all kinds are welcome.) My container ...
In the simulation, where I have commented // Add some events to currentEvents events were being added to currentEvents. (Hope that was clear.) If an event was added that happened to belong at the top of the queue, I believe it messed up the iterator pointing to currentEvents.begin(). I reset the iterator immediately b...
2,851,991
2,852,234
(static initialization/template instantiation) problems with factory pattern
Why does following code raise an exception (in createObjects call to map::at) alternativly the code (and its output) can be viewed here intererestingly the code works as expected if the commented lines are uncommented with both microsoft and gcc compiler (see here), this even works with initMap as ordinary static varia...
The problem is not related to initialization order, but rather to template instantiation. Templated code is instantiated on demand, that is, the compiler will not instantiate any templated code that is not used in your program. In particular, in your case the static class member FactoryBase<>::factory_helper_ is not be...
2,852,140
2,852,183
priority queue clear method
How do I delete all elements from a priority queue? That means how do I destroy a priority queue? advanced thanks for your answer. Is there any clear- or erase-like method?
The priority_queue interface doesn't have a clear() method (for no good reason I've ever been able to discern). A simple way to clear it is just to assign a new, empty queue: priority_queue <int> q; // use it q = priority_queue <int>(); // reset it
2,852,348
2,852,368
Loop through hex variable in C
I have the following code in a project that write's the ascii representation of packet to a unix tty: int written = 0; int start_of_data = 3; //write data to fifo while (length) { if ((written = write(fifo_fd, &packet[start_of_data], length)) == -1) { printf("Error writing to FIFO\n"); ...
These are the ASCII codes of characters: 31 is '1', 33 is '3' etc. 0D and 0A are the terminating new line characters, also known as '\r' and '\n', respectively. So if you convert the values to characters, you can print them out directly, e.g. with printf using the %c or %s format codes. As you can check from the table ...
2,852,390
2,852,419
Reading long int using scanf
To read an int using scanf we use: scanf("%d", &i); What if i is a long not int?? Note: when using %d with long it gives me an irritating warning..
Just use long l; scanf("%ld", &l); it gives me an irritating warning.. That warning is quite right. This is begging for stack corruption.
2,852,400
3,737,644
Using an initializer_list on a map of vectors
I've been trying to initialize a map of <ints, vector<ints> > using the new 0X standard, but I cannot seem to get the syntax correct. I'd like to make a map with a single entry with key:value = 1:<3,4> #include <initializer_list> #include <map> #include <vector> using namespace std; map<int, vector<int> > A = {1,{3,4}...
As the comment above has mentioned, {1,{3,4}} is a single element in the map, where the key is 1 and the value is {3,4}. So, what you would need is { {1,{3,4}} }. Simplifying the error: error: no matching function for call to map<int,vector<int>>::map(<brace-enclosed initializer list>) Not a precise error, but somewh...
2,852,557
2,855,188
Protecting Content Files
I want a simple layer of protection for my content (resource) files in my application. For example, I have various sound and image files used in my application. I think, I can wrap them in a SFX archive (Probably packed with WinRAR), then in my application, start the SFX exe with some parameters, like, -silent. But thi...
Don't use a SFX archive. Well a lot depends on how you use your resources. If you have a lot of library code that requires file names then the files have to be persisted on hard drive for a while. If you can, you want to find out if your sound and media libraries can be passed pointer - then you load the files up yours...
2,852,637
2,853,402
C++ program runs slow in VS2008
I have a program written in C++, that opens a binary file(test.bin), reads it object by object, and puts each object into a new file (it opens the new file, writes into it(append), and closes it). I use fopen/fclose, fread and fwrite. test.bin contains 20,000 objects. This program runs under linux with g++ in 1 sec but...
Unfortunately file access on Windows isn't renowned for its brilliant speed, particularly if you're opening lots of files and only reading and writing small amounts of data. For better results, the (not particularly helpful) solution would be to read large amounts of data from a small number of files. (Or switch to Lin...
2,852,772
2,852,840
Wrong reading file in UNICODE (fread) on C++
I'm trying to load into string the content of file saved on the dics. The file is .CS code, created in VisualStudio so I suppose it's saved in UTF-8 coding. I'm doing this: FILE *fConnect = _wfopen(connectFilePath, _T("r,ccs=UTF-8")); if (!fConnect) return; fseek(fConnect, 0, SEEK_END); lSize = ftel...
ftell(), fseek(), and fread() all operate on bytes, not on characters. In a Unicode environment, TCHAR is at least 2 bytes, so you are allocating and reading twice as much memory as you should be. I have never seen fopen() or _wfopen() support a "ccs" attribute. You should use "rb" as the reading mode, read the raw b...
2,852,775
2,888,489
boost lambda versus phoenix
I recently started looking at boost phoenix, as replacement for lambda. Is phoenix a full replacement for lambda, or is there some lambda functionality which is not provided by phoenix? is phoenix mature? Are there any gotcha I should know about? my primary interest are operator composition, control statements and cas...
This post answers all your questions. Phoenix is very mature. Phoenix and lambda will be merged. It will be the base for future lambda implementations.
2,852,878
2,852,881
Is this a memory leak?
char *pointer1; char *pointer2; pointer1 = new char[256]; pointer2 = pointer1; delete [] pointer1; In other words, do I have to do delete [] pointer2 as well? Thanks!
Nope, that code is fine and won't leak memory. You only have to use delete[] once because you've only used one new to allocate an area for memory, even though there are two pointers to that same memory.
2,852,895
2,856,241
C++ iterate or split UTF-8 string into array of symbols?
Searching for a platform- and 3rd-party-library- independent way of iterating UTF-8 string or splitting it into array of UTF-8 symbols. Please post a code snippet. Solved: C++ iterate or split UTF-8 string into array of symbols?
Solved using tiny platform-independent UTF8 CPP library: char* str = (char*)text.c_str(); // utf-8 string char* str_i = str; // string iterator char* end = str+strlen(str)+1; // end iterator do { uint32_t code = utf8::next(str_i, end); // get 32 bit code of a utf-8 ...
2,852,907
2,853,127
problem finding a header with a c++ makefile
I've started working with my first makefile. I'm writing a roguelike in C++ using the libtcod library, and have the following hello world program to test if my environment's up and running: #include "libtcod.hpp" int main() { TCODConsole::initRoot(80, 50, "PartyHack"); TCODConsole::root->printCenter(40, 25, T...
What happens here, is that 1) make evaluates the target all, which resolves to partyhack. 2) make evaluates the target partyhack, which resolves to $(CPP_OBJS) 3) make evaluates the target $(CPP_OBJS), which resolves to $(TMP)partyhack.o 4) make evaluates the target $(TMP)partyhack.o which resolves to partyhack.o This ...
2,852,952
2,853,010
Purpose of boost::checked_delete
I don't understand the purpose of boost::checked_delete. The documentation says: The C++ Standard allows, in 5.3.5/5, pointers to incomplete class types to be deleted with a delete-expression. When the class has a non-trivial destructor, or a class-specific operator delete, the behavior is undefined. Some...
The most common example of an incomplete type is one that has only been declared: // this file does not include the definition of foo class foo; void bad(foo *f) { delete f; // undefined behavior if there exists foo::~foo } In reality, the definition of foo may look like this: class foo { public: ~foo() { ....
2,852,984
2,853,067
C++ Set Erase Entry Question
I encountered a problem here. I'm using C++ multiset. This is the test file. Score: 3-1 Ben Steven Score: 1-0 Ben Score: 0-0 Score: 1-1 Cole Score: 1-2 Ben I'm using while loop and ifstream (fin1) to read in from the test file above. multiset<string, less<string> > myset; while(!fin1.eof()) { fin1 >> scoreName; ...
If I understand what you're trying to do, I think it would be easier to remember whether the team had won, drawn or lost when you read the "Score" line and only insert the following lines (ie. "Ben") if the team hasn't lost. Inserting everyone and then erasing ones you didn't want seems overcomplicated to me :) For ref...
2,853,029
2,853,053
C/C++ usage of special CPU features
I am curious, do new compilers use some extra features built into new CPUs such as MMX SSE,3DNow! and so? I mean, in original 8086 there was even no FPU, so compiler that old cannot even use it, but new compilers can, since FPU is part of every new CPU. So, does new compilers use new features of CPU? Or, it should ...
gcc will support newer instructions via command line arguments. See here for more info. To quote: GCC can take advantage of the additional instructions in the MMX, SSE, SSE2, SSE3 and 3dnow extensions of recent Intel and AMD processors. The options -mmmx, -msse, -msse2, -msse3 and -m3dnow enable the use of t...
2,853,100
2,855,633
Problem passing a reference as a named parameter to a variadic function
I'm having problems in Visual Studio 2003 with the following: void foo(const char*& str, ...) { va_list args; va_start(args, str); const char* foo; while((foo = va_arg(args, const char*)) != NULL) { printf("%s\n", foo); } } When I call it: const char* one = "one"; foo(one, "two", "three", ...
VS2005 also crashes on it. The problem is that va_start uses the address of the argument given to it, and since str is a reference, its address is the address of the "one" variable defined int the caller, not the address on the stack. I see no way of getting the address of the stack-variable (the argument that actually...
2,853,133
2,853,168
What am I not getting about this abstract class implementation?
PREFACE: I'm relatively inexperienced in C++ so this very well could be a Day 1 n00b question. I'm working on something whose long term goal is to be portable across multiple operating systems. I have the following files: Utilities.h #include <string> class Utilities { public: Utilities() { }; virtual ~Utiliti...
Utilities *u = new Utilities(); tells the compiler to make a new instance of the Utilities class; the fact that UtilitiesWin extends it isn't necessarily known and doesn't affect it. There could be lots of classes extending Utilities, but you told the compiler to make a new instance of Utilities, not those subclasses....
2,853,275
2,853,561
What new Unicode functions are there in C++0x?
It has been mentioned in several sources that C++0x will include better language-level support for Unicode(including types and literals). If the language is going to add these new features, it's only natural to assume that the standard library will as well. However, I am currently unable to find any references to the n...
Does the new library provide standard methods to convert UTF-8 to UTF-16, etc.? No. The new library does provide std::codecvt facets which do the conversion for you when dealing with iostream, however. ISO/IEC TR 19769:2004, the C Unicode Technical Report, is included almost verbatim in the new standard. Does the new l...
2,853,431
2,853,450
C++ - Need to learn some basics in a short while
For reasons I will spare you, I have two weeks to learn some C++. I can learn alone just fine, but I need a good source. I don't think I have time to go through an entire book, and so I need some cliff notes, or possibly specific chapters/specialized resources I need to look up. I know my Asm/C/C# well, and so anything...
I know you said you didn't want to read a book but "Accelerated C++" is probably what you want. It was actually was used in like a 2 week crash course at Stanford from what I remember to get people up to speed on C++.
2,853,438
2,853,451
C++ Vector of pointers
For my latest CS homework, I am required to create a class called Movie which holds title, director, year, rating, actors etc. Then, I am required to read a file which contains a list of this info and store it in a vector of pointers to Movies. I am not sure what the last line means. Does it mean, I read the file, cre...
It means something like this: std::vector<Movie *> movies; Then you add to the vector as you read lines: movies.push_back(new Movie(...)); Remember to delete all of the Movie* objects once you are done with the vector.
2,853,615
2,853,622
get length of `wchar_t*` in c++
Please, how can I find out the length of a variable of type wchar_t* in c++? code example below: wchar_t* dimObjPrefix = L"retro_"; I would like to find out how many characters dimObjPrefix contains
If you want to know the size of a wchar_t string (wchar_t *), you want to use wcslen(3): size_t wcslen (const wchar_t *ws);
2,853,703
2,853,854
Modify an object without using it as parameter
I have a global object "X" and a class "A". I need a function F in A which have the ability to modify the content of X. For some reason, X cannot be a data member of A (but A can contain some member Y as reference of X), and also, F cannot have any parameter, so I cannot pass X as an parameter into F. (Here A is an dia...
If you don't want F to reference X globally, then you could 'set' it on the object before calling the "worker" method. E.g. class A { public: A() : member_x(NULL) { } void SetX(X* an_x) { member_x = an_x; } void F(); { member_x->Manipulate(); } private: X* member_x; }; X global_x; A global_a; void DoStu...
2,853,901
19,693,285
boost::serialization with mutable members
Using boost::serialization, what's the "best" way to serialize an object that contains cached, derived values in mutable members? class Example { public: Example(float n) : num(n), sqrt_num(-1.0) {} // compute and cache sqrt on first read float get_sqrt() const { if(sqrt_...
You can check the Archive::is_loading field, and load cached values if it's true. template <class Archive> void serialize(Archive& ar, unsigned int version) { ar & num; if(Archive::is_loading::value == true) sqrt_num = -1.0; }
2,854,156
2,860,124
Partial specialization with reference template parameter fails to compile in VS2005
I have code that boils down to the following: template <typename T> struct Foo {}; template <typename T, const Foo<T>& I> struct FooBar {}; //////// template <typename T> struct Baz {}; template <typename T, const Foo<T>& I> struct Baz< FooBar<T,I> > { static void func(FooBar<T,I>& value); }; //////// struct MySt...
For me it looks like VS2005 uses the first template specification of Baz template <typename T> struct Baz {}; This struct does indeed not contain a member named func. Looks like VS2005 doesn't deduce the template parameters correctly.
2,854,178
2,855,041
How to access webbrowser object on this code? C++
I found this example http://www.mvps.org/user32/webhost.cab that host an Internet Explorer WebBrowser object, and it uses this code to access the object void webhostwnd::CreateEmbeddedWebControl(void) { OleCreate(CLSID_WebBrowser,IID_IOleObject,OLERENDER_DRAW,0,&site,&storage,(void**)&mpWebObject); mpWebObject->S...
mpWebObject is a member of the class webhostwnd. You can use the code, IWebBrowser2* iBrowser; mpWebObject->QueryInterface(IID_IWebBrowser2,(void**)&iBrowser); anywhere in the class to access the browser interface( once the mpWebObject is created). If you are not hell bent on using the same code, here is a better ex...
2,854,301
2,854,316
Is there a better way to check if a value is bigger than of type double?
double x; cin>>x; if( x > 1.7976931348623157e+308 || x < -1.7976931348623157e+308 ) { cout<<"value not in range"<<endl; exit(1); } Is there like a DOUBLE_MAX or DOUBLE_MIN and would I need to include any header files?
There are constants for the largest and smallest double types, but since x is of type double, x cannot be larger or smaller than these values! If you wish to compare an inputted value to these limits you'll need to parse the string yourself and check for overflow.
2,854,554
2,854,574
What speech libraries are available in Linux?
When it comes to TTS (text-to-speech) libraries in Linux, what choices do developers have? What libraries ship with the majority of distros? Are there minimal libraries? What functionality does each library offer? I'm approaching this primarily from a C++ point of view, although Python would suit me too.
Use Flite as your speech library, and then use voices from festival or festvox.
2,854,563
2,857,118
Lua/SWIG wrap userdata from within Lua
I am using swig-lua. I have a function in Lua which I call and it returns me a pointer (userdata). right now I know what this pointer is, but how can I tell Lua from within Lua?
From the Lua Reference Manual: setmetatable (table, metatable) Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) You cannot "tell Lua" what a userdata is within Lua. It must be given a metatable or manipulated through bound function calls using the C...
2,855,121
4,493,621
What is the purpose of using -pedantic in the GCC/G++ compiler?
This note says: -ansi: tells the compiler to implement the ANSI language option. This turns off certain "features" of GCC which are incompatible with the ANSI standard. -pedantic: used in conjunction with -ansi, this tells the compiler to be adhere strictly to the ANSI standard, rejecting any code which is not complia...
GCC compilers always try to compile your program if this is at all possible. However, in some cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers such as GCC or g++ must issue a diagnostic when these extensions are encountered. For example, the GCC compiler’s -pedantic opt...
2,855,214
2,855,267
How can I assign pointer member with long string?
When I did the practice below to erase my pointer member and assign new value to it. (*pMyPointer).member.erase(); (*pMyPointer).member.assign("Hello"); // Successfully Than I tried more... (*pMyPointer).member.erase(); (*pMyPointer).member.assign("Long Multi Lines Format String"); // How to? If the long multi lines...
I really have no clue what you are trying to ask. Maybe this: (*pMyPointer).member.assign("Long Multi Lines Format String" "more lines that will be" "concatenated by the compiler"); Or did you mean line breaks like this: (*pMyPointer).member.assign("Long Multi Li...
2,855,504
2,856,225
What is the best practice when coding math class/functions?
I'm currently implementing some algorithms into an existing program. Long story short, I created a new class, "Adder". An Adder is a member of another class representing the physical object actually doing the calculus , which calls adder.calc() with its parameters (merely a list of objects to do the maths on). To do t...
You have chosen a very wide subject, so here is a broader answer. Be aware of your surroundings Too often I have seen code doing the same thing as elsewhere in the codebase. Make sure that the problem you are trying to solve has not already been solved by your team-mates or predecessors. Try not to reinvent the whee...
2,855,750
2,855,813
Showing a progress bar while SFX archive is extracting
I'm writing a program with C++ and by native Win32 API. I'm creating a process from a SFX archive EXE in silent mode that no GUI is shown to user. But I want to show a progress bar in my application, while the SFX archive extracting. How can I do that? Thanks.
If the process you create produces some textual output to the standard output then you can probably parse that output somehow and show the progress. To know if it does, activate it in a command line windows and watch what you get from it. win32's CreateProcess() allows you to redirect the standard output of the process...
2,855,874
2,856,229
How to cast a pointer of memory block to std stream
I have programed an application on windows XP and in Visual Studio with c++ language. In that app I used LoadResource() API to load a resource for giving a file in the resource memory. It returned a pointer of memory block and I wanna cast the pointer to the std stream to use for compatibility. Could anyone help me? ...
Why would you need this? Casting raw data pointers to streams means byte-by-byte copying of your resource and, therefore, lacks in performance (and, also to mention, I don't see any benefit in this approach). If you want to work with raw memory, work with it. Casting here (compatibility?) seems to be a very strange ap...
2,855,884
2,860,753
Use the right tool for the job: embedded programming
I'm interested in programming languages well suited for embedded programming. In particular: Is it possible to program embedded systems in C++? Or is it better to use pure C? Or is C++ OK only if some features of the language (e.g. RTTI, exceptions and templates) are excluded? What about Java in this domain? Thanks.
Is it possible to program embedded systems in C++? Yes, of course, even on 8bit systems. C++ only has a slightly different run-time initialisation requirements than C, that being that before main() is invoked constructors for any static objects must be called. The overhead (not including the constructors themsel...
2,855,968
2,856,052
How do I toggle 'always on top' for a QMainWindow in Qt without causing a flicker or a flash?
void MainWindow::on_actionAlways_on_Top_triggered(bool checked) { Qt::WindowFlags flags = this->windowFlags(); if (checked) { this->setWindowFlags(flags | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint); this->show(); } else { this->setWindowFlags(flags ^ (Qt::Customi...
Nokia says no: It is not possible to make changes to the window flags once the window has been created without causing flicker. Flicker is unavoidable since the window needs to be recreated. But sometimes if you're stuck with a flashing effect that's kind of ugly like this, you can intentionally drag it out to make it ...
2,856,156
2,856,186
Constructors for C++ objects
I have class Person as following : class Person { char* name; int age; }; Now I need to add two contructors. One taking no arguments, that inserts field values to dynamically allocated resources. Second taking (char*, int) arguments initialized by initialization list. Last part is to define a destructor sho...
In the default constructor, allocation of the char array should include its desired size, e.g. this->name = new char[32]; Note that this size includes the terminating 0 character, so the effective length of names you can store in this array is 31. In the parameterized constructor, you can simply assign the given param...
2,856,176
2,871,808
How to make windows media player go to previous song in playlist?
I am writing a simple Windows app in c++, that will be able to send commands to windows media player. My problem is that I want my app to move to the previous song in the playlist. IWMPControls::previous() seems to do the job, but its behavior differs from what is written in msdn. In fact this function rewinds current ...
Well, I think I figured it out. You can force the previous song by 1) first calling IWMPControls::put_currentPosition(0.0), 2) then calling IWMPControls::previous(). There can be some problems, as it seems that some time must pass between 1) and 2). The obvious solution is to use ::PostMessage() inside your program (NO...
2,856,334
2,856,579
EXE stops working if containing folder is renamed. MSVCP90.dll
This popup comes up as soon as the app is started: The program can't start because MSVCP90.dll is missing from your computer. Before anyone says "install the VC++ runtimes", wait! If I rename the folder containing my .EXE then the app runs. If I rename it back, it breaks. The app has been running for weeks without an...
It seems that there is a .exe.manifest file lying around, specifying some other version of MSVCP90.dll. Removing this file should do the trick (In theory the manifest is the solution against dll hell, but in reality it is just a new PITA).
2,856,721
2,856,747
Linkage Error with Inherited Class
I have static library and another program which uses it. In the static library If I define header without inheretence it works fine. class TcpCommunication On the other hand If I use inheretence with a QT class, class TcpCommunication:public QTcpServer I'm getting linkage error when I compiling code which uses this ...
The application using your static library also needs to link to QT
2,857,157
2,857,809
stdout and stderr character encoding
i working on a c++ string library that have main 4 classes that deals with ASCII, UTF8, UTF16, UTF32 strings, every class has Print function that format an input string and print the result to stdout or stderr. my problem is i don't know what is the default character encoding for those streams. for now my classes work ...
stdout and stderr use "C" locale. "C" locale is netural, and in most system translated into the current user's locale. You can force the program to use a specific locale using setlocale function: // Set all categories and return "English_USA.1252" setlocale( LC_ALL, "English" ); // Set only the LC_MONETARY category and...
2,857,272
2,857,379
Can't compile std::map sorting, why?
This is my code: map<string, int> errs; struct Compare { bool operator() (map<string, int>::const_iterator l, map<string, int>::const_iterator r) { return ((*l).second < (*r).second); } } comp; sort(errs.begin(), errs.end(), comp); Can't compile. This is what I'm getting: no matching functio...
Maps are, by definition, sorted by their keys, so you can't resort a map by its values. You can provide an alternate comparison function as the third template parameter to a map, if you want to sort the keys by a non-default order. If you're trying to sort a map by its values, then perhaps you could try using Boost.Mul...
2,857,526
2,858,556
Genetic programming in c++, library suggestions?
I'm looking to add some genetic algorithms to an Operations research project I have been involved in. Currently we have a program that aids in optimizing some scheduling and we want to add in some heuristics in the form of genetic algorithms. Are there any good libraries for generic genetic programming/algorithms in c+...
I would recommend rolling your own. 90% of the work in a GP is coding the genotype, how it gets operated on, and the fitness calculation. These are parts that change for every different problem/project. The actual evolutionary algorithm part is usually quite simple. There are several GP libraries out there ( http://en....
2,857,589
2,857,637
Can I avoid a circular dependency in my Matrix class's iterators?
We have two classes: template<typename T, typename Size, typename Stack, typename Sparse> class Matrix and template<typename T, typename Size> class Iterator Matrix should be able to return begin and end iterators and Iterator will keep a referrence to the Matrix to access the elements via it's interface. We don't w...
In order to iterate, iterators typically do need to know about the internal storage they iterate over - this coupling can usually not be avoided. Take a map iterator for example - it is going to have to know about the internal tree structure of the map in order for it to do its job.
2,857,864
2,857,959
QTextEdit with different text colors (Qt / C++)
I have a QTextEdit box that displays text, and I'd like to be able to set the text color for different lines of text in the same QTextEdit box. (i.e. line 1 might be red, line 2 might be black, etc.) Is this possible in a QTextEdit box? If not, what's the easiest way to get this behavior? Thanks.
Use text formated as HTML, for example: textEdit->setHtml(text); where text, is a HTML formated text, contains with colored lines and etc.
2,858,127
2,858,291
"multiset" & "multimap" - What's the point?
As the question states ... I don't get the point about multisets / multimaps. So, what's the purpose?
Some use cases: multimap With ZIP code as a key, all people which have that ZIP code With account ID as key, all open orders of that person/account A dictionary, with per keyword various explanations multiset is in essence a map with a key and a integer count. The inventory of a shop, all products have their key and...
2,858,134
2,858,157
Windows message when mouse leave a control?
I have created a control and the mosemove for that control makes it change color, but I want to change it back to default when my mouse moves out of that control. I would have thought WM_MOUSELEAVE would do it but it didn't. Thanks
That would be the correct message. Are you calling TrackMouseEvent?
2,858,136
2,858,639
Can I detect (and warn on) redundancies at compile time?
Is there any way I can catch and warn about redundancies at compile time? Such as if (abc && abc) or if (def || def) Ok, this isn't actually from an optimisation point of view - I'm thinking more along the lines of a mistake in code - so when the coder intended to write if (abc && abc) when actually they meant to w...
If you're looking for a tool that statically checks for dubious-looking code, you most likely need some form of lint. Industrial-strength lint implementations check for many, many things--I don't know if it will check for the kind of redundancy you gave as an example, but it's worth a try.
2,858,217
2,858,236
How do I extend mouse space in OpenGL windowed mode
How do I extend the distance the mouse can move in an OpenGL window? What I wish to achieve is an fps like interface where the cursor is hidden and camera rotations are not limited by the mouse having to remain inside the window boundaries.
This is often implemented by "warping" the mouse back to the center of the screen, in Linux. Here is a forum thread on this, using the popular SDL library to do the actual mouse reading. In Windows, look into using lower-level input API:s, such as XInput.
2,858,398
2,858,471
Gradients for polygons in OpenGL
what is the best way to create a gradient for a 2D polygon in OpenGL, (Linear, and Radial)? Thanks How can you generate textures for radial gradients on the fly?
Linear is very easy - you just set different colors to different points like red ---- red | | | | | | blue ---- blue for radial texture might be better option to generate it on fly create empty texture then fill it with function sqrt((MAXX - x)^2 + (MAXY - y)^2), then add color to it.
2,858,483
2,860,396
How can I compare the performance of log() and fp division in C++?
I’m using a log-based class in C++ to store very small floating-point values (as the values otherwise go beyond the scope of double). As I’m performing a large number of multiplications, this has the added benefit of converting the multiplications to sums. However, at a certain point in my algorithm, I need to divide a...
Do you divide by the same integer multiple times? If so you can instead multiply by 1./yourInteger, and only do the divide once. That would be faster than either if possible. As to your actual question, it's not only compiler and architecture dependent, but also micro-architecture and data dependent. On your particul...
2,858,724
2,859,280
Link one shared library static to my shared library
I am struggeling a little bit with some options for linking on a project I am currently working on: I am trying to create a shared library which is linked against 2 other libraries. (Lets call them libfoo.so and libbar.so) My output library has to be a shared library and I want to static link libfoo.so to the resulting...
There are two Linux C/C++ library types. Static libraries (*.a) are archives of object code which are linked with and becomes part of the application. They are created with and can be manipulated using the ar(1) command (i.e. ar -t libfoo.a will list the files in the library/archive). Dynamically linked shared obje...
2,858,979
2,859,608
CComPtr CoCreateInstance returns 0x80070582 (Class already exists.)
I have a StartComObjects function called when the user presses the Login button and a StopComObjects function called when the user presses the Cancel button. The StartComObjects function uses CComPtr.CoCreateInstance to create the COM object and sets up some connection points using AfxConnectionAdvise. When the user ...
It is a Windows error (facility 7, error code 1410), caused by RegisterClass(Ex). This sample code reproduces it: #include "stdafx.h" #include <windows.h> #include <assert.h> int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR, int) { WNDCLASSEX wcex = { sizeof(WNDCLASSEX) }; wcex.style = CS_HREDRAW...
2,859,062
2,859,136
Can a constructor return a NULL value?
I know constructors don't "return" anything but for instance if I call CMyClass *object = new CMyClass() is there any way to make object to be NULL if the constructor fails? In my case I have some images that have to be loaded and if the file reading fails I'd like it to return null. Is there any way to do that? Thanks...
I agree with everyone else that you should use exceptions, but if you do really need to use NULL for some reason, make the constructor private and use a factory method: static CMyClass* CMyClass::create(); This means you can't construct instances normally though, and you can't allocate them on the stack anymore, which...
2,859,435
2,860,759
Suggestions on error handling of Win32 C++ code: AtlThrow vs. STL exceptions
In writing Win32 C++ code, I'd appreciate some hints on how to handle errors of Win32 APIs. In particular, in case of a failure of a Win32 function call (e.g. MapViewOfFile), is it better to: use AtlThrowLastWin32 define a Win32Exception class derived from std::exception, with an added HRESULT data member to store the...
AtlThrow isn't terribly useful, it throws CAtlException which merely wraps an error code. Having a MapViewOfFile fail is a truly exceptional problem with a low-level error code that doesn't tell you or your user much at all what actually went wrong. Handling the error is almost always impossible, it isn't likely that...
2,859,761
2,859,891
adding virtual function to the end of the class declaration avoids binary incompatibility?
Could someone explain to me why adding a virtual function to the end of a class declaration avoids binary incompatibility? If I have: class A { public: virtual ~A(); virtual void someFuncA() = 0; virtual void someFuncB() = 0; virtual void other1() = 0; private: int someVal; }; And later modify...
I'm a bit surprised that this particular rearrangement helps at all. It's certainly not guaranteed to work. The class you give above will normally be translated to something on this order: typedef void (*vfunc)(void); struct __A__impl { vfunc __vtable_ptr; int someVal; }; __A__impl__init(__A__impl *object)...