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,041,223 | 5,041,656 | Learning C++ using a template | Do you recommend learning C++ using a template?
Edit
I have basic programming language (I know how to work with things like loops, arrays, classes and functions) and I have been recommended to follow tutorials in a template that is already made for creating games.
I would like to become a game programmer.
| The short answer to your question is yes.
The longer answer is yes, BUT you need to consider when to move into the C++ template world. C++ is a very rich languare and comes with enormous power and possibilities. To use this power one needs responsibility and one must have the knowledge to use things wisely. There are m... |
5,041,290 | 5,041,330 | Which c++ free (none GPL) library to use if I like to encrypt text? | does crypto++ will be fine?
i like to use public keys method
| Crypto++ is excellent and can handle public/private keys. Openssl is also excellent, non-GPL, but is really a C library. And Botan is another good choice, also non-GPL
|
5,041,496 | 5,041,792 | Are there noteworthy uses of m4 besides autoconf? | Does someone know of any uses of m4 besides autoconf (preferably in a c or c++ environment) that is more than just an academic excerise, because it helped solve a problem that would otherwise (for example with a 'standard' preprocessor) have been difficult to solve.
I ask this because I am thinking about a way to do a ... | I have once used m4 to generate a C++ header file from a text file containing a simple version string (MAJOR.MINOR.MICRO-STATUS), and information from subversion, for a Windows Visual Studio project.
m4 was the smallest macro engine that I could easily embed and use for this specific goal.
It looked like this:
#ifndef ... |
5,041,861 | 5,042,238 | ImportError: dynamic module does not define init function, but it does | I'm trying to write a binding for a vendor C++ library. I've successfully used snippets such as the below to define init functions in the other modules, but in this one it doesn't seem to work: it compiles fine, but throws the ImportError as soon as I try to import it into a test script. What could be wrong here?
#ifnd... | This turned to be unrelated to Python or the compiler, but was an incorrect compiler incantation (have to pay more attention while editing the Makefile).
|
5,041,984 | 5,042,172 | Does hash_map.erase invalidate all iterators? | std::hash_map is not part of the C++ standard but is part of extensions to standard library. For example it is defined for VS2005. Would normally std::hash_map.erase invalidate all iterators to std::hash_map? Presumably, the memory can be reallocated to a smaller array when elements are removed to optimize for memory u... | It looks like it is specified in VS2005 example in the documentation:
Each element contains a separate key and a mapped value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element with a number of operations that is independent of the number of elements in the sequen... |
5,042,221 | 5,042,244 | calling const member function | i have called const member function of an object.
I created an object on MainWindow, den called get_size() after setting size previously.
calling get_size() method of base class Gtk::Window.
It gives error: ‘Gtk::Window’ is not an accessible base of ‘MainWindow’.
MainWindow is inherited from Gtk::Window class
class Ma... | Inhertance is private by default for classes. You need to derive from Gtk::Window publicly:
class MainWindow: public Gtk::Window {
|
5,042,280 | 5,042,400 | viability of c++ logging library for asynchronous capturing of high throughput data? | I am working with a real time system written in C++. We are looking to use either boost or pantheios for logging. The system has some standard logging requirements which I'm confident can be met by either framework, but in addition we want to be capable of logging all input captured by this system. This input will b... | I am using the Boost logging library written by Jon Torjo and this one offers to do all writing to log files from a dedicated thread, so you have no I/O delays on the thread doing the logging. This has the disadvantage thought, that when the system crashes some log statements might not be logged, as it makes use of an... |
5,042,744 | 5,042,759 | 3-d animation in C++ | I am doing a scientific project in C++ and I need to draw simple animated 3-d images of moving atomic groups. What is a good and convenient graphics library to do that? Some general remarks are also appreciated. I work in Linux.
Thank you in advance, Roman
| OpenGL of course,
one library you could use is glut for that.
have a look on http://nehe.gamedev.net/
|
5,042,801 | 5,048,839 | Does x64 mono require x64 class library? | I compiled an x64 mono (version 2.11) on Windows.
I noticed that every program that use a class library (System.Net, System.IO, ...) crash systematically.
I downloaded the latest version of class library, it works ok on x86 but not on x64.
Does x64 mono require x64 class library ?
The x64 compatibity issue on Windows p... | Currently, a 64-bit mono runtime does not require a different set of class libraries than a 32-bit mono runtime.
You do however need to ensure your version of the class libraries matches the version the runtime is expecting. If they didn't match you will normally get an error message to the console on startup.
A cowork... |
5,042,924 | 5,043,197 | Using std::bad_alloc for C pointers | I'm using a library written in C in a C++ project.
I'd like to use C++ exceptions to handle C errors. In particular, it would be nice to have an exception thrown if an allocation fails.
I can do this in constructors of classes which hold C-style pointers to C structs :
if (c_object == NULL)
throw std::bad_alloc();
... | It has been already mentioned in the comments, I merely repeat it as an answer:
But if the class is responsible for several C objects they are no ways of free-ing all already allocated pointers since the destructor isn't called.
That is correct. Because of this and the single-responsibility principle, each C++ class ... |
5,043,225 | 5,043,398 | Which Gdiplus::Graphics::DrawImage function should I use? | I want paste a (x,y,w,h) subrectangle from src to dest, so that the (x,y) source pixel appears as the (0,0) dest pixel. I'm having a difficulty deciding which of the gazillion overloads does this. Right now my code looks like this, which obviously doesn't work:
auto_ptr<Gdiplus::Graphics> g(Gdiplus::Graphics::FromHDC(p... | Anyone would work, they work equally well. They are mostly just aliases for each other. The one I guess you are using would be this one which states that:
x [in] REAL Real number that specifies
the x-coordinate of the upper-left
corner of the destination rectangle at
which to draw the image.
y [in] REAL Real num... |
5,043,368 | 5,043,396 | A grammar question about c++ | BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
if (start > end) return NULL;
// same as (start+end)/2, avoids overflow
int mid = start + (end - start) / 2;
BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
BinaryTree *parent = new BinaryTree(list->data);
parent->left = leftCh... | This is a reference to a pointer. Any changes you make to ListNode (making it point at something else) will affect the variable that was passed to the function.
If you remove this, the recursive calls, e.g. BinaryTree *leftChild = sortedListToBST(list, start, mid-1);, will modify a copy of list instead of the actual li... |
5,043,403 | 46,589,798 | Listing only folders in directory | I want to list folders in a directory in C++, ideally in a portable (working in the major Operating Systems) way. I tried using POSIX, and it works correctly, but how can i identify whether the found item is a folder?
| Using the C++17 std::filesystem library:
std::vector<std::string> get_directories(const std::string& s)
{
std::vector<std::string> r;
for(auto& p : std::filesystem::recursive_directory_iterator(s))
if (p.is_directory())
r.push_back(p.path().string());
return r;
}
|
5,043,581 | 5,043,622 | MSDN - is it they or me? | In here I cannot find header type_traits. Is it missing or I'm missing something (again...).
| Because its here:
http://msdn.microsoft.com/en-us/library/bb982198.aspx
It's an extension to the standard library.
|
5,043,718 | 5,043,736 | Function parameter - pointer or reference to a pointer? | void DeleteChildren(BSTNode *node)
{
// Recurse left down the tree...
if(node->HasLeftChild()) DeleteChildren(node->GetLeftChild());
// Recurse right down the tree...
if(node->HasRightChild()) DeleteChildren(node->GetRightChild());
// Clean up the data at this node.
node->ClearData(); // assume... | No, pointers are passed by value, so you're in essence "copying" the pointer when you pass it as a parameter. Only pass by reference when you want the callee to modify the parameter in the caller.
|
5,043,758 | 5,043,785 | C/C++ overwriting array bounds | What is a good way to detect bugs where I overwrite an array bound?
int a[100];
for (int i = 0; i<1000; i++) a[i] = i;
It would be helpful to collect a list of different strategies that people have used in their experience to uncover bugs of this type.
For example, doing a backtrace on from the point of the memory fau... |
Static code analysis (e.g. lint)
Runtime memory analysis (e.g. valgrind)
Avoid fixed-size buffers, prefer dynamically sized containers
Use sizeof() instead of magic numbers whenever you can
|
5,044,084 | 5,044,137 | What library or graphics engine would be suitable for a full-screen professional retail tool? | I find myself in the unique position of having to find a suitable 2D graphics engine (or 3D with easy-to-use support for 2D interfaces) for the creation of a simple, full-screen retail sales tool for my business. I have been considering the use of the SDL library after briefly reviewing its features. It seems fairly ea... | Instead of SDL, go for QT. It is more feature rich and you can do the same (and much more) as in SDL.
This answer explains how to create full-screen windows, so that partially answers your question.
Another part of the answer to your question is this : you can create an opengl widget, in which you can do 2d/3d graphic... |
5,044,129 | 5,044,313 | cURL - put output into an integer variable | I am writing a c++ program that uses cURL and I am trying to read from a php file on a site into an integer variable. I found a post that is similar but I am having trouble adapting that to use an integer variable.
Any help would be very appreciated.
| Read into a string, then use atoi().
|
5,044,167 | 5,044,225 | What should be avoided to write memory-leak-safe code using STL? | I've used STL for quite a while now, but mostly to implement algorithms for the sake of it, other than the occasional vector in other code.
Before I start using it more, I wanted to know what the common mistakes people make when using STL are -- in particular, are there any things I should watch for when using STL temp... | There are a lot of bottlenecks in using STL effectively, if you want to know more I'd suggest the book "Effective STL" by S.Meyers.
|
5,044,409 | 5,044,665 | Events and event handling under the hood | I've just been working through some simple programs using SDL and it made me think back to some Java GUIs I've written.
In the simple SDL programs, I have a loop that checks for any events (keypresses, mouse clicks etc...) and reacts to them. Essentially it's polling for input.
In Java, you attach listeners to the GUI... | "...does Java just handle this polling loop in the background for us...?"
Pretty much, yes. The UI system provides the program with access to a queue that contains events that have occurred and the target. The program runs through a loop requesting items from this queue and then does whatever. Libraries like Qt and ... |
5,044,621 | 5,044,970 | What are C++ interpreters used for? | I wonder what is the usage of C++ interpreters. When are they at their best?
| Like any interpreter, I would say there are two uses:
scripting
experimentation
I don't see scripting catching on for C++, the language is too verbose and there are other more viable alternatives there (python/ruby/shell).
The experimentation however is very attractive. Being able to test a construct on the side is l... |
5,044,792 | 5,044,908 | including header file in a separate folder | I created a class (say, myclass.h/cpp). I want to use the class from many different places. Therefore, I put those files in a folder (say, C:\cpp_include) and I want to include them from whatever folder my codes are. I have a code which uses the class (say, main.cpp). In main.cpp, I include myclass:
#include "myclass... | A simple technique is to have build scripts (makefiles) in the cpp directories. Write a rule that traverses the directories, executing the build scripts. This one step in isolating functionality and also allows one to use libraries.
|
5,044,817 | 5,044,864 | Reading data into a queue | Using the following (incomplete) code, I am attempting to insert 10 strings into a string queue (declared and defined further down), then read the contents out one at a time, however the output from the queue doe snot correspond to the expected output
int main()
{
ifstream File;
for (int count = 1; c... | First pass: You add PL1, remove PL1, add PL1. Queue now contains PL1.
Second pass: You add PL2, remove PL1 (which is at front), add PL1 (filename is updated by remove). Queue now contains PL2, PL1
Third pass: You add PL3, remove PL2 (which is at front), add PL2 (filename is updated by remove). Queue now contains PL1, P... |
5,044,829 | 5,046,871 | Unmanaged dependency dll fails to load when functions called | I am working in with Makefiles in Cygwin in XP but using the Visual Studio 2005 commandline compiler. The unmanged code is written in C++ and the managed code is Managed C++.
I have a project that creates a bunch of unmanaged DLLs and one managed DLL. The managed DLL is a wrapper to one unmanaged DLL which then has ref... | Hans made a good point. I have looked at the SetDLLDirectory (forgot to mention it) but I have never been able to get it to work. I always got the same results: execute program and nothing would happen.
However, I took his advice and reinvestigated the SetDLLDirectory function. I added:
#include "windows.h"
WINBASEAPI
... |
5,044,885 | 5,087,495 | What happened to the "add as link" option? | Why is the add an existing file as a link feature only available for managed projects? I can't use the same feature in a vcproj. Is it because managed projects are built for msbuild, and vcproj files are not?
| The Add As Link feature is not necessary for VC++ projects (whether managed or not) because VC++ projects do not require all source files to reside strictly within the folder that contains the project. C# projects, on the other hand, do have this requirement. So you could say that VC++ always adds files as links and ... |
5,044,990 | 5,045,004 | 2d STL vector typeid | I have various 2D vectors and I want to query their differing types at runtime.
It appears this is possible on an "empty" vector, e.g.:
vector<vector<float> > myVec;
cout << (typeid(myVec[0][0]).name() << endl;
The above returns "float" although I was expecting an exception as I've not pushed back any elements.
Is it... | Since float does not have any virtual methods, the compiler can evaluate typeid(some_float_object) statically without looking at the actual expression, just its static type. According to section 5.2.8 of the C++ standard (current C++0x draft), the compiler is not even allowed to evaluate the expression.
|
5,045,140 | 5,045,163 | Infinite loop with string iterator in C++ | While i'm willing to parse instructions contained in strings, I am basically trying to clean a string from it's spaces and tabs character, in order to seek instructions in it.
Unfortunately, my loop is going into an infinite loop, and I can't find why as i'm refreshing the iterator on each erasing of a char...
Any Hel... | The flow of your code:
it = line.begin();
while (it != line.end()) {
if (((*it) == ' ') || ((*it) == '\t'))
it = line.erase(it);
++it;
}
Correct code:
it = line.begin();
while (it != line.end()) {
if (((*it) == ' ') || ((*it) == '\t'))
it = line.erase(it);
else // <---- THIS IS IMPORT... |
5,045,405 | 5,045,482 | Confusing Function in C++ Dialogs | Hi could anyone explain to me what this function is doing, I am currently reading a programming book and am struggling to follow this function.
From what I can gather the function take in a handle to a window (in this case a dialog box), then information is passed in the second param and the third param being a pointer... | I used earlier something like this to add items to combo box, I might be of help.
SendDlgItemMessage(hwnd, IDC_COMBOSTATUS, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) "Available");
Where hwnd is handle to dialog, IDC_COMBOSTATUS is resource ID, and other is pretty much clear.
Try SendDlgItemMessage function rather SendMessa... |
5,045,430 | 5,045,596 | Read debugging information at runtime from an application | I have some questions regarding debugging symbols and what can be done with them, besides, well, debugging. I'm mostly interested in answers regarding GCC, but I'd also be happy to know how it looks like under other compilers, including MSVC.
First of all:
What are the common formats/types of debugging symbols?
How d... |
What are the common formats/types of debugging symbols?
DWARF and STABS (those are embedded inside executable, in special sections), Program Database (PDB; external file, used by MSVC).
How do they relate to compilers and platforms? Is it always the same format on GCC and MinGW among platforms?
GCC uses DWARF/STAB... |
5,045,692 | 5,045,716 | Making TCHAR* compatible with char* | So a quick question how do I make TCHAR* (or wchar_t as its a macro) work with char*?
I am using the unicode character set.
The code that is the problem is:
TCHAR* D3DDevTypeToString(D3DDEVTYPE devType) {
switch (devType) {
case D3DDEVTYPE_HAL:
return TEXT("D3DDEVTYPE_HAL");
case D3DDEVTYPE_SW... |
And yes I am using the unicode character set.
Then you cannot make TCHAR compatible with char. Because if you're using UCS, then TCHAR is wchar_t. The type char is not related in any way to wchar_t. You could do some work to convert the string (using e.g. WideCharToMultiByte), but then you'd lose Unicode support.
|
5,045,944 | 5,045,983 | Compile time warnings | Does any one know how to specify user defined warnings for #pragma warning directive in VS?
| #pragma message ("Message")
See How to use the #pragma message to generate user-defined warning messages in Visual C++.
#pragma warning is not used to specify user defined warnings but to modify the behavior of built-in compiler (warning) messages.
|
5,046,060 | 5,046,611 | Where to put compile-time-constant arrays? | Say I have an array storing the first 10 primes, like this:
const int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
This is all very fine and simple as long as I have 1 .cpp file. However, if I have multiple .cpp files I don't really know where to put this array.
An obvious solution would be this:
// primes.h:
exte... | I think this should work (now updated after Migi's testing revealed a flaw):
template <bool dummy>
struct primes_lut
{
static const int values[];
};
template<bool dummy>
const int primes_lut<dummy>::values[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
static auto& primes = primes_lut<true>::values;
(There is no pr... |
5,046,159 | 5,046,671 | Safer conditional compilation? | In an MSVC C++ program I have a part of code which I want to enable or disable depending on a preprocessor definition
// 1.h
#ifdef MYOPTION
//...
#endif
But I find that it is quite dangerous when it is used in a .h file included in more than one compilation unit, as I can easily get inconsistent headers (I don't want... | How about something like this: have 1.h define a dummy section in the obj with different options. This way, if MYOPTION is ever used inconsistently, the linker will issue a warning.
1.h:
#ifdef MYOPTION
#pragma section("MYOPTION_GUARD",write)
#else
#pragma section("MYOPTION_GUARD",read)
#endif
namespace { __declspec(a... |
5,046,226 | 5,046,778 | Problem linking my code with ARPACK on OSX (using MacPorts for ARPACK) | I am trying to compile a C++ program which invokes the ARPACK library.
My problem is that when everything is linked, some of the symbols in the ARPACK library do not get resolved. They are
__gfortran_transfer_integer
__gfortran_transfer_character
__gfortran_transfer_complex
__gfortran_compare_string
__gfortra... | add to linker -lgfortran .................
|
5,046,449 | 5,047,047 | fastest way to iterate matrix of known dimensions | I was wondering what the fastest way to iterate through a matrix is in c/c++.
The best method i've come up with so far is to map the matrix to a single dimension.
Then use pointer arithmetic, any other method that might be faster?
Dimensions are known at run time but not compile time, matrix is fully populated.
#includ... | In your example the bounds are even constants, so normal three dimensional arrays would work with this, be it C or C++.
Then, C and C++ are really different languages on what is concerned dynamically allocated arrays with variable bounds, don't mix them up. For C++ use vector classes and such things. They are made for... |
5,046,452 | 5,046,564 | Why can't I directly set an __int64 variable to -2500000000? | This program is written in VC++ 6.0 on a WindowsXP machine.
If I try to set an __int64 variable to -2500000000 directly, it is truncated to a 32bit value and the two's complement is taken.
__int64 testval;
testval = -2500000000;
At this point testval equals 1794967293 (110 1010 1111 1101 0000 0111 0000 0000 binary).... | Get a newer compiler. VC6 standard compliance is VERY poor.
In VC6, try a suffix of i64, as in
__int64 toobig = -2500000000i64;
Found the documentation!
|
5,046,669 | 5,046,718 | Main differences between objects and object pointers? | What's the difference between doing,
EventList temp;
EventList* temp = new EventList();
Where now temp you access it's vars by doing using .
and the other is ->
Besides that difference, what else? Pointer allocates on the heap while just EventList is on the stack. So is it primarily a scope thing?
| Eventlist temp is allocated and deallocated automatically within the scope in which it is called. That is, when you run the following code:
{
EventList temp;
}
The default constructor for EventList is called at the point of its declaration, and the destructor is called at the end of the block.
EventList *temp = n... |
5,046,691 | 5,046,739 | Question regarding structures in C++ | Can structs have the same name as a class?
Am I allowed to pass around structs into functions?
Structs are a light-weight class? Basically without the functions. It's a container that holds vars. I'm just wondering if I made a function, can I pass in a struct like normally passing in any other object?
| In C++, struct and class are effectively identical. The only difference is that members of a struct are public by default, and members of a class are private by default.
You can use them exactly the same way as you use classes. They do need unique names (within the same namespace), so you can't have the struct use th... |
5,046,758 | 5,046,875 | What is the shortest code to write text/image to a HWND | I don't need to have controls or anything, I just need to write something onto a HWND, either centred text or an image, that shows it has been rendered to. The actual use-case is I get passed a HWND at a point I'm not ready to deal with it, so I want to to display text on it like "this Window cannot be used", or a sad-... | HDC hdc = GetDC(hwnd);
RECT rect;
GetClientRect(hwnd, &rect);
char * text = "this Window cannot be used";
DrawTextA(hdc, text, strlen(text), &rect, DT_CENTER | DT_VCENTER);
ReleaseDC(hdc);
You might want to select a different font before you draw the text, but this will get you started.
|
5,047,003 | 5,047,044 | Unable to remove missing ; before variable name error | #ifndef PRODUCTS_H
#define PRODUCTS_H
#include "Products.h"
class Products
{
protected:
static int count;
string name_;
float cost_;
public:
Products() // default ctor
{
name_ = "";
cost_ = 0.0f;
count++;
}
Products(string name , float cost) //parametorized ctor
... | You should include the string header file in your first file. It looks like it's complaining that it doesn't know what a string is.
You need to add
#include <string>
and change the type of name_ to
std::string name_;
|
5,047,032 | 5,047,095 | How to integrate twitter with c++ application? | I have a C++ application that uses curl to go to log in to a website, get information, and then parse the information. Now I want to send myself an alert to my phone via sms or e-mail or I can I also send the alert to twitter and then get a notification that way.
My environment is windows vista and I use MSVS 8.
I jus... | Twitcurl provides a Twitter API on top of cURL.
|
5,047,054 | 5,047,243 | Why does Qt use reinterpret_cast rather than static_cast for void*? | You can cast to/from any pointer to T to/from void* with a static_cast, why does Qt use reinterpret_cast?
int SOME_OBJECT::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
... | Frankly, I've never been able to figure it out either. The void ** structure is created the same way, simply casts an int* to void* and then performs this weird cast on the other side. As far as I can tell, static_cast would not only be fine, it would be better.
You'll find that there's a lot of questionable code in ... |
5,047,080 | 5,047,979 | Finding smallest values of given vectors | How can I find the smallest value of each column in the given set of vectors efficiently ?
For example, consider the following program:
#include <iostream>
#include <vector>
#include <iterator>
#include <cstdlib>
using namespace std;
typedef vector<double> v_t;
int main(){
v_t v1,v2,v3;
for (int i = 1; i<10; i++){... | You can use std::transform for this. The loops are still there, they're just hidden inside the algorithm. Each additional vector to process is a call to std::transform.
This does your example problem in two linear passes.
typedef std::vector<double> v_t;
int main()
{
v_t v1,v2,v3,vfinal(9); // note: vfinal sized t... |
5,047,299 | 5,682,361 | Finding pattern in large binary file using C or C++? | I have a ~700 MB binary file (non-text data); what I would like to do is search for a specific pattern of bytes that occurs in random locations throughout the file. e.g. 0x? 0x? 0x55 0x? 0x? 0x55 0x? 0x? 0x55 0x? 0x? 0x55 and so on for 50 or so bytes in sequence. The pattern I'd be searching for would be a sequence t... | What ultimately worked for me was a hybrid between the Boyer-Moore-Horspool algorithm (suggested by Jerry Coffin) and my own algorithm based on the structure of the tables and the data being stored.
Basically, the BMH algorithm caught most of the things I was looking for. The obvious stuff.
But some tables did turn ou... |
5,047,464 | 5,047,538 | Launch external application from C++ program and attach it to visual 2008 debugger while debugging host in WinAPI | Basically I have Host and Child program. I do not have sources for Child so I can't change anything in it. I want to launch Host from debugger, which at some point should launch Child program. I want to attach Child automatically for debugging session as well (so any breakpoints set in DLL sources loaded under Child pr... | You can use the gflags.exe program. This will be accessable from a VS command prompt. You can specify a debugger to launch when the child program gets launched. By specifying vsjitdebugger.exe as the debugger in gflags.exe you can select the currently running VS instance to be the debugger.
Edit:
Sorry about the con... |
5,047,504 | 5,047,551 | Question about code re-use (Template or Inheritance) | I wrote a link list class and now besides the type of the cur object it can handle now.
I'm interested in reusing the code so it can handle another object.
I was thinking something maybe like this? Right now my current classes are truck and events and I have a linklist class. By using the linklist class it's right no... | A template is definitely the right choice. All of us who've been around since before templates were available can attest to their superiority over the alternatives.
Of course, unless you have some overwhelming reason to write your own, you're probably better off using std::list (or, perhaps, Boost slist).
|
5,047,732 | 5,047,775 | Error Compiling Code After trying to turn a class into a template | 1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall MyList<class Event>::~MyList<class Event>(void)" (??1?$MyList@VEvent@@@@QAE@XZ) referenced in function _main
Any idea what could be wrong? I had a working class before and then i tried to template it and i get this error above. Any idea ? I'm a... | Templates play oddly with C++'s compilation model because they aren't executable code - they're templates for executable code. Consequently, the standard model of partitioning a class into a .h/.cpp pair does not work correctly for templates.
The reason that you typically break apart a class into a .h file with the in... |
5,047,747 | 5,047,887 | I don't want JSON to escape apostrophes in C++. How to fix this? | I've encountered a bit of a problem with JSON (libjson 6). In a chat messenger I am making, there is a conflict between the server (which was made by other people) and the desktop client. My client's JSON strings always have apostrophes escaped, even though I always use quotes to delimit strings. The server, on the oth... | You can remove the escapes before the apostrophes.
If you never have escaped escapes before an apostrophe (e.g. \\' meaning "escaped-escape and unescaped apostrophe") or your library always escapes them, simply replace all \' with '. There are various string replace functions, but this is a simple case:
bool is_broken... |
5,047,783 | 5,047,790 | What can I do with an unsigned char* when I needed a string? | Suppose that I have a unsigned char*, let's call it: some_data
unsigned char* some_data;
And some_data has url-like data in it. for example:
"aasdASDASsdfasdfasdf&Foo=cow&asdfasasdfadsfdsafasd"
I have a function that can grab the value of 'foo' as follows:
// looks for the value of 'foo'
bool grabFooValue(const std... | You need to know the length of the data your unsigned char * points to, since it isn't 0-terminated.
Then, use e.g:
std::string s((char *) some_data, (char *) some_data + len);
|
5,047,798 | 5,047,814 | Which MinGW file to use as a C++ compiler | I have just installed MinGW and in the bin folder I can see 7 .exe files that compile my program:
c++.exe
g++.exe
mingw32-c++.exe
mingw32-g++.exe
gcc.exe
mingw32-gcc.exe
mingw32-gcc-4.4.1.exe
My small program (testprog.cpp) compiles correctly with each of them; the a.exe file is generated in the bin folder and it run... | It's quite possible that they are all the same; either exact copies or symbolic links to one another. Try using the --version flag on each to see what you've got. On my MingGW installation here, each of those binaries differs (checked with diff), but they all output the same version information (with the exception of... |
5,047,849 | 5,047,878 | Limiting Scope of #include Directives | Let's say I have a header file with a class that uses std::string.
#include <string>
class Foo
{
std::string Bar;
public:
// ...
}
The user of this header file might not want std::string to be included in his/her project. So, how do I limit the inclusion to just the header file?
| The user of your class must include <string>, otherwise their compiler will not know how big a Foo object is (and if Foo's constructors/destructors are defined inline, then the compiler also won't know what constructor/destructor to call for the string member).
This is indeed an irritating side-effect of the C++ compil... |
5,047,913 | 9,531,899 | OpenCV - getting the slider to update its position during video playback | I've picked up 'Learning OpenCV' and have been trying some of the code examples/exercises. In this code snippet, I want to get the slider to update its position with each video frame change, but for some reason it won't work (the picture freezes with the following code):
#include "cv.h"
#include "highgui.h"
int g_slid... | This is the actual working code
// PROGRAM TO ADD A UPDATING TRACKBAR TO A VIDEO
#include <cv.h>
#include <highgui.h>
int g_slider_position = 0;
CvCapture* video_capture = NULL;
void onTrackbarSlide(int current_frame)
{
current_frame = g_slider_position;
cvSetCaptureProperty(video_capture,CV_CAP_PROP_POS... |
5,047,938 | 5,047,955 | Forward declare a subclass that inherits from a class in different namespace | I don't understand why this fails to compile:
#include <SomeType.h> // has a namespace called SomeNamespace
class MyApplication;
int main(...)
{
...
MyApplication application;
...
}
class MyApplication : public SomeNamespace::SomeType {
...
};
As it stands I'm getting this error from g++ (Ubuntu 4.4.3-4ubuntu5) 4.4... | In main you're instantiating an object of type MyApplication, which is still an incomplete type; you can't do that, since the compiler doesn't know anything about it yet (it would need to know e.g. how big is it, if it has any constructor, ...).
To solve your problem, you have to define MyApplication before instantiati... |
5,047,971 | 65,659,337 | How do I check for C++11 support? | Is there a way to detect at compile-time if the compiler supports certain features of C++11? For example, something like this:
#ifndef VARIADIC_TEMPLATES_SUPPORTED
#error "Your compiler doesn't support variadic templates. :("
#else
template <typename... DatatypeList>
class Tuple
{
// ...
}
#endif
| Quick history
When this question was asked in February 2011, support for C++11 was inconsistent. Compilers needed time to catch up to the standard, so in the meantime, they released with partial support. For example, a compiler might have implemented variadic templates, but not auto.
If you had code that depended on a ... |
5,047,993 | 5,048,059 | How to get data from windows form | i wanted to get the value of a TextBox in a form and use it in main.cpp. How would i do this? Sorry if this is unclear i have never used forms. i am using windows 7, VC++ 2010.
| You send it a WM_GETTEXT message. If it's your form in your process then you will know the window handle. Otherwise you've got to get hold of it by some means.
|
5,048,034 | 5,048,049 | One Method to be seen throughout the entire Project | I have a question. I have a randomnumber function that I want to be available to all my classes.
In main,
I have the function
int RandomRange(int min, int max)
{
int newValue = (rand() % max) + min;
if ( newValue > max )
newValue = max;
if ( newValue < min )
newValue = min;
return new... | Create a header:
#ifndef RANDOM_RANGE_H_INLCUDED_
#define RANDOM_RANGE_H_INLCUDED_
int RandomRange(int, int);
#endif
Then include that header in any file that needs to use the function.
When you have time, you might want to write a better implementation of the function.
|
5,048,112 | 5,048,136 | Use GDB to debug a C++ program called from a shell script | I have a extremely complicated shell script, within which it calls a C++ program I want to debug via GDB. It is extremely hard to separate this c++ program from the shell since it has a lot of branches and a lot of environmental variables setting.
Is there a way to invoke GDB on this shell script? Looks like gdb requi... | There are two options that you can do:
Invoke GDB directly within the shell script. This would imply that you don't have standard in and standard out redirected.
Run the shell script and then attach the debugger to the already running C++ process like so: gdb progname 1234 where 1234 is the process ID of the runnin... |
5,048,131 | 5,253,874 | Cross Platform MIDI library supporting iOS CoreMIDI | I'm looking for a cross-platform C or C++ MIDI library. Just to send/receive MIDI note events, control codes and timing, not to generate sound.
The main target is iOS/iPad so it has to support CoreMIDI on iOS, which I know is fairly recent. I can use CoreMidi directly but if there's something lightweight out there it ... | You might want to take a look at RtMidi.
It provides a cross-platform API for realtime MIDI input/output, and makes use of the native API's for each platform (winmm, ALSA, CoreMidi).
I haven't used it with CoreAudio/CoreMidi, but it's worked flawlessly for me on Windows and Linux.
|
5,048,374 | 5,048,384 | String slicing in C++ | I am trying to slice the last four characters off a character array, and I tried the method that Python uses without success;
char *charone = (char*)("I need the last four")
char *chartwo = charone[-4:]
cout << chartwo << endl;
I would want this code to return:
four
But C/C++ doesn't seem to be that easy...
Where co... | Try:
int len = strlen(charone);
char *chartwo = charone + (len < 4 ? 0 : len - 4);
In C++, you can replace that with:
char* chartwo = charone + (std::max)(strlen(charone), 4) - 4;
The code uses a special property of C strings that only works for chopping off the beginning of a string.
|
5,048,381 | 5,048,564 | Using genetic algorithms for neural networks | Currently I am working on a project that would use genetic algorithms to optimize neural networks. I do realize this is probably not the best way to optimize them, but I'm new to both so I just wanted to try using them.
My plans are as follows (subject to change, a lot). My input neurons would be using a data set tha... | (Artificial) Neural Networks (ANNs) are notoriously difficult to optimize, and genetic algorithms (GAs) are a reasonably good approach to doing so (mainly because everything else tends to be very limited in how well it can work). Of course there are alternatives that work well too, but they are more complicated and sub... |
5,048,589 | 5,048,603 | Uncatchable Exceptions? | First, is there such a thing as an uncatchable exception in C++?
I've seen one 2005 microsoft kb article that discusses exceptions thrown in one DLL, that can't be caught in another DLL. It seems this was resolved with a hotfix, years ago, but I might be having that problem now - with Visual C++ 2008.
Specifically, ba... | A visual C++ catch block will only be capable of catching a C++ exception. kernel32!UnhandlesExceptionFilter is about the entire SEH exception range, which cover much much more than just C++ exceptions. For a brief introduction, this article is still fresh and accurate: A Crash Course on the Depths of Win32™ Structured... |
5,048,691 | 5,048,768 | Why throw a class over an enum? | Just wondering, why is it better to throw a class over an enum
Surely throwing classes is more overhead?
e.g.
enum MyException
{
except_a,
except_b,
except_c
}
void function f(){
throw except_a;
}
int main(int arc, char* argv[]){
try{
} catch (MyException e){
switch(e){
except_a: break;... | Given
enum MyException
{
except_a,
except_b,
except_c
}
write a catch clause that only catches except_c exceptions.
With
struct my_except {};
struct my_except_a : my_except {};
struct my_except_b : my_except {};
struct my_except_c : my_except {};
that's easy, since you can catch the base class or derived c... |
5,049,016 | 5,049,025 | Having a backend executable communicate with web app on PHP | Suppose my web app is written in PHP & Mysql on the standard LAMP stack etc...and I have some uber awesome and complex algorithm compiled as an executable in some other desktop programming language such as C++, Java, or C running in the backend....how would I go about passing data and information between the PHP script... | I have no idea what you are doing, but have you looked at exec() system() etc?
|
5,049,028 | 5,049,061 | GUI programming c++ or c# | I am taking software engineering classes at my university. I just took data structures and i am almost done taking design patterns. With the design patterns class the instructor let us choose what Language to use and what IDE to use on our labs. Since, i know C++ mostly i used that. Most of the class used c# and some u... | qt is not that difficult to work with. I have tried some gui tool kits for c++ and this is my experience in terms of c++
Qt
For c++ development and gui's i would overwhelmingly favour Qt instead of alternative libraries like win32 api, Microsoft foundation classes, etc.
Advantages
qt is cross platform and can be used ... |
5,049,084 | 5,049,130 | How good is NTP for distributed time synchronization? | How accurate is NTP for keeping a set of servers time synchronized?
I'm writing a service which requires a set of servers (some acting as clients, some as servers) synchronized to second level granularity. I'm wondering if NTP is the best thing to use, or if there's something better?
Should I run a ntp server on one of... | First off, you might have a look at the Wikipedia NTP page.
Basically, to start with (I preach this regularly) state what the service levels you want might be. Do you need accurate UTC? To what tolerance? That is, do you really need to know what time it is?
Or do you simply want precise synchronization among the syst... |
5,049,413 | 5,049,508 | In a multithreaded app, how would I use the atomic builtins to set/view a time_t value? | I have an app that is highly threaded.
The threads in this app read from a shared memory mapped file. You can assume they never write to it.
Now what I need to do is extend it so that when a reader has finished reading from the file, it will update a shared timestamp. i.e. time_t last_access_time = time(NULL);
That ha... | class SomeClass
{
public:
inline
SomeClass ()
: m_lastAccessTime (0)
{ ; }
inline void
UpdateLastAccessTime ()
{
time_t crtTime = time (NULL);
time_t lastTime = m_lastAccessTime;
while (crtTime > lastTime)
{
lastTime = __sync_val_compare_and_... |
5,049,578 | 5,049,866 | Stepping into Qt sources in Qt Creator (in Ubuntu Linux) | I'm using Qt Creator in Ubuntu. It's installed from the repositories but as it is now, there is no way to step into the Qt sources when debugging.
How can I enable that?
| Since Qt Creator uses gdb, you need to configure gdb. First thing to do is to install Qt debugging symbols:
apt-get install libqt4-dbg
Or, for Qt5:
apt-get install qtbase5-dbg # For the qtbase package
This will install the debugging symbols for Qt libraries. Older releases of Ubuntu had a silly bug that required addi... |
5,049,772 | 5,052,839 | How can I define the function body in a .h file? | Sometimes I define bodies of small global functions in .h files (static inline). It works.
Now I have larger global function. I need to to define it in .h file. I do not want it to be static inline. I tried the following trick with "dummy template":
template <typename Tunused> int myfunction(...) {
...
}
to achiev... | Honestly, I don't recommend putting large non-template function's definition
in .h file unless there is definite reason that you can't put the definition
in .cpp file.
If you have to put the definition in .h, the following code might help:
// .h
template< int Unused > int myfunction_() {
// definition
}
namespace { ... |
5,049,891 | 5,049,921 | Reference variable in class definition | I am learning C++, and I read that all references must be initialized upon declaration,
and there can be no "uninitialized references". But what if the reference variable is a class member?
class test
{
int &k;
};
int main()
{
test *abc = new test;
}
This program compiles and runs normally (in g++, no warning... | The program is ill-formed because it constructs a class that fails to initialize a non-static member entity of reference type.
I believe that gcc should fail to compiler this, but I only received the warning "non-static reference ‘int& test::k’ in class without a constructor".
test is a non-POD-struct type as it contai... |
5,049,908 | 5,050,027 | Animation from a C++ program | I have a C++ program in Linux which operates on and gives as the result the trajectories of some simple geometric objects in three or two dimensions. I need to visualize the movement of these simple entities and have a video file as an output. How do I do that, what libraries/software do I need for this?
| A simple library for 2D would be openFrameworks. It's fast to setup and use. To make your video, you could output the objects on the screen and capture the output with a program like Fraps.
As for 3D, there are is afaik no simple Frameworks that let you get started really fast. One possibility would be Ogre3D, which is... |
5,049,957 | 5,049,998 | Assertion failure: calling a list's node deconstructor | I am a computer science student with the task of creating a dynamic data structure, linked lists. I am currently working on a singly linked list and have successfully built the functionality to add, remove and dump all node data.
However, remembering that my 'advanced programming' lecturer stated that in order to avoid... | First of all, you should not call an objects destructor directly, unless you're writing an allocator and used placement new when creating it. Second, you should delete and not delete[] unless you also used new[]. And finally, delete this is a bad habit, but legal according to the standard. Why don't you just call delet... |
5,050,043 | 5,050,180 | What is your way of rendering terrains? | I wanna know how you render terrains in directx.
I have heard people saying that they are using RAW files and some said that they are using .x files. What is our way and why is it good?
| Many 3D engines use height maps to render terrain, due to their space efficiency (only one raster image is required).
|
5,050,239 | 5,050,246 | Where can I find C++/C code for tree isomorphism problem? | Where can I find code for tree isomorphism problem in O(N), where N is the number of nodes?
| Here is one such link: http://www.mareksacha.com/blog/tree-isomorphism-implementation
4th result on Google for "tree isomorphism c++"
|
5,050,261 | 5,050,305 | How to restrict a class/struct so that only certain predefined objects of it can exist? | Suppose your program needs to keep track of, say, months of the year. Each month has a name and a length in days. Obviously, this is information that you want to define at compile time, and you want to limit your program so that no other month information can be defined during runtime. And of course you want to conveni... | How about something like:
class Month
{
public:
static const Month JANUARY;
static const Month FEBRUARY;
...
private:
Month(const std::string &name, int days) : name(name), days(days) {}
const std::string name;
const int days;
};
const Month Month::JANUARY = Month("January", 31);
... |
5,050,283 | 5,050,376 | difference between hashing on x86 or x64 | I want to implement a hashmap into my code, so I decided to stick to murmurhash3
I currently only deliver my programs compiled for x86 and have tried to keep the code general so I've never had trouble running the programs on x64.
Now I've looked at the header files of murmurhash and the library offers following functio... | Edit: Changed everything after looking at the murmurhash3 documentation.
First, the _x86 variants are portable hash algorithms. The _32/_64/_128 indicates the width of the hash in bits. Generally _32 should be fine as long as your hash algorithm is smaller than 232 buckets.
The _x64 variants are an entirely different f... |
5,050,349 | 5,050,366 | Is there a way to compile C++ to C Code? | I have a program which is configured by the user by using C++ classes and
the same class should be used to configure a program which
can only use a subset of C99 (Open CL Language).
So my question is:
Is there a way to compile C++ to C-Code?
Open Source would be great!
| The C++ FAQ has a list of possibilities: Is it possible to convert C++ to C?.
In short, it says that you can't expect this to give you particularly readable code. Think of the complexities involved; multiple inheritance, virtual-function resolution, templates, operator overloading, etc., etc. There's no clean succinc... |
5,050,372 | 5,055,236 | Script system in application | I'm developing a game and now I want to make script system for it.
Now I have abstract class Object which is inherited by all game objects. I have to write a lot of technical code, add new object type into enum, register parser function for each object (that function parses object's params from file).
I don't want to m... | Can you give us a rough idea of how large the game is going to be?
If you're not careful, you could give yourself a lot of extra work without much benefit, but with some planning it sounds like it might help. The important questions are "What parts of the program do I want to simplify?", "Do I need a scripting language... |
5,050,494 | 5,050,568 | Member function pointer in C++ for_each | I'm developing a small Virtual Machine in C++ for a school project, which should work like dc command, and is composed of a Input Output element, a Chipset, a Cpu and Ram. I'm currently working on the chipset, in which I've implemented a little parsing class in order to be able to get some Asm instructions from standar... | std::for_each(
_instructList.begin(),
_instructList.end(),
std::bind1st(std::mem_fun(&Chipset::pushInstruction), this));
|
5,050,588 | 5,106,187 | how in BOOST send a signal in a thread and have the corresponding slot executed in another thread? | In Qt for instance if you emit a signal in a thread other that the GUI thread, the signal is enqueued and executed later in the GUI thread, is there a way to do that with boost?
thanks
| For an event loop use boost::asio::io_service. You can post tasks inside this object and have another thread execute them, in a thread safe way:
struct MyClass
{
boost::io_service service;
void doSomethingOp() const { ... }
void doSomething()
{
service.post(boost::bind(&MyClass::doSomethingOp, ... |
5,050,648 | 5,050,677 | DrawText only displays the first call | I'm using the DrawText function in a Win32 program to display "Local" at the top center of the screen and "Server" in the center. When I run the program it displays "Local" but not "Server". Here is the code in my message loop:
case WM_PAINT:
{
RECT localLabel;
localLabel.left = 0;
... | Your second rectangle is not valid (bottom should be 120 instead of 20 because it's the actual bottom coordinate, not the height). Also, you have to render both strings before calling EndPaint():
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT localLabel;
localLabel.left = 0;
localLabel.top = 0;
localLabel.right... |
5,050,763 | 25,376,425 | double checked locking pattern | In C++ and the Perils of Double-Checked Locking, there's persudo code to implement the pattern correctly which is suggested by the authors. See below,
Singleton* Singleton::instance () {
Singleton* tmp = pInstance;
... // insert memory barrier (1)
if (tmp == 0) {
Lock lock;
tmp = pInstance;
... | I didn't see any correct answer here related to your question so I decide to post one even after more than three years;)
I just wonder that whether the first memory barrier can be moved right
above the return statement?
Yes, it can.
It's for threads that won't enter the if statement, i.e., pInstance has already bee... |
5,050,869 | 5,051,100 | Extend Qt standard icons | How would one extend the standard icons provided by the QStyle class with support for Windows and Linux in mind?
namespace Ui {
class TVLoader;
}
class TVLoader : public QMainWindow
{
Q_OBJECT
public:
explicit TVLoader(QWidget *parent = 0) :
QMainWindow(parent),
ui(new Ui::TVLoader)
{
ui->setupUi(this);
... | You man want to subclass QStyle if you want to provide your own icons, reimplement the standardIconImplementation() slot in your subclass and return a new icon from there. Below is an example:
class MyProxyStyle : public QProxyStyle
{
Q_OBJECT
public:
MyProxyStyle(QStyle *style = 0) : QProxyStyle(style) { }
p... |
5,050,870 | 5,050,940 | Ugly compiler errors with template | template<typename T>
struct function
{
typedef T type;
template<typename U>
static void f() {}
};
template<typename T>
struct caller
{
int count;
caller(): count() {}
void operator()()
{
count++;
T::f<typename T::type>();
}
};
int main()... | T::template f<typename T::type>();
Without this "template", the code is parsed as:
T::f [less-than operator] typename T::type [greater-than operator]...
Which is an error.
|
5,050,959 | 5,051,856 | WH_KEYBOARD_LL hook not called | I'm having some problems with a WH_KEYBOARD_LL hook :
The reason why I'm using a global LL hook is not important I just need it for my app (I tried other types of hooks but they didn't work for me).
The hook function is in a dll, the dll is loaded on the application start-up and the hook is set also on start-up from th... | The hook callback is made on the same thread that called SetWindowsHookEx(). That bit of magic requires that thread to pump a message loop. Which is the rub, your timer callback method is called from a threadpool thread. It doesn't pump, it's not even around long enough to ever be able to get the hook callback.
Invo... |
5,051,264 | 5,051,317 | Dynamic cast, list of objects conversion, templates | There are 2 classes:
class A
{
private:
double a1, a2;
...
};
class B : public A
{
private:
double b1, b2;
};
and a generic container
template <typename Item>
struct TList
{
typedef std::vector <Item> Type;
};
template <typename Item>
class GList
{
private:
typename TList <... | GList <B> B3 = dynamic_cast <GList <B> &> (A1);
dynamic_cast works with only polymorphic type. Here GList is not polymorphic. Hence it would not even compile!
If you make this polymorphic, even then this cast wouldn't work, since there is no relationship between GList<B> and <GList<A>. They're like two different unrel... |
5,051,340 | 5,051,427 | C++ List destructor called after every use of List's method | This is a follow up to a question I asked earlier today regarding the appropriation of directly calling a class' destructor.
I'm creating my own List for an assignment. I have overloaded the assignment, square brackets, in and out stream operators and have the basic adding, removing and printing to screen functionality... | It's because you took your List by value- that is, you copied it. You need to take it by const reference- that is,
ostream &operator<<(ostream &stream, const List& theList)
Furthermore, your assignment operator should take a const reference, not a non-const ref.
I also don't think that this
delete _head, _tail, _curren... |
5,051,500 | 5,052,087 | Optimal data structure for time and source dependent log data for fast browsing? | I've got field bus data that gets sent in packets and contains a datum (e.g. a float) from a source.
=> I get timestamps with a source ID and a value.
Now I want to create a little program (actually a logging deamon in C++ that offers a query interface over HTTP for displaying the data in a plot diagram) where the user... | It really depends on the specific case but I can think that a possible solution would be to store events in pages and keep in memory just the page directory:
struct Page
{
int id;
int timestamp0, timestamp1;
int bytes_used;
};
Every page only has events for a specific ID and all pages are of the same size ... |
5,051,545 | 5,051,857 | Matrix multiplication running times Python < C++ < Matlab - Explain | I have a matrix M thats's 16384 x 81. I want to compute M * M.t (the result will be 16384x16384).
My question is: could somebody please explain the running time differences?
Using OpenCV in C++ the following code takes 18 seconds
#include <cv.h>
#include <cstdio>
using namespace cv;
int main(void) {
Mat m(16384, 81, ... | What CPU are you running on? For modern x86 and x64 chips with dynamic clocking, getTickCount and getTickFrequency cannot be trusted.
18 seconds is long enough to get acceptable precision from the standard OS functions based on the timer interrupt.
And what BLAS are you using with OpenCV? MatLab installs some highly ... |
5,051,601 | 5,051,845 | is there a cross-platform unicode string class that I can use both on Win32 and MacOSX systems? | Also I need locale aware case conversion. .NET do this very well. Do us C++ programmers have to wait 100 years for such thing ? I am aware of the ICU library but it's 20MB and I can't even get to link my code with it... All in all I want to end this nightmare..
| You might want to use the API provided by the operating system. Windows has NLS API that deals with locale specific string comparison and case conversion.
Standalone Unicode Libraries are ICU and IConv. Both require some time to learn. The data file is also quite large - expect to carry > 10M data files to support most... |
5,051,634 | 5,051,703 | The Best way of storing/retrieving config data in Modern Windows | I've not done much coding for Windows lately, and I find myself sitting at Visual Studio right now, making a small program for Windows 7 in C++. I need some configuration data to be read/written.
In the old days, (being a Borland kind of guy) I'd just use a TIniFile and keep the .ini beside my exe Obviously this is j... | Often people use XML files for storing preferences, but they are often overkill (and they aren't actually all that readable for humans).
If your needs would be easily satisfied with an INI file, you may want to use Boost.Program_options using the configuration file parser backend, which actually writes INI-like files w... |
5,051,749 | 5,052,755 | Use methods of DLLs into other ones | I have 3 DLLS and one win32 project in the same solution. The win32 project should use methods and classes of the DLLs and the DLLs should use methods of the other ones.
How can I do this? Should I include the .h files of every DLLs in the other ones?
Also, I have a function in one DLL that initialize a class defined i... | I don't quite understand what your problem is. You link to DLLs using header and lib files. I think you already know this.
If you want to share an instance between code in different DLLs you need to export that instance just like you export the classes and functions. You can export the symbol directly, or provide a fun... |
5,051,859 | 5,051,946 | C++ Get Application Directory *NIX | How can I get the application directory in C++ on Linux/Unix. getcwd() returns the directory from which the application was run, but I want the actual directory which the build is sitting in.
I know you can get this from the main() but I dont really have access to it, and I've been told you cant rely on it (Is that tru... | You can see this answer:
c++ - Finding current executable's path without /proc/self/exe - Stack Overflow
|
5,051,894 | 5,051,937 | C++ address operator uses? |
Possible Duplicate:
Why use pointers?
I know what the C++ & does. but what can it be used for?
|
& is used to pass address of arguments (pointer) to function, when it's used at calling site.
& is used to pass arguments by reference to function, when it's used in function parameter list.
& is bitwise AND. e.g. (a & b)
& is used in logical AND. In this case, two & make logical AND. e.g (a && b).
|
5,051,935 | 5,053,867 | Check for Identical Birthdays in a Specific group size in C++ | I am brand new to this site. A friend told me about it and how much it has helped him, so here goes!
I am trying to create a program that will read in a certain size of a group. At this point it will then create random birthdays for each 'member' of the group (a day 1-365) and then compare to see if there were any iden... | There are various errors with this code.
As Gabe mentioned it, the int identicalBday = 0 is local and doesn't reset the global one, which explain your 100% increase between runs. I think this error could be avoided by using a simple coding style rule: declare the variable where/when they are needed, that is the most l... |
5,051,983 | 5,051,996 | Calling methods of class derived from an abstract class [C++] | You'll have to forgive me if this is a really basic question; I haven't used C++ this much in a long time so I've forgotten how a lot of it works.
Anyway, I have a base class and a couple derived classes like this (super oversimplified, but the gist is the same):
class Base
{
public:
Base () { }
int SomeFunction ... | Your method should be declared virtual. And in your case, probably pure virtual.
class Base
{
public:
Base () { }
virtual int SomeFunction (int x, int y) = 0; // abstract definition
};
Note that, while this is not absolutely required, you might as well declare a virtual destructor. Do it if you ever delete a der... |
5,052,126 | 5,052,305 | Rails - How to create a desktop application? | Is it possible to transform a rails application to a desktop application? And if yes what is the best way of doing it.
And where should I start if I just want to create an simple windows desktop application that shows a few columns from a Mysql Database and check if they have changed.
| Transform in the literal sense, no, no such tech exists. However, you can make a rails app that's live on the web, or any other web application appear somewhat like a desktop application (with its own icon, and even some OS integration) by using a "Site Specific Browser"
OSX: http://fluidapp.com/
Windows (and OSX): htt... |
5,052,211 | 5,052,853 | Changing value_type of a given STL container | Suppose, I've a STL container type (not object), say vector<A>. Now it's value_type is A, so I want to change it to B.
Basically, I want a class template of this form, or a variant of it:
template<typename container, typename new_value_type>
struct change_value_type
{
typedef /*....*/ new_container;
};
So that I... | You might try specializing with template template parameters.
#include <vector>
#include <list>
#include <deque>
#include <string>
template <class T, class NewType>
struct rebind_sequence_container;
template <class ValueT, class Alloc, template <class, class> class Container, class NewType>
struct rebind_sequence_co... |
5,052,347 | 5,053,260 | Eclipse-cdt to index my C++ code only | Is it possible to have eclipse index my C++ code (built using cmake)?
I prefer to compile/run the actual code using a bash prompt, but I would like to write code in an editor like eclipse so I can easily follow definitions and have auto-completion.
I'm worried the C++ indexing in eclipse will become out of sync at so... | Yes, I currently use Eclipse as an editor with its index on a project that is built outside of eclipse. Just turn off all the automatic build options in the project, and it will still index the code for you whenever a file changes. My project uses a bunch of special scripts to perform the build, so I just left it as a ... |
5,052,442 | 5,052,484 | Access violation reading from array of derived classes | (Relevant to this question.)
I have a base class Base and two derived classes, Der1 and Der2. (See linked question for basic implementation. Each has a number of public properties as well.) In my program I create an array of Base like this:
Base *array[10];
int count = 0; // program-wide count of how many objects are i... | Der1 d = Der1();
constructs a instance of Der1 on the stack. If d goes out of scope before you call SomeFunction you get a access violation. You need to construct Der1 on the heap by using new.
Der1* d = new Der1();
You need to delete the d instance if you don't need it anymore or at the end of the program:
delete d;... |
5,052,521 | 5,053,017 | compile error when making functor a class member function | I have a functor which i want to use with sort() the container in question has the type
std::list<std::pair<unsigned, unsigned>>
This container is a temporary initialized in one of class GameBoard's functions.
the functor has the declaration
bool GameBoard::SortMoveList(std::pair<unsigned, unsigned> left,
... | A functor is a an object that behaves like a function.
This means you need to define a class that defines the operator()
Example:
class GameBoardMoveListSorter
{
bool operator()(std::pair<unsigned, unsigned> const& left,
std::pair<unsigned, unsigned> const& right) const
{
return lef... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.