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,785,108
5,785,141
Weird XOR swap behavior while zeroing out data
Thanks Doug. Here's the fix: void swap(int& a, int& b) { if (&a == &b) // added this check to ensure the same address is not passed in return; a ^= b; b ^= a; a ^= b; } I am implementing quicksort for fun in C++, and I am using integers for dummy data. I had been using the XOR swapping algori...
Your swap a and b are the same location. The XOR hack only works when they are different locations. I think in C; here's a table: &a != &b &a == &b *a *b *a *b -5 -5 -5 -5 *a ^= *b; 0 -5 0 0 *b ^= *a; 0 -5 0 0 *a ^= *b; -5 -5 0 0
5,785,341
6,684,762
basic OSC tutorial in C++? what library to use?
I would like to learn how to write the simplest server/client C++ command line application for sending a few lines of data from one application to the other in real-time, using OSC (Open Sound Control). I would like to make it work in localhost mode or over the network, but I think in OSC its just the question of the I...
We are using oscpack as a cross plattform osc library. https://code.google.com/archive/p/oscpack/downloads we are using it with Linux, Windows and MacOSX and are quite happy. It's simple to use and works well.
5,785,586
5,785,854
Storing vector of std::shared_ptr<Foo> where Foo is a templated class
I have a base class that I made a template because I want to vary the type it takes for several functions, but I want to derive from these templated base classes. I want to store a vector of these classes. My idea was to create a non-templated base class above everything in the hierarchy, and use double dispatching t...
I think you've almost got it. I would write the visitor class like: class Visitor { public: virtual void HandleFoo( Foo<Bar> &f ) = 0; virtual void HandleFoo( Foo<Baz> &f ) = 0; //default implementation for unknown Foo types: virtual void HandleFoo( FooBase &f ) = 0; }; Now you don't need to speciali...
5,785,631
5,785,721
C++ Function Template, Int Parameter Question
I was curious why this doesn't work: const int ASSIGN_LEFT = 1; const int ASSIGN_RIGHT = 2; template <int AssignDirection> void map( int& value1, int& value2 ); template<> void map<ASSIGN_LEFT>( int& value1, int& value2 ) { value1 = value2; } template<> void map<ASSIGN_RIGHT>( int& value1, int& value2 ) { value2 =...
The following definitely works. It also works around the fact that you can't partially specialize a function template by having the function template delegate to a specialized class template: enum AssignDirection { AssignLeft, AssignRight }; template <typename T, AssignDirection D> struct map_impl; template <typena...
5,785,697
7,375,337
Using log4cxx as input counter
I want to add a counter that record how many data input per hour or per day. Since there is no timer in my code, I hope that log4cxx, which can handle daily log rotation, could help me. Like, every midnight, print a log showing how many data got in yesterday. Do anyone know the trick or any reference? THX.
This is a late answer, but maybe it's going to be useful to other people. Nope, log4cxx cannot do it — print a log at a given time, out of itself. Log4cxx is not about timers, roll-over detection routine is checked with every log statement processed by the library, more specific, by the appender. There are no watchdog ...
5,785,976
5,786,043
C++ Virtual Destructors
If I have a base class and a derived class, and I delcare the destructor in the parent virtual, but instantiate an object of type subclass, when destroyed it will invoke the parent destructor right(since virtual)? If I also declare a destructor in the derived class, will it call both destructors (base and derived). Th...
Yes, parent destructors will be called automatically. The destructor should be virtualised so a derived instance can be destroyed properly by code that thinks it has a reference to a base class instance. In very limited circumstances, it is OK not to virtualise, if you really need to save a few cycles on the vtable loo...
5,786,013
5,786,033
Simple compiler question
I'm having a problem compiling a multiple-part project. I thought I had included the correct #ifndef/#define statements and included header files correctly, but apparently not. When attempting to compile this error came up: [23:18]andrew final_project$:g++ driver2.cpp fish.cpp bay.cpp ld: duplicate symbol Fish::Fish() ...
Don't include the .cpp files in driver2.cpp. Include fish.h and bay.h instead.
5,786,015
5,786,086
how to exit after no input in a c++ program+
Hi guys i am new to c++, I just wrote this code to find min/max of a array of numbers. I just want to know how can I make the no. of entries flexible(I mean the user should be able to enter as many entries as possible without specifying how many in the starting) Here's the code, but its not working, can someone please...
You will have to use some sort of variable length datastructure and Vector is the best choice for this since you are working in C++. Therefore, instead of your fixed length array: int *A; A=new int[5]; use a vector like this: std::vector<int> input; And then to add values to this, use the following: input.push_back(1...
5,786,044
5,786,105
Memory use in SQL Server and C/C++
Is there a way to avoid writing to file, and keep a table in main memory?, using C/C++ and SQL Server 2008?
If you mean whether there is an in-memory version of the SQL Server, like TimesTen for Oracle the answer is no. If you mean a 'little' database that you can add to your App see MS SQL Compact Server. If you mean using memory mapped files instead of a database, see here: http://msdn.microsoft.com/en-us/library/system.io...
5,786,179
5,786,272
Need to make an array of already created objects
I am making several items, and need to set them as being interactable with each other. Item i1 = Item("Item 1"); Item i2 = Item("Item 2"); Item i3 = Item("Item 3"); Item i4 = Item("Item 4"); i1.setInteractable({i2,i3}); i2.setInteractable({i1,i4}); i3.setInteractable({i1}); This is the method header for the setIntera...
It's a wrong C++ syntax to pass an array initialization like that: i1.setInteractable({i2,i3}); // error: invalid In various way you can achieve this. The most straight forward way is to use std::vector. First declare interactableItems as, static vector<Item> interactableItems; Now you don't need setInteractable(), i...
5,786,230
5,786,524
Copying numbered lists from a RichEdit?
When you send a WM_COPY message to a RichEdit control having a numbered list selected, and then paste the text into Notepad, the numbers are not included. Is there any way to get them? Thanks!
You don't get the numbered list because Notepad does not support text formatting such as bullets, bold, numbering etc. The target application must support rich text. Copying from RichEdit and pasting in Wordpad, MS Word, Html Editor works well. Thanks.
5,786,244
5,786,270
how to enable c++ support in visual studio 2010?
I want to create a C++ project in Visual studio 2010 but I don't see any template for a C++ project. All I see is visual c# templates. Please let me know how to enable c++ support in visual studio 2010.
You likely have Visual Studio installed without the C++ compiler. You have to start the installer and alter the installation so that C++ compiler is installed.
5,786,296
5,787,087
Overloading comparision operator in C++ results in "invalid operator<"
Currently attempting to sort a vector of object, with each object containing a string, in C++ The strings can contain letters or numbers (due to a design constraint, this is necessary, as the comparator can be changed). At the moment, the class of the object is overloaded, so that when two objects are compared, the str...
You operator is effectively invalid. The operator < must have a number of mathematical properties if you want it to be usable for sorting. One is the AntiSymmetry property: x < y => !(y < x) Let's define x = "b" and y = "aa". x < y because the length of "b" is inferior to the length of "aa" y < x because "aa" is inf...
5,786,400
5,786,513
Effective testing of multiple students programming solutions
As part of my lecture in C++ the students will have to solve assignments. Each solution shall implement the same functions with the same functionality and the same parameters (function name, return value, passing parameters). Only the code inside is different. So i'm thinking about a way to test all solutions (around 3...
The reason why unit tests are one of the most efficient types of automated testing is because the return of investment is relatively small (compared to other types of testing), so it makes perfect sense to me to write a verification suite of tests. You might even go so far as to give the students the test suite instead...
5,786,514
5,786,577
C++ assignment operators question about inheritance
I have two classes - base class A and derived class B - and I write this A obj; B obj2; obj = obj2; What would actually happen if I have yet to overide any assigment operators? Would this just copy the A part of obj2 into obj? Is this even proper, or a error that the compiler just excuses? Does a IS_A relations...
class Base { //Members }; class Derived1:public Base { //Members }; class Derived2:private Base { //Members }; int main() { Base obj1; Derived1 obj2; Derived2 obj3; obj1 = obj2; //Allowed Since Public Inheritance obj1 = obj3; //Not Allowed, Compiler generates error } W...
5,786,583
5,786,821
Self Modifying Code [C++]
I was reading a codebreakers journal article on self-modifying code and there was this code snippet: void Demo(int (*_printf) (const char *,...)) { _printf("Hello, OSIX!n"); return; } int main(int argc, char* argv[]) { char buff[1000]; int (*_printf) (const char *,...); int (*_main) (int, char...
The code is relying on knowledge of the layout of functions from the compiler - which may not be reliable with other compilers. The func_len line, once corrected to include the - that was originally missing, determines the length of the function Demo by subtracting the address in _Demo (which is is supposed to contain ...
5,786,814
5,787,188
visual studio Find Replace
I have lots of source code files. I have lots of hard coded string. I want find/replace some words from C/C++ strings only. for example. I have source code like log_msg_w(LOG_ERR, "string1"); log_msg_w(LOG_ERR, "string"); i want to find/replace and make the code like this log_msg_w(LOG_ERR, _T("string1") ); log_ms...
Open the file where the replacement should be done. Press Ctrl+H to open the "Find and Replace" dialog. In "Find what:" text box type {\"[^\"]*\"}, it searches all the strings in double quotation marks. In "Replace With:" text box type _T(\1). \1 means to use the matched pattern enclosed in curly braces. Check "Use:" c...
5,786,882
5,786,901
Store C++ maps by value
Is it possible to store pairs such as ordered by value in a map. Therefore finding the min and max element would be very cheap for me. I know in gnu libstdc++, map is implemented by using a RB-tree, but couldn't figure out how to store elements by ordered by value. I don't want to exchange keys with values, because my...
You could use a std::multiset, if you only need your values. Example: #include <set> #include <map> int main(){ typedef std::map<int,double> your_map_type; your_map_type your_map; // populate your_map std::multiset<double> your_values; for(your_map_type::const_iterator it = your_map.begin(); it != your_map.e...
5,786,889
5,786,974
Explain the following C++ Code snippet
I am new to C++ and have programming knowledge only in Java. Can anyone please explain the meaning of the code below: #define DEF 134 ; int k; char msk; PMSK *pm; //At the begining of class some declaration // i is some counter(int) if ( (nVersion >= 2004) && (nVersion < 2008)) { k = to_bits(DEF, ...
What is pm->orbits[k]? can we replace it in java like pm.orbits[k]? Basically, yes. The -> operator de-references and then access a field (also known as access the field/function of the object pointed to by the pointer). However, if you had a reference type to begin with, you get the de-referencing "for free". PMSK *pm...
5,786,929
5,787,186
How to prevent implementing a method that is intended to be non-implemented in C++?
Possible Duplicate: What's the most reliable way to prohibit a copy constructor in C++? Suppose I want to make a class non-copyable and want to prohibit copy constructor and assignment operator. I make them private and leave unimplemented: class Class { //useful stuff, then private: Class( const Class& ); //not ...
In C++0x there is the new delete keyword, that does just this What's the most reliable way to prohibit a copy constructor in C++?
5,786,954
5,786,985
C++ Destruct Function Error!
I wrote a program that cannot work properly.The problem is that when I destruct the pointer it goes all wrong. the code is as follows: if(pImage) delete pImage; but if i use this code, it can work all right. if(!pImage) delete pImage; can you explain the reasons ? thank you !
The second example will for sure not work correct - at least not the form of correct you want it to be. If pImage is any non-zero value, the delete statement won't be executed. It may compile and work fine, but you're leaking memory (and possibly other resources). Your problem is most likely double-deletion, aka deleti...
5,787,006
5,787,500
Passing partially specialized template as a template parameter
I have a class template, expecting some other template as a parameter: template< class Key, template <typename K,template <typename T> class Allocator> class Policy > class container { Policy<Key,Allocator>* _policy; //some code here }; and usually i use it with the policy class like this: template ...
You have two options: binding, and rebinding. In binding, you adapt the ternary policy into a binary one, as expected by the template-template parameter Policy: template <typename Key, template <typename T> class Allocator> struct policy_3_100500 : ternary_policy<100500,Key,Allocator> {}; and use policy_3_100500 inste...
5,787,033
5,787,480
Smart Pointers In C++
Say we have a base class and a derived. So: class base { protected: ~base(){ //... } // ... }; class derived : public base { // ... }; And now say that we have this code using the above classes with a smart pointer class: SmartPointer<base> bptr(new derived()); delet...
First thing is that as it stands the code will not work. The destructor of base must be at the very least protected (or derived classes be friends of the base). A private destructor means that the compiler will not allow you to write the destructor for the derived classes. Now, assuming that you have a protected destru...
5,787,456
5,787,484
How to develop an API for an c++ project
I have developed an crawler in c++ with curl library and as it is developed in c++ it does not has an GUI and i am planning to implement the GUI using java .I have a question how to develop an API to access it in java... for example Mongo db is written in c++ and it has API for all languages..how it access the c++ do ...
You will need to write/wrap the crawler as a service and host it on a server that is listening on a port. You might want to create a text or binary protocol whereby the clients can then talk to this service. Once thats established, you can write the clients in any language including Java.
5,787,466
5,787,490
Should I be using static in this case
I have a global unique value, which I wish to use it across within a exe and different DLLs. For any project which wish to use it, they may just include defs.h I was wondering, should I declare it as // defs.h const UINT UNIQUE_MESSAGE = RegisterWindowMessage(_T("UNIQUE_MESSAGE-{E5476FDB-3E7E-4113-8132-1D87709BC46...
In C++, namespace level const are implicitly static (i.e it has internal linkage), unless you write extern const. So both of your syntax is basically same. §7.1.1/6 says, Objects declared const and not explicitly declared extern have internal linkage. So I would suggest this: (with minimal consideration, like excludi...
5,787,495
5,787,637
How does the copy-and-swap idiom work during self-assignment?
I am reading the excellent copy-and-swap idiom question and answers. But one thing I am not getting: How does it work in case of self-assignment? Wouldn't the object other mentioned in the example release the memory allocated to mArray? So wouldn't the object which is being self-assigned end up in having an invalid poi...
But one thing I am not getting how does it work in case of self assignment? Lets look at the simple case: class Container { int* mArray; }; // Copy and swap Container& operator=(Container const& rhs) { Container other(rhs); // You make a copy of the rhs. // This means you h...
5,787,963
5,787,980
Are these codes different?
I find when I research programming every book has a different way of doing the basics. So I was wondering if these two codes are different or if they compile down to the same thing and what would be the benefit of one over the other. if(a > b && b >c) {} if(a > b) { if(b > c) {} }
They have the same effect (the program will do exactly the same) and they'll likely cause the same machine code to be emitted. The first one is shorter, the second one might be more convenient to step over in the debugger (debuggers step over code line by line).
5,787,964
5,788,251
C++ quick sort algorithm
I'm not looking to copy a qsort algorithm. I'm practicing writing qsort and this is what I've come up with and I'm interested in what part of my code is wrong. Please don't tell me that this is homework cause I could just use the code in the link below. Reference: http://xoax.net/comp/sci/algorithms/Lesson4.php When t...
// sort interval [begin, end) void myQSort(int* begin, int* end) { if(end - begin < 2) return; int* l = begin; int* r = end - 1; // Initially find a random pivot int* pivot = l + rand() % (r - l + 1); while(l != r) { // Find the lowest bound number to swap while(*l <...
5,788,043
5,788,095
How to create a macro that throws on verifying HR and also logs?
I have a scenario in the code where the following pattern exist - if (!function(A)) { log("this is the %d error in this file called %s", num, fileName); throw AppException(FUNCTION_ERROR); } the issue with this is you need to do this all the time and the code looks really dirty. so I want to define a macro like...
Use __VA_ARGS__ as: #define VerifyOrThrow(b, retcode, ...) if (b == 0) \ { \ log(__VA_ARGS__); \ throw(AppException(retcode)); \ }
5,788,115
5,795,633
Hide border of window, if i know a handle of this window
I have already OLE Embedded object Excel Chart. And, when I create this object, i have some problem in project, when I'm resizing window. Using Spy++ I see two process: Excel 7 and Excel 9. Excel 9 contain "trash" in right part, and when I resizing window I can see undefined behaviour. On the following picture you can ...
You might try using SetWindowLong(), but I don't know if the effect is going to be what you are looking for. SetWindowLong(win_handle, GWL_STYLE, GetWindowLong(win_handle, GWL_EXSTYLE) | WS_EX_TOPMOST); ShowWindow(win_handle, SW_SHOW);
5,788,217
5,788,260
C++ getters and setters best style
in Java code convention is simple and obvious, in this style: public: int GetMyAge(){ return myAge; } void SetMyAge(int myAge){ this->myAge = myAge; } private: int myAge; (I know it's "again the same thing", but) I have read most of related questions on SO and I still don't know "th...
The best style is the one that allows you and your team to make quality software that your clients continue to pay you for. How does this style work for you and your team? Do you find it causes (or prevents) bugs? Do you find it easy to maintain the code? Do you bicker about the formatting? Answer those questions and t...
5,788,330
5,788,344
Do you see any problem with this C++ code?
#include<iostream> #include<conio.h> using namespace std; class A { public: int *p; A() { p =new int; } ~A() { delete p; //Is this what i am doing is correct? cout << "in A's destructor"<<endl; } }; int main() { A *obj=new A; delete obj; getch(); } This programs,i have executed in Dev c++ and ...
That code is logically fine (the part with new/delete you're asking about), but designed badly in other aspects. First, if class A owns that heap-allocated int (int lives for as long as class A object lives) there's no point in creating it with new, it'd be much more efficient to make it a member variable of class A. S...
5,788,443
5,788,487
internal working of the recv socket api
I am working on TCP client server application using c++.third party lib are now allowed in this project. Here exchange between client server takes using well define protocol format.once the client receives the packet it will send it for parsing.I have protocol manager which will take care of the parsing activity. I hav...
TCP emulates a stream, so in TCP there is no notion of messages. If you want messages, your application has to have some protocol to seperate them. UDP does have a messages, so there it is possible to retrieve separate messages.
5,788,540
5,788,706
AnyCPU C# DLL in 64bit process loads 32bit DLL
I have a 64bit C++ process that loads an AnyCPU C# DLL. Can this AnyCPU C# DLL can load 32bit C++ DLLs, or can it load only 64bit DLLs? Thanks! :-)
An AnyCPU DLL runs in the context of the calling process, which is x64 according to your question. If this AnyCPU DLL loads another DLL, this also runs in the context of the x64 calling process that loaded the AnyCPU DLL. This is the problem with running code across different platforms. If you want to run a 32 bit DLL ...
5,788,604
5,788,781
Question about assigning default constructor to *this in C++?
I am reading some C++ text. In an example, the text written: class Student { int no; char grade[M+1]; public: Student(); Student(int, const char*); const Student& set(int, const char*); void display() const; }; Student::Student() { no = 0; grade[0] = '\0'; } Student::Student(...
It's not possible to call the default constructor directly (C++ FAQ). ie. Student::Student(int n, const char* g){ Student(); set(n, g); // validate, reset if ok } doesn't work. However I'm not sure about the solution you have, either. *this = Student() will call Student::operator=(const Student&). In this particular...
5,788,772
5,788,778
Convert CString to float in mfc
how can I convert a CString variable to a floating point? (I'm using visuall c++ 6.0 and the MFC) I'm trying to use an edit box to return a value which I'm putting into an array of floating points. I'm Using the GetWindowText method to get the value, which returns a CString. So I need to convert to a floating point. (o...
you can just do CString pi = "3.14"; return atof(pi); EDIT Also use this function: CString pi = "3.14"; return _ttof(pi); Reading a string value and parse/convert it to float allows you to locate the error when there is one. All you need is a help of a C Run-time function: strtod() or atof(). I would...
5,789,145
5,789,613
What is main difference between creation of reference vs creation of object?
So a while ago I were playing with Boost.Extension example. They used std::map<std::string, factory<computer> > computers; computers.swap(types.get()); But when I started porting project from bjam to premake to visual studio project 2008 I found out that I can not use method they used for creating map. I always g...
The difference is that the second case doesn't create a map at all; it creates a reference to a map that already exists. types contains a map, and types.get() returns a reference to that map, which you use to initialise your own reference. If you modify the map using that reference, then you are modifying the map conta...
5,789,377
5,789,414
Is there some kind of list with special (memory) addresses for Linux or gcc?
I've heard there are some special addresses(or, at lease, some ranges with special addresses), used from Linux(or gcc, I don't know and this is a part of the question), but I can't find such. And I don't even know how to look for it. ( for example, in Visual Studio, there's such thing for uninitialized variables ) And ...
In ASCII it's "0000", so it may be that something got overrun. Or that there's a memory error somewhere.
5,789,605
5,789,627
fopen with the stdin as the filename parameter
I was requested to write a program the basically parses the file given to it, with redirecting the stdin, like this: myProg param1 param2 param3 < theFileToParse I'm trying to use the fopen function in order to open the given file, but i don't understand what should i give it in the 'const char * filename' argument. ...
You don't need to open the file. Your program has a special value called stdin which contains a handle to the process's standard input stream. You can use this just as you would a file handle, for example: int c = fgetc( stdin ); or: fread( somebuffer, somesize, 1, stdin );
5,789,672
9,096,760
How to correctly wrap 3rd party library struct?
In my project I use a 3rd party library which is constantly changing. I have a wrapper class (Bridge pattern + Pimpl pattern) for this library. So none of my sources except wrapper implementation sees that library. This library has an Options struct, e.g. struct Options { double distance; double weight; int num_r...
As I use Bridge + pimpl patterns I've decided to totally hide the 3rd party library.
5,789,673
5,790,330
R: C++ Optimization flag when using the inline package
In R when using the cxxfunction from the inline package, how does one change the optimization flag for the cpp compiler? By default, on my machine, it compiles with -g -O2. But I would like to use the -O3 optimization to gain speed. I use the Rcpp plugin if that makes any difference. I have tried creating my own plugin...
There are a couple of options: The best solution is to modify this for all usage by R so create e.g. a file ~/.R/Makevars and set CFLAGS, CXXFLAGS, ... there. This will affect all use by R CMD INSTALL ..., R CMD SHLIB ... etc pp and as cxxfunction() from inline uses it, it works here too. Specific to inline and Rcpp:...
5,789,692
5,789,717
Compiler error with ASSERT-C++
#include "stdafx.h" #include <iostream> #include <assert.h> using namespace std; class A { public: int IsLocked(); }; int A::IsLocked() { return false; } int main() { A a1; ASSERT(a1.IsLocked()); return 0; } getting error as assert identifier not found.... I tried including also..
Should be: assert(a1.IsLocked()) note lower case.
5,789,762
5,789,817
could not understand including the header file
#include "Ser.h" #include ".\ser.h" Is this .\ser.h is an executable of Ser.cpp...When right clicked on it and when pressed "open the document .\ser.h" its going to the Ser.h file... Why does they again include the executable file(./ser.h) as header file.... isnt the header file(Ser.h) enough to get all the delaration...
.\ser.h is not an executable file, it's simply another header file. In systems where file names are case-irrelevant (and this seems likely here since it's using the Windows path separator \), it may well be just including the same file twice. If include guards are used correctly, that won't matter. If case is relevant,...
5,789,806
5,789,842
Meaning of *& and **& in C++
I found these symbols in a function declaration several times, but I don't know what they mean. Example: void raccogli_dati(double **& V, double **p, int N) { int ultimo = 3; V = new double * [N/2]; for(int i=0; i < N/2; i++) { V[i] = new double[N/2], std :: clog << "digita " << N/2 - i <...
That is taking the parameter by reference. So in the first case you are taking a pointer parameter by reference so whatever modification you do to the value of the pointer is reflected outside the function. Second is the simlilar to first one with the only difference being that it is a double pointer. See this example:...
5,789,829
5,798,077
Spirit Qi semantic actions and parameters for functions unrelated to the parser
How would I declare a semantic action that calls a free function that doesn't use the attribute the rule/parser returned? Like, let's say we have a parser that returns a string, but I want to call an unrelated function like Beep, which takes two integer values for frequency and duration and does not care for strings? I...
As John said you could use boost::bind. You have to be very careful not to mix and match placeholder variables from different libraries, though. When using boost::bind you need to use its placeholder variables, i.e. ::_1 (yes, boost::bind's placeholders are in global namespace - yuck). The best solution (and the safes...
5,789,843
5,790,851
How i can simulate a double mouse click on window ( i khow handle) on x, y coordinate, using SendInput?
How i can simulate a double mouse click on window ( i know handle of this window) on x, y coordinate, using SendInput?
void DoubleClick(int x, int y) { const double XSCALEFACTOR = 65535 / (GetSystemMetrics(SM_CXSCREEN) - 1); const double YSCALEFACTOR = 65535 / (GetSystemMetrics(SM_CYSCREEN) - 1); POINT cursorPos; GetCursorPos(&cursorPos); double cx = cursorPos.x * XSCALEFACTOR; double cy = cursorPos.y * YSCALE...
5,789,856
5,790,137
How to create/find header files in OpenOffice SDK 3.3.x
I have downloaded and installed the OpenOffice SDK 3.3.x and I cannot find the header files ( *.hpp or hxx ) files corresponding to the *.idl files. There are *.idl files under the ( idl/com/.../) directories. Under the include directory ( include/com/...) there are no corresponding *.hpp or *.hxx include files. I loo...
Well I would imagine that you can generate the headers from the idl. The tool you use will be dependent on the ORB and the target compiler. For example TAO ORB using MSVC++ 7. You can put the commands in a .cmd file (windows) and add it as a pre-build step is you like. set path=%path%;..\..\thirdparty\ACE_wrappers_1.7....
5,789,857
5,789,913
How to perform type scanning in C++?
I have an ESB. Any serialized message transports its own fully qualified name (that is, namespace + class name). I have a concrete type for each message that encapsulates a specific logic to be executed. Every time I receive a message, I need to deserialize it at first, so I can perform its operations --once more, depe...
C++ has no reflection capability. I suppose you could try to scan object files, etc., but there's no reliable way to do this (AFAIK); the compiler may entirely eliminate or mangle certain things. Essentially, for serialization, you will have to do the registration (semi-)manually. But you may be interested in a seria...
5,789,909
5,790,073
Calculation of accumulation area
I'm looking for a GIS/Geometric algorithm: I have 1000 points randomly distributed in a large area(such as a city), How can I find out all the small areas which have more than 15 points? Like this picture below: Each point has its own latitude and longitude coordinates. The small area less than 200m x 200m.
You should take a look at RTREE structures. See http://en.wikipedia.org/wiki/R-tree You've such algorithms implemented e.g. in the SQlite3 engine. See http://www.sqlite.org/rtree.html Our Open Source version already includes the RTREE extension for Delphi 6 up to XE, compiled by default since rev. 1.8.
5,789,990
5,790,108
Pass parameters as array?
Is it better (performance …) to pass parameters as array template<typename Number> static int solveQuadraticFunction(Number* dst, const Number* src) { Number a=src[0], b=src[1], c=src[2]; // … } or the "standard" way template<typename Number> static int solveQuadraticFunction(Number* dst, Number a, Number b, Numbe...
Probably not. It depends on the arrangement of the arguments before the call. In the former case, you're requiring that the arguments be arranged into an array before the call, which might already be the case, or it might not; if it is already the case, and there are a large number of arguments, then it may be more opt...
5,790,161
5,790,259
Is the backslash acceptable in C and C++ #include directives?
There are two path separators in common use: the Unix forward-slash and the DOS backslash. Rest in peace, Classic Mac colon. If used in an #include directive, are they equal under the rules of the C++11, C++03, and C99 standards?
C99 says (§6.4.7/3): If the characters ', \, ", //, or /* occur in the sequence between the < and > delimiters, the behavior is undefined. Similarly, if the characters ', \, //, or /* occur in the sequence between the " delimiters, the behavior is undefined. (footnote: Thus, sequences of characters that resemble es...
5,790,165
5,790,217
how to store the content of variable into const char*?
i have a pointer or variable which stores the address like 0xb72b218 now i have to store this value in to const char*. how i can store it. Thanks in advance. I tried following: suppose i have a pointer variable "ptr" which contains 0xb72b218 value ostringstream oss; oss << ptr; string buf = oss.str(); const char* value...
Well... if you really want the address of something in a string, this will do: #include <stdio.h> #include <iostream> int main(){ char buf[30]; void* ptr = /*your pointer here*/; snprintf(buf,sizeof(buf),"%p",ptr); std::cout << "pointer as string: " << buf << "\n"; std::cout << "pointer as value: " << ptr <...
5,790,305
5,790,847
Workaround for specialized template for member function, when template class is not specialized
I'm building a datastructure class with an std-like interface, and implementing different iterators for the data structure. Conceptually, what I would like to do is something like this: template <class DataT> class DataStructure { protected: DataT& Data; public: DataStructure(DataT& data) : Data(data) {} cl...
Function templates cannot be specialized in C++, point. It does not matter whether they are members of template or not, specialization of function templates is not allowed. Normally when using argument types to infer the template arguments, overloading does the same specialization would, so specialization for functions...
5,790,315
5,790,369
How to change the base class variables with the derived class object-c++
#include "stdafx.h" #include <iostream> using namespace std; class A { public: int a,b,c; A() { a=0; b=0; c=0; } }; class B:public A { public: void get() { A *a2 =new A; a2->a=10; a2->b=20; a2->c=30; cout<<a2->a<<""<<a2->b<<""<<a2->c<<""<<endl;...
In your get() method, you are actually creating a temporary instance of Base class A, which has nothing to do with the class getting derived. Simply remove a2 from everywhere in your get() and try it. You will be able to see the changes happening. [Note: Base class object is automatically allocated when derived object ...
5,790,456
5,790,479
с++ question new delete
I have the following code void foo() { char* pcBlock = new char[1000]; ... delete[] pcBlock; ... pcBlock = new char[100000]; ... delete[] pcBlock; } Would the code below result in a memory leak? void foo() { char* pcBlock = new char[1000]; ... pcBlock = new char[100000]; ......
Yes, there's likely a memory leak if you don't delete[] pcBlock in the first .... Reassigning a pointer does not automatically delete what it previously pointed to.
5,790,468
5,790,841
JNA Error at Program Exit
So I have the following in c++ __declspec(dllexport) extern "C" char** get_prop_types( int* count ) { const vector<string>& r = prop_manager::get_prop_types(); char **p = (char**)malloc( r.size() ); char **ptr = p; for( vector<string>::const_iterator it = r.begin(); it!=r.end() ; ++it ) { *p = (char*)malloc...
This: *p = (char*)malloc( it->size() ); should be: *p = (char*)malloc( it->size() + 1); And I just noticed that: char **p = (char**)malloc( r.size() ); should be: char **p = (char**)malloc( r.size() * sizeof(char *) ); which shows how often I use malloc these days!
5,790,483
5,790,522
How to define an interface in C++?
I'm working on a C++ class which provides an abstraction of BSD sockets for networking. I want to define an interface ISocket which is implemented by CSocket and MockSocket (the latter for unit testing). I know that I need to define the methods that I want implementing classes to provide as pure virtual, i.e. class ISo...
In general, you should declare a virtual destructor; otherwise you'll get into undefined behaviour if you try to invoke delete on a pointer-to-interface. There are no such issues with constructors. Oh, and you are correct that it is not possible to instantiate an object of a class with a pure-virtual.
5,790,514
5,793,706
QThread - Using a slot quit() to exit the thread
I want to inform an object when a thread has finished running. However, I cannot get the thread to exit properly. I have the following code: Processor.cpp thread = new QThread; tw = new ThreadWorker; connect(tw, SIGNAL(updateStatus(QString)), this, SLOT(statusUpdate(QString))); tw->doSetup(thread, strDic); tw->moveToTh...
Assuming that Processor.cpp is running in your main thread, the while(thread->isRunning()) loop has your main thread completely tied up. This means that your application's event loop cannot do any processing so the signalupdateStatus() for example, will never get processed. As mentioned in the comments, since the QThre...
5,790,534
5,790,610
Static structure initialization with tags in C++
I've searched stackoverflow for an answer but I cannot get something relevant. I'm trying to initialize a static structure instance with initial values by specifying their tags, but I get an error at compilation time: src/version.cpp:10: error: expected primary-expression before ‘.’ token Here's the code: // h typedef ...
The feature you are using is a C99 feature and you are using a C++ compiler that doesn't support it. Remember that although C code is generally valid C++ code, C99 code isn't always.
5,790,595
5,790,672
Test if multiple variable values are either all positive or negative
Is there a good and fast way in C/C++ to test if multiple variables contains either all positive or all negative values? Say there a 5 variables to test: Variant 1 int test(int a[5]) { if (a[0] < 0 && a[1] < 0 && a[2] < 0 && a[3] < 0 && a[4] < 0) { return -1; } else if (a[0] > 0 && a[1] > 0 && a[2] > 0 ...
I think your question and what you're looking for don't agree. You asked how to detect if they're signed or unsigned, but it looks like you mean how to test if they're positive or negative. A quick test for all negative: if ((a[0]&a[1]&a[2]&a[3]&a[4])<0) and all non-negative (>=0): if ((a[0]|a[1]|a[2]|a[3]|a[4])>=0) ...
5,790,980
5,791,036
C++ interface multiple inheritance with same method
I need to inherit from two interfaces which both have the same method which in both cases should perform exactly the same thing. Is this code correct or not? I need this for some kind of proxy class. Thanks for answers. class InnerInterface { virtual int getID() const = 0; //... }; class OuterInterface { vi...
Yes, this is correct. The single getID() method can override both virtual methods.
5,791,335
5,791,392
How to compile and build a very simple Gnu linux application to Windows using Mingw or Cygwin?
I would like to port an existing Linux application from its plain C/C++ source code to Windows XP/Vista/7 exactly same functionality to have, without losing few modules here and there etc. Basic codes are fine to build, but problem is the application I will be porting have other Linux dependencies. Question: How can I ...
MinGW is, by nature, minimalist; it tries hard not to bring any baggage with it. It sounds like you actually want baggage, in which case rather than using MinGW you should be using Cygwin, which emulates/implements many UNIX system calls and libraries on Windows. The whole GNU toolchain is there, and many times you can...
5,791,353
5,791,429
Convert from std::string to DWORD
I have a simple problem with a conversion: std::string str = "0xC0A80A02" and I need to convert it to DWORD. I searched on the web and found some solution but none seems to work. try1: DWORD m_dwIP = atol(str.c_str()); try2: std::istringstream ss(str.c_str()); ss >> m_dwIP; try3: sscanf (str.c_str(),"%u",st...
istringstream will work fine, just strip off the 0x prefix and use the std::hex formatter: std::string str = "0xC0A80A02"; unsigned int m_dwIP; std::istringstream ss(&str[2]); ss >> std::hex >> m_dwIP; std::cout << std::hex << m_dwIP << "\n"; Outputs c0a80a02.
5,791,384
5,791,433
Dealing with trees of different node types
I am having a tree data structure that can have different types of nodes deriving from one TreeBaseNode class. I have made the tree nodes of type TreeBaseNode * which gets assigned to objects of different Special nodes at run time. How can I access aNodeAttribute from the TreeBaseNode* pointer while traversing the tre...
There is no polymorphism of data-members of clases in c++, but you can use polymorphism of function-members. So you should declare virtual int getNodeAttribute(){} in your base class. And reimplement it in two Derived classes to return attribute what you want.
5,791,613
5,791,986
Unresolved externals when compiling code which uses a dll
I'm trying to get started on using dll's for my code in VS 2005. The code I have is very simple, just to try a test case. testdll.h: #ifdef TEST_EXPORTS #define TESTDLLPORT __declspec( dllexport ) #else #define TESTDLLPORT __declspec( dllimport ) #endif namespace TestDLLNS { static int s = 0; class MyTest...
There are few things to note and I hope you did not miss them. What you have is a linking error, means that your compiling was okay, but there is a link error. The error shows that the linking does not find a definition for your printDLLFuncs() function which was referenced in the object file. You either have to provi...
5,791,668
5,791,741
Is there a way to create a std::vector of dynamically allocated arrays?
For example, is it possible to have a std::vector of these arrays? int *test1 = new int[10]; int *test2 = new int[20]; int *test3 = new int[3];
Yes. std::vector<int*> vints; vints.push_back(new int[10]); vints.push_back(new int[20]); vints.push_back(new int[3]); But there is a problem: the vector can't remember the size of each dynamically allocated arrays. So better use std:map as: std::map<int, int*> arrayMap; arrayMap[10] = new int[10]; arrayMap[20] = new ...
5,791,996
5,793,465
Re-registering User-defined Window Class - C++
I'm getting a class already exists error from the call to RegisterClassEx in the following code. This code is in a class constructor: this->m_wcx.cbSize = sizeof(WNDCLASSEX); // size of structure this->m_wcx.style = CS_HREDRAW | CS_VREDRAW; // initially minimized this->m_wcx.lpfnWndProc = &WndProc; // points to...
UnregisterClass() will fail (will not delete the class) if there are windows of that class in the system. So you will need to ::DestroyWindow() for all windows that were created with the class.
5,792,082
5,792,154
Why are there no capacity argument in the constructors for the containers?
If I want to set the capacity to a std::vector I have to call .reserve(...), are there any reason why there is not a capacity argument in the constructor for the containers in stl, std::string, std::vector?
There is one obvious reason: what would such a constructor look like? All of the sequence containers already have a constructor that can be called with a single integer argument. That constructor resizes the container to have the specified number of elements. Yes, you could add a second parameter (like bool reser...
5,792,111
5,792,204
C++ Help with setf floatfield from string
*mit = 13311 std::istringstream iss(*mit); double temp; iss.setf(ios::fixed, ios::floatfield); iss.precision(15); iss >> temp; std::cout<<"temp "<<temp<<endl; std::stringstream ss; ss<<temp / 1024; I had tried with / without set precision, I still got 12.999, instead 12.9990234375 Please advise what did I do wrong? ...
Add std::setprecision( 15 ) in the cout std::cout<< "temp " << std::setprecision( 15 ) << temp <<endl; EDIT: sorry, if I got you wrong. You expect to see 12.9990234375 printed or you expect ss to be 12.9990234375 ? If the second, then make: ss << std::setprecision(15) << temp / 1024;
5,792,272
5,792,414
Loading native COM DLLs in 64bit environment
I have a 32bit/64bit COM DLLs in C++: mycom32.dll, mycom64.dll. Both of them are exactly the same but mycom32.dll is compiled for 32bit and mycom64.dll is compiled for 64bit. That means that BOTH DLLs have the same UUID and the same CLSID! Now, sometimes I want to use this COM from 32bit processes and sometimes I want ...
It should be possible to register both of them without issue; this is part of what Registry Redirection is supposed to solve. Here's a more detailed explanation of how this works.
5,792,508
5,804,005
In boost.python; how do I expose a class that is contained in another class (via composition)?
I'd like to do something really simple with boost::python. I can find documentation for class member functions, and documention for inherited classes but nowhere can I find the syntax for exposing class hierarchies created via composition. So I have some C++ code that goes something like this: struct A{ double x,y;...
Documentation for dir says: If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. In your example, your class member are exported as instance attributes and not class attributes which is what you want when exporting non static class me...
5,792,519
5,792,566
string searching with exclusions
Firstly, I do not have the option to use Regular Expressions. It pains me to say this. My problem is I may have a std::string that might contain something like: std::string someString = "(U//DISTRIBUTION//DONE)". What i'd like to do is search the string for just the captial U and nothing else around it. In other wo...
Make sure that you pad your searchee string with leading and trailing // (if it's not already present) and then use someString.find("//U//") != std::string::npos.
5,792,526
5,792,594
Operator keyword used in an unexpected manner in a function
I ran across this code recently which is part of a template class: operator T*(); I have been unable to find a clarification on this on SO or online. I have been unable to figure out how this declaration is working.
It's an implicit cast operator that allows the object to be converted to a T*. For instance : template<typename T> class arrayOf10T { T data[10]; operator T*() { return data; } }; Allows you to cast an arrayOfT into an int* like this : int* ptr = arrayOf10T<int>;
5,792,703
5,793,073
Moving unique_ptrs from one vector to another
I'd like to move the unique_ptr's stored in an unsorted vector of them to another vector, that will contain the sorted vector of pointers. Surely moving a unique_ptr will not automatically erase the element in the first vector? How can I do this? Example of what I want to do: std::vector<std::unique_ptr<T> > unsorted, ...
Your code looks basically correct to me, except that it seems like you intend for the moved-from unique_ptr to be erased from the unsorted vector: std::vector<std::unique_ptr<T> > unsorted, sorted; // fill the "unsorted" vector while( unsorted.size() > 0 ) { const auto it = find_next_element_to_add_to_sorted(unsort...
5,792,704
5,792,865
convert int[2] to long
I have an int[2] representation of a long int in a 32 bit machine and want to convert it to long on 64bit machine. is there a safe architecture independent way of doing this conversion? The source machine is 32bit and an int is 32bits. Destination machine is 64bit and the long long type is definitely 64bits. can I do t...
I have an int[2] representation of a long int in a 32 bit machine and want to convert it to long on 64bit machine. is there a safe architecture independent way of doing this conversion? Not really. Because apart from endianness, the sizes of the two datatypes may vary as well. On some popular platforms, int and long ...
5,792,727
5,838,364
Looking for unnecessary buffer copies in assembly code
I am using Visual Studio 2008 C++ for Windows Mobile 6 ARMV4I and I'm trying to learn to read the ARM assembly code generated by VS to minimize unneessary buffer copies within an application. So, I've created a test application that looks like this: #include <vector> typedef std::vector< BYTE > Buf; class Foo { publi...
Analyzing Create is fairly straightforward, because the code is so short. NRVO clearly has been applied here because the return statement generated no instructions, the return value is constructed in-place in r0. The copy that would take place for Foo::Foo's pass-by-value parameter is slightly harder to analyze, but t...
5,792,883
5,793,218
Zip directory in C++
How can I zip directory in C++. I read this question: How do I zip a directory of files using C++? But I'd prefer a way that uses something like gzip, zlib and boost(because I do not want to add new libs to the project). Winapi-way is also acceptable (if it exists). And I do not want to start new process. I would like ...
You want zip but you don't want to use any libraires? Do you want to be bound by a particular licence - if so then simply copy all the code from zlib and the zip add-on into your own code. If you can't use their licence then get the specs and write your own clean room implementation - make sure that you haven't seen t...
5,792,957
5,793,656
use of IPC in Cpp in Android
after having a bit exploring at Android2.2 source code,I get to know Android Framework works with large number of IPC mechanisms written in Cpp, such as CameraService,MediaService and etc. I also see those many key classes drive these IPC mechanisms, such as IInterface, BpInterface, BnInterface, Binder, IBinder, RefBa...
There is basically no documentation on these, since they are not part of the public SDK/NDK. If you are working at this level, you are doing platform development; the documentation is for the most part the rest of the platform and the source code of the things you are using. You will find these a lot rougher to use th...
5,793,030
5,793,048
How to get file size on disk on linux?
I want to find the size of file on disk on linux OS . I know command to do so: du -s -h Is there any way to find it using c/c++ code ?
Yes, use the stat(2) system call: #include <sys/stat.h> ... struct stat statbuf; if (stat("file.dat", &statbuf) == -1) { /* check the value of errno */ } printf("%9jd", (intmax_t) statbuf.st_size);
5,793,069
5,793,536
How to get the return code of a spawned program
This will run a program and give me the return code. int returnCode; returnCode = system(program); How can I do the same thing with execv?
The exec family of calls trash the current process and launch the new program within the same process space. If you want to execute another program within your current program, you need to spawn a new process using fork You then call exec in the child process and get the parent to wait until the child process completes...
5,793,114
5,793,137
C++ is blowing my mind
#include <iostream> int main() { int x = 1; for(int i = 0; i < 100; ++i); // What will the next line do? Increment???????????/ ++x; std::cout << x << std::endl; } Why does the code print 1 and not 2?
The trigraph sequence ??/ sequence is converted to '\' so ++x is a part of the comment line. This gotw article discusses the same problem[exact same code].
5,793,334
5,794,619
C++, static vs. namespace vs. singleton
I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this. I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones)....
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often). Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here...
5,793,531
5,793,562
equivalant of fprint in c++
g++ (GCC) 4.6.0 20110419 (Red Hat 4.6.0-5) what is the equivalent of this in c++? I know that this will compile in g++. But I just interested to see if there is any thing else in c++ that I can use like this. fprintf(stderr, "Server failed to receive message [ %s ]\n", stderror(errno)); Many thanks for any suggestions...
What about: std::cerr << "Server failed to receive message [" << stderror(errno)) << "]" << std::endl;
5,793,636
5,793,655
Why is “strcat” considered as “unsafe”?
Possible Duplicate: Why does MSVC++ consider “std::strcat” to be “unsafe”? (C++) Here is my code: char sentence[ 100 ] = ""; char *article[ 5 ] = { "the", "a", "one", "some", "any" }; lexeme = rand() % 4; // random lexeme strcat( sentence, article[ lexeme ] ); strcat( sentence, " " ); While debugging in MSVC++ it ...
This is because there's nothing to stop you from strcat-ing more than 100 bytes into your sentence buffer, with undefined results up to and including heap corruption, stack corruption, program exit, even somebody owning your machine if the data past the 100th byte is appropriately constructed. This is a common class o...
5,793,986
5,794,022
convert float to string
Possible Duplicate: Convert double to string C++? I searched in the page but i haven't found the solution. I have a method to convert from int to string. But now i need to convert from float/double to string. Because i want to write some data in a file. Anyone could help me ?? Thanks in advance.
http://www.daniweb.com/software-development/cpp/threads/146718 #include <sstream> std::string Convert (float number){ std::ostringstream buff; buff<<number; return buff.str(); }
5,794,347
5,794,587
No class template named X in templated class
When tryin to compile this (CRTP-like) code with GCC 4.6.0: template<template<class> class T> struct A; template<class T> struct B: A<B<T>::template X> { template <class U> struct X { U mem; }; }; B<int> a; I get the errormessage "test.cpp:3:26: error: no class template named ‘X’ in ‘struct B<int>’". Why does X ...
As Emile Cormier correctly points out here the problem is that at the place of instantiation of A, B is still an incomplete type, and you cannot use the inner template. The solution for that is moving the template X outside of the template B. If it is independent of the particular instantiation T of the template B, j...
5,794,727
5,794,893
Using RPC or something else
Does RPC is still in use nowadays. Or rpc were replaced by other technology? If i start new project in C++ should i consider use of RPC? More info because i know that RPC is still in use in production code: I have two apps to communicate each other. These two are on same machine but one is service, second is user app. ...
Remote Procedure Call is a very generic idea and not something specific. There are ZeroC Ice, CORBA, Java RMI, SOAP, DRb, WCF and a lot more technologies that are built around the idea of RPC. They are being used indeed. For example, CORBA is used by some Electronic Currency Exchanges (ECNs), ZeroC is used by Skype, He...
5,794,943
5,794,969
C++ Integer array and boolean functions
I need to write in C++ a complete boolean function that will take an integer array and it's maximum size as a parameter and return whether or not that array has any elements with a value of 0. I'm not even sure where to start. Thanks in advance.
bool checkFunction(int *myArray, int size) { for (int i=0; i < size; ++i) { if (myArray[i] == 0) return true; } return false; } Are you talking about something like this? This will iterate through the array and return true if there is a value of 0 anywhere.
5,795,270
5,826,603
Keep .exe timestamp from changing
Does anybody know of a way to prevent the timestamp of an executable from changing? I'm trying to generate a consistent hash code for the .exe but I think the timestamp may be preventing that from happening. Each time I recompile the code (VS C++) the FastSum generates a different checksum. Thanks!
Depending on what you have to checksum, you can either strip off the COFF header (where the timestamp resides) or the Optional Header. In the latter case, you just only save the section table and section data (the binary content of the executable). If you make sure your source code is not changed and compile and link f...
5,795,283
5,796,250
Creating and sending data packets in C/C++
Let's say I want to send the following data to a socket using C or C++, all in one packet: Headers ------- Field 1: 2 byte hex Field 2: 2 byte hex Field 3: 4 byte hex Data ---- Field1 : 2 byte hex Field1 : 8 byte hex What would the code typically look like to create and send the packet containing all this data?
Let's suppose that your program is already organized to have the header in one struct and the data in another struct. For example, you might have these data structures: #include <stdint.h> struct header { uint16_t f1; uint16_t f2; uint32_t f3; }; struct data { uint16_t pf1; uint64_t pf2; }; Let's c...
5,795,304
5,795,327
Count lines in files of type *.cpp and *.h only
I have already following bash script. It count lines in *.cpp only. How i can count line in the *.h file too without pugixml.cpp? find . -type f -name \*.cpp -and ! -name \pugixml.cpp -exec cat '{}' + | wc -l
Use -o to look for files named *.cpp or *.h, and add parentheses for precedence. Note that I've removed the -and and the backslash in \pugixml as they were unnecessary (though harmless). find . -type f \( -name \*.cpp -o -name \*.h \) ! -name pugixml.cpp -exec cat {} + | wc -l Also you could reduce find -exec cat {} +...
5,795,354
5,795,408
Conditional compilation from .h and .cpp
I'm trying to make a library file. The .cpp file has some conditional compiled lines. The code can be found at: HMC58X3.h http://sprunge.us/hEYW HMC58X3.cpp http://sprunge.us/faRN HMC58X3_raw.pde http://sprunge.us/BFVj Basically, in the Arduino sketch file HMC58X3_raw.pde I define ISHMC5843 and in both HMC58X3.cpp and ...
A #define is not like a global variable. It's a pre-processor macro that only applies to the remaining text of that compile unit. There are a couple ways to do what you want: Create a config.h with #define ISHMC5843 and be sure to include it everywhere (and before any other includes that reference it). In your Makef...
5,795,606
5,795,650
sql connectionstring debug step by step?
Hello I hope this is my last post concerning sql connectionsstrings.... I have a win32console app written in VS2010Express and I try to connect my SQL server. I think i did everything right and that the "only" problem is the connection string. Could anyone please confirm that there is no other big mistake in the code? ...
You need to escape backslashes, so: connection->Open(L"Data Source=PETERPAN\SQLEXPRESS;Initial Catalog=Stackhoover; User Id=Test; Password = Test", L"", L"", USEADO::adConnectUnspecified); should be: connection->Open(L"Data Source=PETERPAN\\SQLEXPRESS;Initial Catalog=Stackhoover; User Id=Test; Password = Test", L"", L...
5,795,704
5,796,095
Can Boost.Asio strand.dispatch() block?
I'm experimenting with Boost.Asio strand for a server I'm writing and wanted to clarify a few things. Let's assume we have SomeClass with something like this: void SomeClass::foo() { strand_.dispatch(boost::bind(&SomeClass::bar, this)); } Further, the strand has an io_service with multiple threads calling run(). ...
Logically, it would be impossible for this guarantee to be met without some possibility of (b)locking. The code for dispatch (in detail/impl/strand_service.hpp from 1.46.1) confirms this. That's the nice thing about Boost, it's all there for you to see. There is info on order of handler invocation in the docs here, ...
5,795,790
5,796,979
Update part of database on app update
I'm developing an application with C++ (Qt) and SQLite. The app is installed with predefined database filled with some records. User has the ability to extend the database with his own records. I'm wondering how to achieve update of the app, i.e. when new version of app is being installed, I want to remove the old core...
There's a third variant: Keep your original tables as you need them for the app. For every table: Add a second table that consists of just one column. These columns reference the PKs of your 'real' tables. Then insert the keys of your default records in the new tables. During the update, just join the corresponding ta...
5,795,892
5,795,909
Even the simplest class doesn't compile, "has not been declared
OK, this is really annoying. I have the (almost) simplest class possible. Two files: a.cpp and a.h a.h: #ifdef A_H #define A_H class a{ public: a(); }; #endif and a.cpp #include "a.h" a::a(){ } and yet it won't compile: g++ a.cpp a.cpp:3: error: ‘a’ has not been declared Clearly, I am doing something wrong,...
Its because #ifdef A_H needs to be #ifndef A_H notice the "n", as in if NOT defined. The former will only compile the code if A_H is defined, which it isn't since you only define it on the next line.
5,796,023
5,796,132
Tower of hanoi problem
Hi Guys I am faced with a problem on tower of hanoi: we are given a stack of cylinders of alternate colors stacked over one another alternately.The job is to separate the two stacks of same colour I could write the code(algorithm) for a regular tower of hanoi using recursion, but I am not able to figure out this part. ...
Solve the problem n times, alternating pegs that you leave the solution on. int main() { int n; cout<<"Enter the height of stack"; cin>>n; char startPeg = 'A'; char interPeg = 'B'; char slnPeg = 'C'; while(n > 0) { hanoi(startPeg,interPeg,slnPeg,n); n--; char temp =...
5,796,362
5,796,666
Reading text from a website in C++
I am currently coding a chat application-like-thing, and it writes and reads from a .txt file on DropBox in my 'public' folder. I was wondering how exactly I could achieve this. My code so far is: #include <iostream> #include <fstream> #include <Windows.h> #include <cstdlib> using namespace std; int main () { str...
Check out the libcurl library. It supports many file transfer protocols, including HTTP. There is also curlpp which is a C++ wrapper around libcurl. See this related question for an example. Reading the file via HTTP should be fairly straightforward. Alas, I don't know what mechanism Dropbox uses to upload files (WebDA...
5,796,375
5,796,462
How to use FLAC in iPhone application?
I'm developing iPhone app that should use Google Voice API, so my app should convert voice recorded in m4a to flac. Of course I should use libflac, but all my attempts to compile static library for iOS were failed due to linker errors. So the question is: where could I find static iOS binaries of libflac or what should...
ScummVM has libflac in their iPhone setup. See: http://wiki.scummvm.org/index.php/Compiling_ScummVM/iPhone I'm sure you can look over their setup to figure it out.
5,796,678
5,796,735
C++ define interface
#define interface class (here is more - http://www.codeproject.com/KB/cpp/CppInterfaces.aspx ) Does that make sense? Does this clarify the difference between interfaces and implementing them classes? Or it's confusing, because it's obvious that pure virtual classes are interfaces? Do you use it? or "macros are evil"?
I'd say it makes no sense. The "solution" proposed in that article looks like a horrible mess - what's wrong with using C++ as it is? Why introduce some crappy macros when you can just define a pure abstract class when you need one and be done with it? It looks like someone with C#/Java background was trying to find hi...