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
7,809,270
7,809,621
Call a class' function in the constructor. C++
I was curious since I thought of the idea as a solution to improve the readability of my code for my assignment. When I create an object of a class, is there a way to call one of the object/class' functions inside the constructor? If I'm not explaining myself clearly enough just ask and I'll try to expound on it.
Of course you can... ... But beware of virtual methods There is only one catch, though: Avoid calling virtual methods as you won't call the most derived method, only the most derived for that class. For example: class A { public: A() { std::cout << "A::A()" << std::endl ; } virtual void foo() { std::cout...
7,809,277
7,811,269
CUDA Cusp in Windows7
I have trouble getting the CUSP (version 0.2) library running under windows7 x64 and visual studio 2008. When including for example: #include <cusp/hyb_matrix.h> i get the following error: error C2039: 'hypotf' : is not a member of '`global namespace'' c:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include\cu...
POSIX standard math libraries provide hypot and hypotf. Microsoft's libraries define _hypotand hypotf. You will probably have to patch cusp/complex.h to work around it. You might also want to post a bug report with the CUSP developers here, this seems like something they would want to fix.
7,809,303
7,810,739
Porting kernel project from DJGPP to MinGW
Trying to compile a C++ kernel project with MinGW & NASM (formerly DJGPP & NASM). Have actually tried Cygwin too, with the exact same results below: First, just swapped out \DJGPP\bin for \MinGW\bin. Got the following link error: target coff-go32 not found. Swapped target to elf32-i386, and got cannot perform PE opera...
You need to build a free-standing cross compiler. This problem has been referenced many times at the OSDev Wiki to the point that most people recommend you begin writing a kernel by first creating a cross compiler. This article will provide a step-by-step reference to building your own cross compiler. Note, in Windows,...
7,809,321
8,019,855
Python C API - Stopping Execution (and continuing it later)
1) I would like to use the profiling functions in the Python C API to catch the python interpreter when it returns from specific functions. 2) I would like to pause the python interpreter, send execution back to the function that called the interpreter in my C++ program, and finally return execution to the python inter...
If I understand your problem, you have a C++ program that calls into python. When python finishes executing a function, you want to pause the interpreter and pick up where the C++ code left off. Some time later your C++ program needs to cal back into python, and have the python interpreter pick up where it left off. I ...
7,809,468
7,809,637
friendship with extern "C" function seems to require :: to qualify name
Trying to make a class friends with an extern "C" function, this code works: #include <iostream> extern "C" { void foo(); } namespace { struct bar { // without :: this refuses to compile friend void ::foo(); bar() : v(666) {} private: int v; } inst; } int main() { foo(); } extern "C" { v...
[n3290: 7.3.1.2/3]: Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup (3...
7,809,623
52,413,963
Can we rely on any guarantees based on memory layout and default destructor
A while ago we had this declaration (simplified): Declaration 1 struct SomeType { // allocates Implementation in SomeType's TU SomeType(); // ... other stuff struct Implementation { std::string someAtribute1; std::string someAtribute2; } std::auto_ptr< Implementation> pimpl; }; Some time later ...
I "cross posted" this on comp.lang.c++ where Alf P. Steinbach made me realize that TU's compiled against 'Declaration 2' is leaking memory (which is rather embarrassing). Based on this we will revert to 'Declaration 1' and recompile every domain that is compiled against 'Declaration 2', hence we do not have header or A...
7,809,987
7,815,545
C++: how to define a class method as a start routine to thread (with pthread library)
i have a Base class and Derived class. they have a virtual function- virtual void action() how can i pass it to *pthread_create()* function? example(with errors): class Base{ protected: pthread_t tid; public: virtual void* action() = 0; }; class Derived : public Base{ void* action(); Derived(){ pthr...
I ran into this problem a couple months back working on my senior design project. It requires some knowledge of underlying C++ mechanics. The underlying issue is that pointers to functions are different from pointers to member functions. This is because member functions have an implicit first parameter, this. From the...
7,810,227
7,810,764
TeamCity MSbuild C++ only build some solutions
In our C++ project we have several solutions, is there a way to only build select solutions in TeamCity. Or is there parameters for msbuild that can accomplish this? We are using .Net v4.0 Thanks in advance.
I guess you have several projects in your solution? You can create a build configuration (something like Debug/Release) for the whole solution und choose which projects should be built in this. You can pass this configuration's name to Teamcity.
7,810,396
7,810,479
Convert .lib and .h files to .NET
A brokerage firm has an API built around C++ provided as a library and header files for users to consume(orders, prices, news..etc), long story short, I only have practical knowledge of C# and would like to make use of some wrapping technologies to make use of the .lib and .h files provided by converting them into mana...
You can use C++/CLI. Try to starts from here. Basically I would create a C++/CLI wrapper in order to expose a wise set of functionality to c#. Anyway, it is not an easy task. An alternative is to write in pure c++ some extern "C" entry point to the library and access that api using P/Invoke.
7,810,489
7,815,705
Create directx9 texture using a portion(s) of an image
i have an image(208x8) and i would like to copy 8x8 squares from it at different areas then join all the squares to create one IDirect3DTexture9*
Depending on exactly what you are trying to do IDirect3DDevice9::UpdateSurface or IDirect3DDevice9::StretchRect might help you. For simple operations on very small textures like you are describing, it can be advantageous to manipulate them using the CPU (i.e. with IDirect3DTexture9::LockRect). With D3D9 this usually im...
7,810,508
7,810,555
Returning an iterator over a template vector
I've been searching around for something similar but couldn't find it (or what I found wasn't helpful). I'm trying to be able to have an iterator over a vector of a template class, returning it and using it outside the class, as demonstrated in the code below. #include <iostream> #include <vector> using namespace std;...
I got different errors than you (missing typename, missing ;, missing ns::). Apparently, the different errors messages were from different versions of GCC. You ran this under g++ 4.1.2. I use g++ 4.6.1. After fixing all of the errors, this works for me: #include <iostream> #include <vector> using namespace std; name...
7,810,618
7,810,660
Call function template of class template in external function template
Possible Duplicate: Where and why do I have to put “template” and “typename” on dependent names? I have following constellation: template<typename T> class A{ template<typename U> A<U> f()const; } template<typename T, typename U> A<U> F(const A<T> &I) { return I.f<U>();//this does not work } The compiler er...
That's two-phase lookup for you. Do this: I.template f<U>(); This is necessary because, when the compiler compiles the function template F(), it does not know what T it might be instantiated with. A could be specialized after the definition of F(), which would only be known the moment F() is actually instantiated. Th...
7,810,632
8,099,608
How to use and set axes in a 3D scene
I'm creating a simulator coded in python and based on ODE (Open Dynamics Engine). For visualization I chose VTK. For every object in the simulation, I create a corresponding source (e.g. vtkCubeSource), mapper and actor. I am able to show objects correctly and update them as the simulation runs. I want to add axes to h...
Well, if you do not mess with objects' transformation matrix for display purposes, it could probably be sufficient to just put your camera into a different position while using axes approach 2. The easy methods to adjust your camera position are: Pitch(), Azimuth() and Roll(). If you mess with object transforms, then a...
7,810,701
7,811,289
C++ Template deduction while calling a template function
FastDelegate refers to http://www.codeproject.com/KB/cpp/FastDelegate.aspx, but I don't think it is related. I have code like following, and got error. #include <FastDelegate.h> using namespace fastdelegate; template <typename T> T Getter() {} template <typename T> void Setter(T) {} template <typename T> class Pro...
Have you tried Prop<int>* c = MakeProp(FastDelegate0<int>(Getter<int>), FastDelegate1<int>(Setter<int>)); ? Setter<int> cannot be converted to FastDelegate1<T>!
7,810,773
7,810,871
ERROR: does not name a type
I'm implementing a chess game in c++ and some of the classes are "Board" and "Piece". There are classes "Rook", "King",... etc inherited from "Piece". So a board is a 2D array of pieces and so board.h has piece.h included. For recent development (on implementing moves) I wanted to give the pieces access to the board. ...
Since move only uses a reference, you could definitely avoid the inclusion of board.h and only forward declare your class Board. If you really need to have piece know about board and board know about piece, you could declare an interface class to Board (pure abstract) and include that interface instead of the board mak...
7,810,947
7,811,064
Add to C++ application C# GUI
I would like to add my C++ application a C# .NET GUI . My C++ application is very simple but I have a some Pointer and Reference . What is the Best way C# will recognize this pointer and Reference?
There are several ways, here are some, and it depends on your taste and on your project. a) Use COM interop, if your C++ project is written in COM. b) Use COM interop, you can write COM wrappers to your C++ application and use it from C#. c) Use C++/CLI, that is, convert your project to become a Managed C++ application...
7,811,055
7,811,065
C++ "undefined reference to..."
I cannot figure out why my code is breaking, and I could use some help. First of all, the code: Timer.h: #include [...] class Timer { public: [...] Timer operator+(double); [...] private: [...] void correctthedate(int day, int month, int year); [...] }; Timer.cc...
The following line: void correctthedate(int day, int month, int year) { should read void Timer::correctthedate(int day, int month, int year) { Otherwise you're just defining an unrelated function called correctthedate().
7,811,118
7,811,188
How does one call into COM from worker thread created with NT's QueueUserWorkItem?
I've got a set of tasks that I slaved to the NT threadpool using QueueUserWorkItem. I need to make some calls to COM from these separate threads to access data inside WMI. I'm unsure, however, how the correct calls to CoInitializeEx need to be made. Basically, the CoInitializeEx docs say that the call should be made on...
You can call CoInit and CoUninit multiple nested times, they just have to be balanced. Your proposed solution of doing it at the beginning and end of your thread proc is reasonable. Just make sure you don't have any early exits that skip the CoUninit call, and don't call CoUninit if CoInit fails.
7,811,190
7,811,244
Multiple Inheritance in C++ vs Java
When i came across the reason why Multiple Inheritance was not included in Java, the reasons given were to keep 'simplicity' and 'reduce complication'. However working with Java environment coming from a C++ background, don't you think that Interface concept to support multi inheritance has complicated the matter rath...
Multiple implementation inheritance and multiple interface inheritance are not the same beasts. However, it would significantly complicate the GC and other language implementation if they were to add multiple implementation inheritance.
7,811,245
7,811,285
Is it possible to bind and listen to one IP address with TCP/IP sockets? (Linux/C)
I have always used: serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); which means that I will accept connections from any interface. If I replace the INADDR_ANY with “192.168.0.1”. Does this mean I will only accept connections from the IP address of 192.168.0.1, or does it mean I will accept connections from the interfac...
The bind address is the local address to listen on; you can specify the address of a local interface. If you want to control who can connect, you can either inspect the peer address inside the select/accept loop, or limit inbound connections using iptables. Update If I say serv_addr.sin_addr.s_addr = inet_addr("192.16...
7,811,291
7,812,750
OpenGL Selection Buffer - Use A Pointer to the Object Instead of an Unsigned Int?
I am attempting to use the glSelectBuffer(GLsizei size, GLuint * buffer) method to select objects in a slightly different way then I believe is supported in C++ for OpenGL 3.1. Selection works great if I do everything as is specified online. Instead of a GLuint*, I would like to actually store pointers to my graphical ...
Preferably in OpenGL 3.1, but future versions are applicable as well Selection mode has been removed from OpenGL-3 core and later versions. OpenGL is meant for drawing, and selection mode uses to fall back into software mode anyway, i.e. is not HW accelerated. Just my suggestion: Don't use it.
7,811,445
7,811,490
C++ destructor memory leak
Relatively simple question about handling destructors properly... First I've got a class that's something like this: class Foo { public: ReleaseObjects() { for (std::map<size_t, Object*>::iterator iter = objects.begin(); iter != objects.end(); iter++) { delete (*iter).second; } o...
You've got to make sure that your destructor is virtual so that the proper derived destructor is called. class Object { . . . virtual ~Object() . . . };
7,811,572
11,164,121
SGI STL Rope in g++?
It seems that there is a implementation of rope in my /usr/include/c++/4.5.1/ext/rope (and ropeimpl.h). I compared it with SGI STL and the code seems to be pretty much the same codebase. I'm not aware of its status or if its functional or not. Nor i am aware if this is super old stale code, or code in progress in any c...
It's taken straight from the SGI code, and is still maintained (I changed it just the other day to fix a longstanding bug) but is only documented briefly with the deprecated extensions.
7,811,656
7,811,818
LD_PRELOAD only working for malloc, not free
I'm trying to interpose malloc/free/calloc/realloc etc with some interposers via LD_PRELOAD. In my small test, only malloc seems to be interposed, even though free is detected (see output). I'd expect the output to contain a line "NANO: free(x)" - but this line is missing. Given // compile with: gcc test.cc #include <s...
You are compiling a C++; this means that (by default) functions are name-mangled to fit the C++ ABI. Unfortunately, the functions you are trying to hook are not name-mangled, so you end up hooking the wrong (nonexistent) function. The fix is to either a) define your wrappers in a extern "C" { } block or a) make sure yo...
7,811,687
7,811,900
Can an object be considered as a variable?
I'm having some trouble keeping apart the terms class, object, variable and datatype. can a class be considered as a datatype? can an object be considered as a variable? Also, what's the technical difference?
There are two different uses of these terms: Casual use: Class: Abstract data type with methods and fields. Object: Instance of a class. Variable: Language-level name (i.e: name given by a programmer) for some piece of storage. Datatype: Type that a variable (or some unnamed piece of storage) can have. C/C++ standar...
7,811,893
7,811,919
Creating a copy constructor for a linked list
This is homework I'm working on implementing a linked list class for my C++ class, and the copy constructor has be very confusing for me. The linked list is comprised of structs called Elems: struct Elem { int pri; data info; Elem * next; }; Elem * head; info is a separate, custom ...
You have to be careful with Step 1 and part of Step 2. Step 1 should allocate a new node and use that as the head. In Step 2, the part about next = v.next, unless your intention is to make a shallow copy, is incorrect. When you copy a container such as a linked list, you probably want a deep copy, so new nodes need to ...
7,811,899
7,811,997
What is ** doing in this simple hash implemtation?
I know * defines a pointer... does ** define a pointer to a pointer? If so, why? Is a pointer to a pointer some times known as a reference? Just need clarification for the following very simple hash. Generally pointers are used to pass the location of larger structures when passng the entire contents would be too costl...
Yes, ** defines a pointer to a pointer (because the spec says so). No, I can't quite imagine anybody calling that a reference. As to why they're using it in this case, they're writing (very C-like) code to dynamically allocate an array of pointers to X. This code: hash_entry **table; [ ... ] hash_map() { table...
7,811,918
7,811,947
Simple Inheritance Gets Vtable Error
So I am trying to compile this simple code: // In Test.h #include <iostream> using namespace std; class A{ public: virtual string f (string&); }; class B : public A{ public: B (string); string f (string&); }; // In Test.cpp #include <iostream> #include "Test.h" using namespace std; B :: B (string row...
I think you either have to make A::f(string&) abstract by writing = 0 at the end of the declaration, or actually provide an implementation of A::f Since currently the virtual function A::f does not exist, the compiler cannot create a vtable for it (the virtual function table).
7,812,009
7,812,554
error compiling boost
I am trying to compile Boost 1.47 for x86 Windows CE using Visual Studio 2008 and STLPort 5.2.1. I can successfully compile for x86 Windows and ARMV4I Windows Mobile 6.5. When I run bjam, I get this error in most every module: stlport\ctype.h(42) : fatal error C1083: Cannot open include file: '../1/ctype.h': No such f...
You have X86 macro defined (either by one of the earlier-included headers, or from a command line) and set to 1, so it gets expanded, like macros tend to do. #undef X86 will get rid of it.
7,812,057
7,826,263
const char to SQLCHAR error
The SELECT statement is a const char and "query" has to be a SQLCHAR* I've tried reinterpreting the cast but that doesn't seem to work. The code runs, even with this error, but I would like to get rid of the error. The line: SQLCHAR* query = "SELECT tblIP.[IPAddress], tblIP.[IPStatus], tblIP.[IPType] FROM tblIP ORDER...
SQLCHAR* query = (SQLCHAR *)"SELECT tblIP.[IPAddress], tblIP.[IPStatus], tblIP.[IPType] FROM tblIP ORDER BY tblIP.[IPAddress] ASC;";
7,812,083
7,813,514
Developing QT applications in Xcode?
My IDE of choice for the Mac (at least for C++ and Objective-C development) is Xcode. I have a 64-bit Intel Mac with OS X Lion installed, and Xcode version 4.2 downloaded from the Mac App Store. My problem is that Qt is apparently not compatible with Xcode 4 (it crashes when launching projects generated by qmake), so I...
Google shows up many pages, but this Qt4 with Xcode page appeared at first glance to be a fairly definitive resource. However, it was last changed in 2006. Please check out: http://qt-project.org/doc/qt-5/macosx.html There is a much more recent Qt Developer Network forum post that seems to have good info in it. Specif...
7,812,105
7,812,185
enumerations in C from a c++ perspective
I am a C++ programmer and I rarely have to deal with GCC "C". I am currently converting some code from C++ to C for use with the GCC compiler. In C++ I would use the following source code. Note that I would use a class for scope. C++ Source class Card { public: enum Suit { Diamonds, Hearts, Clubs, Spades ...
Do it just like the old days: enum Suit { ST_Diamonds, ST_Hearts, ST_Clubs, ST_Spades }; enum WeaponType { WT_Rocks, WT_Clubs, WT_Guns }; int main () { Suit a = ST_Clubs; WeaponType b = WT_Clubs; return 0; }
7,812,164
7,814,446
null pointer in opencv (QT) when running
Hello i have a Macbook pro with osx 10.7. I just installed Qt (nokia), opencv, cmake. I have never worked with any of those . So i started my first tutorial. I created a new QT Gui application. I changed my main.cpp to : #include <QtGui/QApplication> #include <opencv/cv.h> #include <opencv/highgui.h> #include "mainwin...
cat.jpg is probably not in the right directory. If you don't supply a path it searches the current directory, which is probably /Users/olivierjanssens/untitled1-build-desktop-Desktop_Qt_4_7_4_for_GCC__Qt_SDK__Debug or /Users/olivierjanssens/untitled1-build-desktop-Desktop_Qt_4_7_4_for_GCC__Qt_SDK__Debug/untitled1.app/...
7,812,178
7,812,195
How do Prefix (++x) and Postfix (x++) operations work?
Can someone tell me how prefix / postfix operators really work? I've been looking online a lot but haven't found anything. From what I can tell prefex first increments, then does the operation and then assigns. Postfix would do the operation first, then assign and then increment. But I'm having a bit of trouble with m...
In C# the operands of + are evaulated in left-to-right order. In C and C++ the order of evaluation for the operands of + is unspecifed. For C# your examples work as follows: y = x + x++; ^ x is 1 ^ x is increased to 2, but the postfix increment returns the old value (1) y = 2 y = x++ + x; ^ x b...
7,812,179
7,812,308
How does one tell when the state of a child window changes in WTL?
I've written a simple GUI using WTL: I've got everything figured out as far as setting up the window is concerned, and also wired up the menus and such to call whatever I wish. But I need to know when, for example, someone checks one of the checkboxes in the list view, or when someone clicks on a button. Do these chil...
Child notifications are typically sent to the parent window in the form of WM_NOTIFY or WM_COMMAND messages. Some child notifications are common across most control types (e.g. NM_CLICK and NM_CUSTOMDRAW), but in general you'll need to look at the notifications reference for each control type on MSDN to see what's avai...
7,812,370
7,812,452
std::out_of_range thrown when parsing a text file
I have the following code to read a text file. const string FILENAME = PACKAGES_DIR + pname; //the arguments to ifstream is a cstring and hence the conversion must be made ifstream freader; freader.open(FILENAME.c_str(),ios::in); if(freader.is_open()) { while(freader.good()) { string line; ...
Problem 1 while .good or while !.eof is almost always wrong. Throw away whatever book told you to do that, and do this instead. In this case, the changed code looks a bit like this: const string FILENAME = PACKAGES_DIR + pname; //the arguments to ifstream is a cstring and hence the conversion must be made ifstream frea...
7,812,566
7,812,587
Why no variable size array in stack?
I don't really understand why I can't have a variable size array on the stack, so something like foo(int n) { int a[n]; } As I understand the stack(-segment) of part of the data-segment and thus it is not of "constant size".
Variable Length Arrays(VLA) are not allowed in C++ as per the C++ standard. Many compilers including gcc support them as a compiler extension, but it is important to note that any code that uses such an extension is non portable. C++ provides std::vector for implementing a similar functionality as VLA. There was a p...
7,812,660
7,995,816
gSOAP WSSE Header missing xmlns namespace declarations
I have a problem generating a gSOAP security header (WSSE). I have compiled all the necessary file and used the following calls to add the WSSE security header to the request: soap_wsse_add_Security(proxy.soap); soap_wsse_add_UsernameTokenText(proxy.soap, "UsernameToken-1", "user","passwd"); My security header comes o...
Just answering the question to close it. What you need to do is to edit the *.nsmap file. There you can add your namespace definitions in the struct for example: SOAP_NMAC struct Namespace ZamtelWSZambia_namespaces[] = { {"wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-ecext-1.0.xsd", NU...
7,812,801
7,814,875
Implementing lua callbacks for a menu system
In our menu system, we define menus in xml with lua chunks used for callbacks for menu component events. Currently, everytime a script callback is called, we call lua_loadstring which is quite slow. I'm trying to make it so this only happens once, when the menu is loaded. My initial thought was to maintain a lua table...
If you want to put the function in a table, then put the function in the table. It seems that your Lua-stack-fu is not strong; consider studying the manual a bit more closely. Anyway, I'd say the biggest problem you have is your insistence on params. Callback functions should expect to be varadic; they take ... as thei...
7,812,824
9,872,836
Safe to perform Word automation on open document?
I'm looking to perform Microsoft Word automation -- straightforward stuff such as instructing Word to open a document and save it as an RTF file. But what happens if the user already has the document open in a running instance of Word? Can I still safely perform automation actions (that don't modify the document itself...
There are lot of problems in doing this. First of all Microsoft doesnt recommend to use Word for automation. use OpenXML instead. In my experience every day I ended up investigation Com exceptions by automating Word in Server. http://support.microsoft.com/kb/257757 Even if you attempt to take the risk by automating, I...
7,812,914
7,813,195
Using an array and moving duplicates to end
I got this question at an interview and at the end was told there was a more efficient way to do this but have still not been able to figure it out. You are passing into a function an array of integers and an integer for size of array. In the array you have a lot of numbers, some that repeat for example 1,7,4,8,2,6,8...
In what follows: arr is the input array; seen is a hash set of numbers already encountered; l is the index where the next unique element will be placed; r is the index of the next element to be considered. Since you're not looking for code, here is a pseudo-code solution (which happens to be valid Python): arr = [1,7...
7,812,959
7,813,151
using templates with vectors and vector functions
I am attempting to template a vector. In my main I have the following: std::vector<Word> concordance = push_vector(data); Where Word is a struct containing a std::string and an int, and data is a std::string. In my header file I have: template <typename T> std::vector<T> push_vector(std::string&); However when I co...
If I understand what you actually want to do perhaps something more like this: template <typename T> void push_vector(const std::string& str, std::vector<T>& vec) { // convert str to T if possible // throw on failure maybe? // assign vec with converted data } Then call it like so: std::string data("Hello"); s...
7,813,276
7,813,698
How does the recursive part of quick_sort work?
Here is an implementation of quick_sort found in many places including wikipedia. Here is my simple synopsis. Select a pivot element – ½ of left and right. Start index at right and iterate left. If Elements[right] < P pick as flip. Start index at left and Iterate right. If Elements[left] > P pick as a flip. Fl...
If you start with an array: [74, 32, 39, 15, 25, 82, 23, 2, 97, 62, 95, 34, 92, 84, 28] it selects the element in the middle (23), and partitions: [15 2 ] 23 [ 32 74 32 39 25 82 97 62 95 34 92 84 28] Note the list is not sorted. Since there's more than one on the left, it calls itself to sort the left partition....
7,813,376
7,825,243
Rotate cv::Mat using cv::warpAffine offsets destination image
I'm trying to rotate a 1296x968 image by 90 degrees using the C++ API of OpenCV and I'm facing a few problems. Input: Rotated: As you can see, the rotated image has a few problems. First, it has the same size of the original, even though I specifically create the destination Mat with the inverted size of the original...
I've found a solution that doesn't involve warpAffine(). But before that, I need to state (for future references) that my suspicion was right, you needed to pass the size of the destination when calling warpAffine(): warpAffine(image, rotated_img, rot_matrix, rotated_img.size()); As far as I can tell, the black border...
7,813,728
7,813,789
Pointer vs. reference return types
i'm trying to come up with a concrete reasoning why to use a pointer over a reference as a return type from a function , my reasoning is that if inadvertently a null value is returned to a reference type it could not be checked , and could lead to run-time errors int& something(int j) { int* p = 0 ; ...
You could use a pointer instead of a reference if: Null is a valid return value You dynamically constructed something in the function, and the recipient becomes the owner. (In this case, you might consider returning a smart pointer such as std::unique_ptr or boost::shared_ptr.) Regardless, you would not want to retur...
7,813,902
7,813,932
A good C++ programming enviornment for Mac OS X
I have tried Xcode, textwrangler and Qt. I like textwrangler the best but it doesn't support C++, i.e. compiling, and checking syntax. Can you please recommend a good editor for me? I didn't like Xcode because it guesses what function you are typing and it's not helping me learn the syntax.
I think you probably need to separate learning the language from learning a tool. XCode is probably the best integrated development environment for the Mac and you will come to appreciate its autocompletion feature as it saves you a lot of typing! If you really don't want it (and I suggest that you do!) then you can tu...
7,814,131
7,814,206
C++ Command Line: Output program variable value
I am writing a drop-down console for my app. Suppose I want to output the value of variable myvar by using the following command: ]/get myvar Is there a better way than to create a map so that the output is return mymap[argv[0]]; ? In other words, can I associate the input char array "myvar" to the variable named my...
Short answer: No. Long answer: Pfff, no way! After your piece of code is build as a binary, there is no such thing as a variable name. Just some pointers, values on the stack, and so on... If you want to implement something like this, I would recommend you to go for a scripting library (Lua, for example), and manually ...
7,814,209
7,815,152
Parsing Text to Make a Tree Data Structure
Let's say I'm reading a line from a file: {Parent{{ChildA}{ChildB}}} More complex example: {Parent{{ChildA{ChildC}{ChildD}}{ChildB{ChildE}{ChildF}}}} Which is the grammar used to construct a tree. Any name inside {} brackets is a node, and if within that bracket there are other nodes (brackets), those nodes are child...
Spoiling the fun with an answer you can't use anyway if it's homework: A minimal implementation with Boost Spirit Qi: #include <boost/spirit/include/qi.hpp> namespace qi = boost::spirit::qi; typedef boost::make_recursive_variant< std::vector<boost::recursive_variant_>, std::string>::type ast_t; void dump(con...
7,814,305
7,814,665
stringstream operator selection issues
I have a class constructor like so: DotDashLogMatcher( std::stringstream const& pattern ); I call it like so: std::stringstream s; DotDashLogMatcher( s << "test" ); This is an over-simplified example, but that is essentially what is going on. Here is the exact compiler error I'm getting. Note that for some reason the...
operator<< does not return a std::stringstream because it is inherited from std::ostream. See: http://www.cplusplus.com/reference/iostream/stringstream/ You may use: DotDashLogMatcher( s ); Or you may change your method declaration in order to match the return type.
7,814,313
7,814,534
unordered_set: is pointer address a good hash?
i want to store a set of (smart) pointers in a hash set, either <boost/unordered_set>. After 10 seconds of thought, i came up with this hash function: typedef boost::shared_ptr<myType> ref_t; struct SharedPtrHash : public std::unary_function<ref_t, std::size_t> { std::size_t operator()(ref_t...
If you want to detect objects that are not identical even though their contents might be equal, you have no choice but to use the address of the object in the hash. The only question is whether to use the address directly or to run it through a formula. Dividing by sizeof(mytype) would tighten up the holes in the distr...
7,814,330
7,814,414
How can I use Unicode mappings
I found all the nice mappings from various systems to the according Unicode code points. They are listed in a clear format, which would for sure be easy to parse. But since I don't want to reinvent the wheel is there a C/C++ library using these files to map char arrays from any of those encodings to Unicode? I only fou...
iconv -l lists ISO-8859-8, codepage 862, and MacHebrew on OS X Lion. Maybe they're just not enabled in your OS or it's using an old version of iconv.
7,814,359
7,814,387
Confusion about nested loops and array access
I have some C++ I'm trying to port, and I'm confused about a couple lines and what exactly they're doing. The code is as follows. The variable im is a 2D float array of size num_rows by num_cols. for(x=0; x < num_cols; x++){ float *im_x_cp = im[1]+x; //(1) for(y = 1; y < num_rows; y++, im_x_cp+=num_cols){ f...
im[1] is a pointer to an array of floats, that is, it's the second line/column of your matrix. im[1] + x is a pointer to the element at coordinate (1,x) (recall how pointer arithmetic works) and s1 is its value.
7,814,723
7,814,793
In what way is ::operator new[]() different than ::operator new()?
I need to construct an array of objects from a previously allocated block of memory. However, I cannot understand in what way ::operator new[]() is different from ::operator new() from the user point of view when allocating that block, since both require the size of the block. In the following example, using either one...
You're misusing the new. The point of using new [] is that it calls the constructor for each and every element of the array being allocated. delete[] does the same for the destructors. You're using placement new and manually calling the constructors and destructors, missing the whole point.
7,814,750
7,814,775
inheritance, calling overloaded method from base method
I have two classes: class A { int get(); string str(); } string A::str() { return string_with( get() ); } class B : public A{ int get(); } if I do: A a B b b.str() b will invoke A::str() (good) and it ill use A::get() method (bad!). I want, that when I invoke b.str(), the B::get() is used by str. Ho...
Just make it virtual. That's exactly what virtual is for. Write virtual int get(); in A's definition. And, just to make the code more understandable, do the same in B's. By the way, I'm assuming that you meant to write class B : public A.
7,814,868
7,814,881
Library path for C++. Fail?
Im trying to execute this code on a mac. I have installed the curl. When i search for curl, i can find it under /usr/include/curl/curl.h. Below is the program i want to run. Taken from here. #include <iostream> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl)...
You’ve forgotten to link the libcurl library: g++ simple.cpp -lcurl A header file such as <curl/curl.h> (typically) only declares that a group of functions exist but does not contain the actual functions. In the case of curl on OS X Lion, those functions are in libcurl (/usr/lib/libcurl.dylib, which points to /usr/lib...
7,814,915
7,814,958
Creating an Object Based on a Function Arguement C++
Say I have a member function that creates a new object and places it into a data structure (in this case a map) in the class: Class A { std::map<std::pair<int,int>, BaseClass*> store; //... public: void createObject(?a?) { BaseClass* temp = new ?a?; //place in map... }; }; Whe...
Use a member function template. In the context of your example: template<class T> void createObject() { BaseClass* temp = new T(); //place in map... }; Invoke with: a.createObject<B>(); Where a is an instance of A, and B is a type derived from BaseClass.
7,815,216
7,815,505
C++ getline and gcount
Suppose I have an std::istream pointing to the following contents (the line break is a '\n' character): 12345678 9 and run the following code: std::istream & is = ... char buff[9]; is.getline(buff, 9); int n = is.gcount(); Now n == 8 and strcmp(buff, "12345678") == 0. The question is, how do I know that I read the en...
The key to your answer is in your question is.getline(buff, 9); int n = is.gcount(); Now n == 8 According to the reference for getline, it will extract up to n - 1 characters -- in your case, up to 8. This is slightly misleading, because if the nth character is the delimiter, it will also be extracted (but not copied...
7,815,435
7,815,504
Casting/converting from size_t to uint8_t in C++?
I'm trying to write some code that uses boost::asio's sockets to send a message from one end (the client) to another (the server). My particular goal right now is to prepend every message being sent with a 1-byte unsigned integer (uint8_t) telling the receiver how many bytes long the rest of the message is. Note that t...
The value being assigned to your little (uint8_t) variable is not a printable ASCII character code that would display like '6'. Instead, it is a binary value, which is equivalent to coding '\006' in your source code. If your data transfer protocol does work with binary code bytes, you're probably good to go. What do...
7,815,487
7,815,502
C++ Overloading Output Operator
I have a header file that looks like this: #pragma once //C++ Output Streams #include <iostream> namespace microtask { namespace log { /** * Severity level. */ enum severity { debug, info, warning, error, cri...
In your .cpp file, don't say using, but instead declare the proper namespace: namespace microtask { namespace log { ::std::ostream & operator<<(::std::ostream& out, const severity& level) { // ... } } } In fact, don't say using casually at all if you can help it. In my o...
7,815,975
7,815,996
Why is this declaration of a custom class not acceptable?
In my code I want to declare an instance of my custom class like this: MyClass anInstance; if(something){ anInstance = MyClass("instantiated like this"); }else{ anInstance = MyClass("not instantiated like that"); } //use my anInstance object ... My IDE is flagging the first line where I declare anIns...
MyClass probably lacks a default constructor. If so, you need to initialize it when you declare it. Something like this: MyClass anInstance(something ? "instantiated like this" : "not instantiated like that");
7,816,244
7,816,258
Why do my division results appear to be off?
I cannot understand why the results of my division appear rounded down? #include <iostream> #include <stdio.h> using namespace std; int rVote, oVote, dVote; int rTotal, oTotal, dTotal, total; int rPercent, dPercent, oPercent; bool loop(char vote){ switch(toupper(vote)){ case 'D': ...
It's because you're doing integer division. Integer division in C/C++ rounds down. So your following code: rPercent = ((rTotal/total)*100); dPercent = ((dTotal/total)*100); oPercent = ((oTotal/total)*100); is all rounding down to 0. To fix this, you should cast to a floating-point type: rPercent = (int...
7,816,267
7,818,860
How to structure C++ Windows API programs like C# WinForms
I'm an experienced GUI C# programmer and have some experience with C/C++ for CLI only. I'm teaching myself native Windows API using C++. I am able to create windows with buttons and input fields, etc; perform actions when buttons are clicked and text is typed, etc. However, everything I've done so far has been in a sin...
I have used my own Window class similar to what's shown below. This is a reply I poseted for a different question but you might find this useful. So here it is: #pragma once #include <windows.h> #include <process.h> #include <iostream> using namespace std; static const char *g_AppName = "Test"; class CMyWindow { ...
7,816,269
7,825,645
STL List - Datatype as a pointer object
I'm having a problem using inheritance and the STL list library... Say, I have an abstract base class with two derived classes (where all comparison operators are defined). The list is declared as list<StoreItem*> items; I'm inserting a derived class (of the abstract base class, StoreItem) called either Food or Cloth...
You are assuming that the item you are pulling from the list is a Food instance; however, the compiler doesn't know that. When you construct a new instance of Food from an item in the list (an item with apparent type StoreItem), you are trying to call Food::Food(const StoreItem) or something compatible. Why? Because ...
7,816,406
7,816,450
C++ using std::set and getting a segmentation fault D:
I have no clue what my error report in valgrind is telling me... but here are the parts of my code pertinent to the issue: template<typename T> struct CompareEvents { public: bool operator()(const T a, const T b) const { return a.time < b.time ? true : false; } }; class EventManager { public: voi...
Without seeing more info, here's a guess! I would guess that the EventManager you're calling SendEvent on is NULL. The valgrind error is telling you that 0x10 is an address that valgrind has no clue about, and 0x10 is a nice round number, possibly a 16-byte offset into a structure (EventManager), but your pointer was N...
7,816,409
7,817,333
What is the difference between ATL and WTL?
I know "WTL builds on ATL", but what does that mean in practical terms? Is ATL a subset of WTL in terms of features? (i.e. are ALL features in ATL also present in WTL?) I notice Wikipedia states ATL's development status is "current" whereas WTL's most recent release is from mid-2009. Does that mean if I want to write W...
ATL is the Microsoft C++ library which primarily implements COM base. A part of it also targets ActiveX controls (which is definitely not a primary goal of the whole library) and it also covers related stuff such as thin wrapper of HWND (CWindow class), string manipulation classes CString, CStringA, CStringW, ANSI/Unic...
7,816,473
7,816,619
How to avoid code duplication in this example?
I have two classes, Base and Derived. I provide a function that applies a function to all elements of Base, and another function to apply a function to all elements of Derived: #include <iostream> #include <vector> class Base { typedef std::vector<int> Vec; typedef Vec::const_iterator CIter; CIter begin() const;...
Assuming the const Base& vs. Derived* difference is an error, yes, you need a function template to call the functor with the correct argument type: template <typename Collection, typename F> void processCollection (Collection& col, F& f) { for (typename Collection::CIter i=col.begin(); i!=col.end(); ++i) { ...
7,816,565
7,818,029
Trouble With Smooth Animation In C++/SDL/OpenGL
I been working in the animation of a 2D platformer game in C++/SDL/OpenGL, and my team and I reach the point where we need to establish that every animation of the player (Walking, Running, etc..) needs a different framerate for our concept, but I use as a guideline the Game Programming All In One as a example for the...
At first look Animation::animate doesn't look right. Let me explain: Assuming you have a fixed display frame rate (for a sprite based game this will hold), you want a linear mapping from frame counter to sprite frame. If you graph this, this was a line. And in this case one over a discrete sampling grid. Whenever one t...
7,816,618
7,820,994
Suggestions for Creating an Image for Each Word in a Text
I am looking for a way to automatically create an image rendering for each word in a text file (I am working on an "easy" way to display a complex script on computers and cell phones that don't support the complex script). Is there an easy way to do something like this? The text will be in Khmer (UTF-8). I've alread...
Use Gtk3::WebKit to capture rendered HTML to any libcairo output target. As of 2011, this is the most modern and flexible solution. Sample rendering to PNG of the whole Khmer phrase
7,816,986
7,817,032
Using a subscript operator on a char pointer passed into a function doesn't modify the value. Why?
I've noticed that the following function: void myFunction(char *myString) { myString[0] = 'H'; } will not actually modify myString. However, this function does: void myFunction2 (char *myString) { *myString = 'H'; } It's obvious to me why myFunction2 works, though I'm not sure why myFunction does not work. Co...
No, I don't think you're right about that one. If you enter the following code: #include <iostream> void fn1 (char *s) { *s = 'a'; } void fn2 (char *s) { s[0] = 'a'; } int main (void) { char str1[] = "hello"; char str2[] = "goodbye"; fn1 (str1); std::cout << str1 << std::endl; fn2 (str2); std::cout <...
7,817,161
7,817,234
boost::mutex::~mutex(): Assertion `!pthread_mutex_destroy(&m)' failed
I got the captioned error in the mutex destructor. since the error may due to the mutex is in lock state during destruction, I create a new mutex class which is inherited from boost:mutex. it is to make sure the mutex is unlock during destruction. However, the same error still occurs. Any hits would be appreciated! cla...
Do Not inherit from boost::mutex, the boost::mutex class does not have a virtual destructor, so it is not actually meant for Inheritance. Possible Root Cause: The error you are getting indicates that you are calling unlock on a mutex that was never locked. Something like: boost::mutex m; m.unlock(); By trying ...
7,817,274
7,817,320
Count number of ways to make an amount with change given
I was trying to code an algorithm to count the number of different possible ways the make a certain amount with the given denominations. Assume the US dollar is available in denominations of $100, $50, $20, $10, $5, $1, $0.25, $0.10, $0.05 and $0.01. Below function, works great for int amount and int denominations /* ...
When dealing with such "small" currency amounts and not dealing with interest it will be much easier to just deal with cents and integer amounts only, not using floating point. So just change your formula to use cents rather than dollars and keep using integers. Then when you need to display the amounts just divide the...
7,817,275
7,817,344
C - faster locking of integer when using PThreads
I have a counter that's used by multiple threads to write to a specific element in an array. Here's what I have so far... int count = 0; pthread_mutex_t count_mutex; void *Foo() { // something = random value from I/O redirection pthread_mutex_lock(&count_mutex); count = count + 1; currentCount = count;...
You need to use interlocking. Check out the Interlocked* function on windows, or apple's OSAtomic* functions, or maybe libatomic on linux. If you have a compiler that supports C++11 well you may even be able to use std::atomic.
7,817,364
7,817,526
Are there any concurrent containers in C++11?
In particular, I am looking for a blocking queue. Is there such a thing in C++11? If not, what are my other options? I really don't want to go down to the thread level myself anymore. Way too error-prone.
According to Diego Dagum from Microsoft's Visual C++ Team: A recurrent question (well, one of the many) is about STL containers and whether they are thread safe. Taking Stephan’s words here, the reality is that they aren’t, not as a bug but as a feature: having every member function of every STL container acquiring an...
7,817,474
7,817,529
STL container performance overview
Possible Duplicate: What are the Complexity guarantees of the standard containers? From the answers to my yesterday's question std::queue<T, list<T> >::size() is slow in O(n)? I learned that my assumptions on STL container performance characteristics are not always right. Time to learn! Do you know about any "cheat ...
There is a nice chart which compares performances of all standard library containers here.
7,817,537
7,817,592
How would you go about defining undefined functions in a template?
I'm writing a C++ project and have a generic evaluate method in a class template. My only question is how would I define the generateAllMoves and isPosFinal so that it is defined inside the classes that use this class template? I've read that using pure virtual functions is a no no. I also do not want to make it static...
A good way to do just this is to use the "Curiously Recursive Template Parameter" idiom. See here for more information.
7,817,696
7,870,380
C++ STL low level programming
Is it possible to do some low level programming with STL, at least containers and algorithms? I need to do a simple OS and have to know if is feasible to try the C++ and STL or go with plain C. Any resources are accepted.Thanks. Edit--------- And how about Boost?
You should totally use the C++ STL. Even if you only work with bare pointers and arrays, the STL Algorithms will vastly clarify your thinking and programming. The genius of Alexander Stepanov's STL is that Algorithms are expressed with respect to Iterators, and Iterators are a generalization of pointers, so you can app...
7,817,704
7,877,555
opencv 2.3.* imread not working
I cant get imread to work, its same problem as this guy: OpenCV imwrite 2.2 causes exception with message "OpenCV Error: Unspecified error (could not find a writer for the specified extension)" on Windows 7 I just dont wannt use the workaround. Anyone know the problem? Using windows 7 64bit
The problem was due to mixing up debugging and release builds. If building in debug mode, the debug libs are needed. On unix this dont seem to be a problem.
7,817,943
7,818,126
Constructing a string of a specific length starting with a specific prefix
I need to construct a string of a specific length starting with a specific prefix. Is there any faster way (in terms of performance) to achieve the objective of the following piece of code? Would it be of any help to use char* here? int strLen = 15; string prefix = "1234"; // could be a number of any length less than s...
try this: std::string content(15, '9'); // start off with all 9s content.replace(0, 4, "1234"); // replace the first four characters etc.
7,818,022
7,818,991
Mapping C/C++ Data Type In C++/CLI
I have to start the development of the C++/CLI Wrapper around Existing Static C Library. I Encountered number of enums, typedefs, and structs in the C Library. Since I am new to C++/CLI I wanted to know what data type can used in C++/CLI. typedef struct _GC_DEVICE { TCHAR *ptszDevicePath; /// The human-readabl...
ref class GCDeviceWrapper { public: // operations with the GC_DEVICE instance private: GC_DEVICE device_; };
7,818,050
7,818,495
Populate global function pointers in shared library (Solaris, Sun Studio)
I am creating a small C++ wrapper shared library around a Fortran 95 library. Since the Fortran symbols contain . in the symbol name, I have to use dlsym to load the Fortran function into a C++ function pointer. Currently, I have a bunch of global function pointers in header files: // test.h extern void (*f)(int* arg);...
Where does the line f = reinterpret_cast<void(*)(int*)>(dlsym(RTLD_DEFAULT, "real_f.symbol_name_")); occur in test.cc? The pointer will be initialized when the line is executed (which of course depends on when the function which contains it is called). Or did you mean to write void (*f)(int* ) = reinterpret_cast<voi...
7,818,232
7,818,342
In C++, is not permitted to pass an object to function directly?
I know C, but I'm not good at C++. The following code will crash (In getval(), using reference as a parameter is ok). And value of *p is changed after first cout statement. It looks there is some overwriting caused by out of bound of memory. My question is why it crashed (or why its value is changed). It's 'call by val...
My question is why it crashed (or why its value is changed). This is a very common problem of shallow copy and double delete. Compiler picks up the default copy constructor and both a.p and o.p are pointing to same memory location. When both objects invoke their destructor, the delete p; statement is executed twice. ...
7,818,371
7,818,394
Printing to nowhere with ostream
I'd like to send data to nowhere, I mean that I don't want to print data in console nor in file, but I need some std::ostream object. How to do that?
I've used: std::ostream bitBucket(0); recently without problems, although it was flagged as having some potential problems if you looked at it from a certain angle (see the link below). Aside: From what I understand (and I'm not entirely sure of this), that call above eventually ends up calling basic_ios::init(0) and...
7,818,493
7,818,544
Returning a pointer to the object that an iter points to using `&*iter`
I have an iterator and I want to return a pointer to the element it is pointing to. Is this ok to do? return &*iter; It doesn't really seem like a good idea.
It is perfectly fine. But be aware that if the iterator is of a container which deallocates and reallocates memory on resizing, then the returned pointer will become invalid. For example, if the iterator is an iterator of std::vector, then iter and &*iter both become invalid if the underlying vector resizes itself. By ...
7,818,496
7,822,859
Blog software written in C or C++
Does anyone know of any blog/CMS software (similar to Wordpress, but doesn't have to be as featureful, I only need basic features) written in C or in C++? If you're about to ask "why do you need this?" - I want it for fun. I get far more enjoyment from playing with native code than with PHP and friends. I work as a PHP...
Yes, this is for example a blog running on this system. http://art-blog.no-ip.info/cppcms/blog It is written entirely in C++ using CppCMS web framework. The blog software itself is available from SVN as part of CppCMS project: https://cppcms.svn.sourceforge.net/svnroot/cppcms/blog/trunk It is used on several web si...
7,818,542
7,818,571
How to initialize wchar_t pointer variable in c++?
I like to know how to initialize and how to copy the contents of one wchar_t* variable into another wchar_t* variable. wchar_t *lfFace = new wchar_t; dc.GetTextFaceW(LF_FACESIZE,lfFace); This sample will throw runtime error.Please correct these. Thnks
Use CStringW instead. Like this: CStringW faceName; dc.GetTextFaceW(faceName);
7,818,622
7,818,690
constructing a class with a struct inside of it c++
So I have a class which holds a struct inside its private variables and inside this struct I have an array where the size of the array is only determined after the construction of the class. template <typename T> class btree { public: btree(size_t maxNodeElems); ~btree() {} private: // The details of...
You are just declaring the type, not an actual object of that type. You need to make your struct declaration public and the object private: template <typename T> class btree { public: btree(size_t maxNodeElems); ~btree() {} struct node { // <- this is just a declaration of a private inner-class ...
7,818,952
8,663,939
Reinstall of Visual Studio 2010 Professional does not install C++ headers and libraries
I have a Windows7 x64 machine (german). I had VS2008Prof, VS2010Prof and VS11 DP installed. I work mainly with VS2010. I was experimenting with the latest Qt version and tried to get html5 video running with QtWebKit. I installed some codecs and then also the Windows SDK 7.1. Suddenly the VS2010 debugger began to behav...
I resolved this issue by re-installing the complete system. Perhaps VS2010_Uninstall-RTM.ENU.exe /full /netfx may have helped, but I overlooked the /full switch.
7,819,109
7,820,081
Learning to use VBOs properly
So I've been trying to teach myself to use VBOs, in order to boost the performance of my OpenGL project and learn more advanced stuff than fixed-function rendering. But I haven't found much in the way of a decent tutorial; the best ones I've found so far are Songho's tutorials and the stuff at OpenGL.org, but I seem t...
The initial value is said to be 0; but it's supposed to be a pointer. The context (not meaning the OpenGL one) matters. If one of the gl*Pointer functions is called with no Buffer Object being bound to GL_ARRAY_BUFFER, then it is a pointer into client process address space. If a Buffer Object is bound to GL_ARRAY_BUF...
7,819,148
7,819,179
error: no match for 'operator<<' C++
I've looked at a few threads on stackoverflow before I thought of asking this question (since there has been a couple out there), but even through implementing some of the solutions, it doesn't seem to help my problem. That or I'm doing it wrong. Anyways, as it goes, the error I'm getting is: error: no match for 'oper...
Use *itr instead of itr: os << *itr; This is the desired behaviour. Now, for this to work, you have to make sure that operator<< exists for type T which is basically the type of *itr. Instead of manual loop, you could use std::copy as well: template <typename T> std::ostream& operator<<(std::ostream& os, const btree<T...
7,819,274
7,819,737
Using char ** as C# DLLImport Parameter
I am trying to use the following function from my .NET application... int mysql_library_init(int argc, char **argv, char **groups) Where the argv and groups params are passed the following... static char *server_args[] = { "this_program", /* this string is not used */ "--datadir=.", "--key_buffer_size=32M"...
Just declare the arguments as string[]. Pinvoking the MySql native interface is painful and unnecessary. Use its .NET data provider.
7,819,309
7,819,342
having to use pointers to abstract class causes difficulties
My first question here... I want to use an abstract class A from which i derive a class B (and classes B2, B3, ...). I understood that in order to handle them uniformly, I have to use pointers to the base class, so here variables of type A*. In the example below, I want to fill aa which is of type vector<A*> in functio...
B b(var); aa.push_back(&b); It is pushing the address of the local variable. That is the cause of the problem, because the local variable gets destroyed on returning from the functon, but aa still contains the pointer to the non-existing object. Such a pointer is called dangling pointer using which invokes undefined b...
7,819,404
7,819,420
How to represent sqrt(-1) in programming?
I want to represent sqrt(-1) in C++, because I am trying to implement an FFT algorithm. Is there a good way of representing this?
I guess you're looking for #include <complex> e.g.: std::complex<double> num(0,1); You can actually use std::sqrt with this complex type to compute sqrt(-1): #include <complex> #include <iostream> int main() { const std::complex<double> result = std::sqrt(std::complex<double>(-1,0)); std::cout << result << std::e...
7,819,546
7,819,703
inputting & displaying of values
Below are the list of my codes. Please kindly take a look. Option 1 is inputting of values. Whereas Option 5 is displaying of values. The problem with my program is. I dont have a problem inputting and displaying 1 set of values, it displays normally. When i input 2 set of values for example like.. (1, 1, Type O, 1, 1...
It's simple: if (OptionChosen == 1) { //declarations int i=0; You are resetting i to zero every time you select option 1. You will be better off fully constructing point2d before adding to the point2dVector collection: PointTwoD point2D = PointTwoD(x,y,locData, civIndex=0); point2D.setxCOORD(x); point2D.setyCOORD(...
7,819,747
7,819,930
Reading text file per line in C++, with unknown line length
I have a text file, that is formatted somewhat like this: 1 3 4 5 6 6 7 8 4 12 16 17 18 19 20 20 0 A line can contain 1 to 10000 integers. What I need to do, is read all of them line by line. Pseudocode like this: line=0; i=0; while(!file.eof()){ while(!endLine){ array[0][i++]=file.readChar(); } line++;i=0; } So,...
Probably something like this: after reading an int, I manually skip spaces, tabs, carriage return and end of line (for this one you'll have to implement your logic). To read an int I read it directly using the C++ functions of ifstream. I don't read it character by character and then recompose it as a string :-) Note t...
7,819,813
7,819,869
passing arrays (&) to functions c++, runtime error
#include <iostream> #include <cmath> using namespace std; void input(int(&x)[10]); int copy(int (&x)[10], int(&y)[10]); void read(int(&x)[10], int b); int main() { int m[10], v[10], c; input((&m)[10]); read((&m)[10], 10); c = copy((&m)[10], (&v)[10]); read((&v)[c],c); system("PAUSE"); re...
The syntax of passing an array is not correct (though it compiles). It should be as simple as, input(m); read(m, 10); c = copy(m, v); read(v, c); int(&x)[10] should be used for the function prototype where you are receiving an array of size 10 by reference. While calling the function simply pass the name of the variab...
7,819,835
7,819,882
Delete dynamically allocated memory form std::map
I have a map std::map< string,A* > MyMap, here A is a class; its object is created created using "new" and inserted into map like this, MyMap["first"] = new A(); MyMap["second"] = new A(); // second step MyMap["third"] = new A(); Like this, I am inserting dynamically created A object into array with in every 5 sec...
Definitely. First, obtain a pointer or reference to the object you want to remove. Then, take it out of the map using map.erase(). Now, the object is held only the your pointer or reference, so you can free up its memory using delete.
7,820,145
7,820,308
Direct vs uniform initialization in std::allocator
This question has also been submitted to Usenet, where it is more appropriate, but this is a larger and more reliable forum. std::allocator::construct is defined to forward its argument parameter pack to object construction using parentheses, a.k.a. direct-initialization. If it used braces, a.k.a. uniform initializat...
I don't know what the SC considered, but keep in mind that uniform initialization doesn't really 'work' in generic contexts (barring value construction*). Consider this attempt: template<typename T, typename... Args> T make(Args&&... args) { return T { std::forward<Args>(args)... }; } You get: assert( make<std::ve...
7,820,364
7,820,536
which is the Memory efficient way to pass the string as argument to a function.?
can any one tell me .Is there any benefit of passing string as func(string& ) instead of func( string).
Passing an object by reference means, well, that you're passing the reference by value, instead of passing the object by value, which means that you have to made a copy at function invocation. However, passing-by-reference introduces a new set of questions which you must be aware of: does the function modifies or not ...
7,820,429
7,820,468
Lifetime of return value in comma separated statements
Is the order of execution of the three commented lines below guaranteed? struct S { S() { /* called 1st */ } ~S() { /* called 3rd */ } }; boost::shared_ptr<S> f() { return boost::shared_ptr<S>(new S); } int second() { return 0; /* called 2nd */ } int test() { return (f(), second()); } With my comp...
Yes. Temporaries persist until the completion of the full-expression. [n3290: 12.2/3]: When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called fo...
7,820,516
8,156,751
Usage-based Licensing framework
I am just trying to look at different licensing models and potential technical C++ implementations. Suppose you have a desktop application including several algorithms (A1, A2, A3). This application is communicating with some server (potentially in the cloud). These "local" algos may be used independently. Is there any...
Though your Pricing model is feasible for large scale and probably same as what cloud offers. I don't think any native application would be scalable/feasible with this model. Most of the License of software's that are too costly to buy for each user, they give a floater license and a cap limit of number of simultaneous...