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
3,877,180
3,877,482
Call function after certain time has elapsed
I'm making a GUI API (for games, not an OS) and would like to implement animated buttons. I'd like to be able to create timed events, but, within the class. example: class TextBox { void changeColor(int color); void createTimedEvent(func* or something, int ticks); void animate() { createTimedEvent(cha...
I believe you could make this work portably using Boost.Asio - this is primarily designed for async I/O but I see no reason why the timer code cannot be used in other contexts. See this example for how to kick off a timer which calls back your code after expiry. The only proviso I noticed is that you have to call io...
3,877,368
3,877,390
default d'tor, copy c'tor, operator=
let's assume I have some class A: header class A{ int x; int value() {return x}; }; main A a; cout << a.value(); my question is: will my compiler produce d'tor copy c'tor and operator= for me or not (cause it actually doesn't need it) EDITED does it write d'tor for me at all, cause it seems to be useless, may you giv...
In principle, yes for the ctor and dtor, which are "used". No for the operator=: the default functions are only generated if used, which is quite important since for some classes the default operator= "wouldn't work", so it's not available. In practice, the auto-generated ctor and dtor of this class do nothing. A comp...
3,877,377
3,877,412
in C++ how can I pass a static array to an object as a parameter, and modify the original array in there?
The array has to be on the stack, and I need to modify the elements. Here is what I have: Class Me { private: int *_array; void run(){ for (int i = 0 ; i < 10; ++i) { _array[i] += 100; } } public: Me(int array[]) { _array = array; } }; This is main: int a...
When I fix your code so that it actually compiles, I get the output 100 101 102 103 104 105 106 107 108 109 Is this not what you expected?
3,877,495
3,877,516
Will a function pointer be NULL by default?
In the class below, would this mean that onPaintCallback is NULL, or must I make it NULL in the class constructor? I want to start checking for NULL before it is given a valid pointer. class AguiWidgetBase { virtual void onPaint(); void (*onPaintCallback)(AguiRectangle clientRect) = 0; public: AguiWidgetBas...
What you have isn't legal. You have to initialize it in the constructor: AguiWidgetBase::AguiWidgetBase() : onPaintCallback(0) {} You could use boost::function<void(AguiRectangle)>, which aside from being more flexible, initializes itself correctly to null. You can check it like: if (f) // ...
3,877,514
3,877,860
Difference between QSharedPointer and QSharedDataPointer?
What is the difference between these two types of pointers? As far as I can read, QSharedPointer can handle situation well, so what is the need for QSharedDataPointer?
From Qt documentation QSharedDataPointer The QSharedDataPointer class represents a pointer to an implicitly shared object. QSharedDataPointer makes writing your own implicitly shared classes easy. QSharedDataPointer implements thread-safe reference counting, ensuring that adding QSharedDataPointers to...
3,877,613
3,877,636
Self destructing objects
Just wondering whether an object can self-destruct. Consider this situation. An object that extends a thread object. Session : Thread { Session() {} ~Session() {} ThreadMain() { while(!done){ /* do stuff ... */ ... // something sets done = true; } ~Client(); } }; void ...
you can do "delete this" when the session loop exits but see https://isocpp.org/wiki/faq/freestore-mgmt
3,877,640
3,877,730
how to send key's to any application that is currently running from background program (c++)
my question is how to send some key's to any application from application that is running in background? Let's say that I made shortcut to LEFT ARROW key which is ALT+S, and than I want whenever I'm in any application and when I press ALT+S that background application response that shortcut and send to currently opened...
I strongly encourage you to use RegisterHotKey instead of GetAsyncKeyState. That way you won't need a loop nor a Timer, thus making your application more reliable and responsive. To simulate the keypresses to another application/window, you need to: A) Focus the specific window: BringWindowToTop(hwnd); SetForegroundWin...
3,877,714
3,877,724
C++ - Big-O Notation
For some reason im unable to solve this. what will be the Big-o Notation for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { c[i][j] = 0; for (int k = 0; k < n; k++) c[i][j] += a[i][k] * b[k][j]; }
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { c[i][j] = 0; for (int k = 0; k < n; k++) c[i][j] += a[i][k] * b[k][j]; } It looks like it's O(n^3) because it has 3-level loops.
3,877,856
3,877,874
Passing a object by reference in c++
This is a noobie question, but I'm not sure how to pass by reference in C++. I have the following class which sets up a Node and a few functions. class Node { public: Node *next; int data; Node(int dat) { next = NULL; data = dat; } Node* getNext() { return next; } void setN...
C++ has support for reference semantics. Therefore, for a given function: void foo(Bar& bar); To pass by reference you do: int main() { Bar whatsit; foo(whatsit); return 0; } That's it! This is commonly confused with passing a pointer, where for a function such as: void foo(Bar* bar); You would do: int main(...
3,877,862
3,877,884
Will function pointers always initialize to NULL?
I'm using MSVC and it seems like the code below does not crash and the function pointer is initialized to NULL by the compiler. int (*operate)(int a, int b); int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int main() { if(operate) //would crash here if not NULL {...
operate is initialised to NULL because it is a global variable, not because it is a function pointer. All objects with static storage duration (which includes global variables, file-level static variables and static variables in functions) are initialised to 0 or NULL if no initialiser is given. [EDIT in response to J...
3,877,958
3,878,001
Resource conflict on ON_UPDATE_COMMAND_UI
I have an EXE class which contains a button resource with ID EXE_BUTTON_RESOURCE ON_UPDATE_COMMAND_UI(EXE_BUTTON_RESOURCE, OnUpdateExeButtonResource) void EXE::OnUpdateExeButtonResource(CCmdUI* pCmdUI) { pCmdUI->Enable(exe_flag); } This EXE application will load another DLL class. DLL class is having a menu ...
Check this for a cool tool: http://www.codeproject.com/KB/macros/resorg.aspx- Another useful post: MFC resource.h command/message IDs
3,878,033
3,878,144
What am I missing? GetLine function (C++)
string GetLine() { char parameter[26] = {NULL}; inFile.getline (parameter,26,' '); return parameter; } Now an example of my input file looks like this: ~in.txt~ BAC BCA(space after the last A) ~End File~ I have to have that space after the A or else my function to get line won't work. Is there a way to not have a sp...
This is kind of a silly redundant function, and I don't know why you would call it "GetLine", but here ya go: string GetLine() { string s; infile >> s; return s; }
3,878,066
3,878,198
Character by Character Input from a file, in C++
Is there any way to get input from a file one number at a time? For example I want to store the following integer in an vector of integers since it is so long and can't be held by even a long long int. 12345678901234567900 So how can I read this number from a file so that I can: vector<int> numbers; number.push_back(/...
This could be done in a variety of ways, all of them boiling down to converting each char '0'..'9' to the corresponding integer 0..9. Here's how it can be done with a single function call: #include <string> #include <iostream> #include <vector> #include <iterator> #include <functional> #include <algorithm> int main() {...
3,878,083
3,878,092
c++ fraction class. overloading operators?
I am making a fraction class for a school project, and my brain is frying. I was told to overload the << and >> operators through the friend keyword. But I'm getting errors for this. I've posted the relevant code here: http://pastebin.com/NgCABGJ2 The errors include: error C2270: '<<' : modifiers not allowed on nonmemb...
Sounds like you tried to declare friend ostream &operator<<(…) const; . The important thing about friends is that they are not members. A friend function exists outside the scope of the class, even if it is defined inside the class {} block. In other words, you are declaring a function ::operator<<(), not fraction::ope...
3,878,106
3,878,123
C++ cout fresh array gibberish
When I "cout" an empty array, I get gibberish. Why? int main() { char test[10]; cout << test; return 0; } ...returns some unicode blather. An easy answer I'm sure.
Since you didn't initialize the array you got a garbage value (test[0] is what you are printing out). Initialize it: int main() { char test[10] = {}; cout << test; return 0; } Just like to note: Just because some compilers initialize stuff (like some compilers initialize ints, floats etc., at 0) it is not...
3,878,185
3,878,201
When to use QThread::exec()
I've checked a satisfying explanation but could not find. Usually docs mention that in order to use signals/slots between threads, we need to use event loops and start them by calling exec. However I can see that w/o using exec(), I can still send signals and handle them across threads. What's the exact use of it?
Use QThread::exec() when you want to run the event loop Qt provides for you in the QThread class. If you don't call exec(), you need to create your own event loop that processes Qt events (that is, if you want signals / slots to work). This is almost certainly more work than it's worth, unless you have very specific ne...
3,878,259
3,884,084
Simple C++ project issue with XCode
I am setting up a C++ project in XCode and it seems to not recognize my classes. By default, there is a main.cpp file in the source folder. I added a Node.cpp and Node.h file to this folder, and included the Node.h in my main.cpp file. Unfortunately, it's not recognizing it, it says No such file or directory. Why...
How did you include the Node.h in your main.cpp? #include <Node.h> will not work, you have to use #include "Node.h"
3,878,303
3,878,908
C++ UDP Socket port multiplexing
How can I create a client UDP socket in C++ so that it can listen on a port which is being listened to by another application? In other words, how can I apply port multiplexing in C++?
I want to listen on only one port You can do that with a sniffer. Just ignore the packets from different ports. I might need to stop it from sending out some particular packets, because my program will send it instead of the original application Okay, here I suggest you to discard sniffers, and use a MITM technique...
3,878,396
3,881,430
why does directx 9 lack of resources? c++
directx 9 is most library i have found that doesn't have any free tutorials or resources. why is that?
You have a pretty extensive tutorial by Microsoft at MSDN. Check it out here Or you can go to the Direct X Development Center
3,878,456
3,879,062
Determine the Internal Path Length of a Tree (C++)
Well I'm down to the last function of my program and I'm done. I've hit another stump that I can't seem to fix on my own. int Tree::InternalPathLength(Node * r, int value) { if(r->left == NULL && r->right == NULL) { return 0; } return value + InternalPathLength(r->left, value+1) + Inter...
if(r == NULL) { return 0; } return (value+InternalPathLength(r->right,value+1)+InternalPathLength(r->left,value+1)); I finally got it! Thanks for your help though!
3,878,511
3,878,534
Basic stucture of a C/C++ project (header files and cpp files)
This is a brain-dead newbie question, but here goes: What determines what files get included in a C/C++ project? My understanding is that the compiler starts with the file that has main() in it and that file will contain #include's to get various h files which contain #include's to other h files and so on until everyth...
Think of files as just an easy way to split up your code to make it both more reusable and more maintainable. You can just as easily put an entire application in one big honking source file but you may find that the file will get rather big, leading to the compiler complaining about it (or at least taking a long time t...
3,878,654
3,878,795
c++ gethostbyaddr with user input
I am writing c++ code for a telnet client. I am having problems getting the host address from the user input. struct in_addr peers; cin>>peers; peerserver = gethostbyaddr((const char*)peers,4,AF_INET); if (peerserver == NULL) exit(0); I am new to c++, can anyone suggest a better way of getting the host addr wit...
What you're looking for is gethostbyname, not gethostbyaddr. gethostbyaddr assumes that you've already got the IP address. char peers[256]; cin >> peers; struct hostent *ent = gethostbyname(peers); printf("%04x\n", *(int *)(ent->h_addr));
3,878,670
3,878,862
Initializing 2D Array In Class Constructor in C++
I define a 2D array in my header file char map[3][3]; How can I initialize the values in the class constructor like this map = {{'x', 'x', 'o'}, {'o', 'o', 'x'}, {'x', 'o', 'x'}};
Firstly, there is a difference between assignment and initialization. The OP title is about initialization. Secondly, you have not told us if your 2D array is a class member(static/non static) or a namespace variable. -Since you mentioned about initializing it in the class constructor, I am assuming that it is a class...
3,878,681
3,878,730
C++ new operator inheritance and inline data structures
I have a (C++) system that has many classes that have variable storage (memory) requirements. In most of these cases, the size of the required storage is known at the creation of the object, and is fixed for the lifetime of the object. I use this, for instance, to create a "String" object that has a count field, follo...
have you used using Expando::new in your derived class new operator? For example: void* operator new (....) { using Expando::new; .... } Otherwise, if you don't mind my opinion, I think your implementation of your String class is way off base. You have a count member, but no actual pointer data member to poi...
3,878,840
3,878,916
Is my design for UDP socket server correct?
I am designing a server which is used in UDP communication using MFC. I have the following classes CMyDlialog - Take care of User interface CController - Act as an Mediator between all the classes CProtocolManager - Take care of Encoding/Decoding msgs (This is a static class) CConnectionManager - Take care of UDP conn...
I think designs are never right or wrong, but you can rate them according to some principles that many people consider to be "good" (see the SOLID principles). Your sending approach sounds reasonable, but making the Dialog global for receiving is definitely considered "not so good". See the hollywood principle. I sugge...
3,878,873
3,880,279
transforming an image into an array of lines to draw
How do I generate a list of lines to draw if I have pixel data for an image, so I don't have to draw every pixel? Any language will do, although I listed what I have a working knowledge for. C is ok as well. There was a limit to how many tags I could choose. Also, you can just point me toward an algorithm.
You are looking for a "raster to vector" algorithm. The term comes from early graphics display systems, that used a CRT (cathode ray tube) for the display itself. There were 2 approaches to displaying graphics: "raster" was the scan of a series of lines left to right, top to bottom, each line made up of on/off pixels...
3,878,883
3,880,371
Compiling static TagLib 1.6.3 libraries for Windows
I am having a super hard time compiling and using TagLib 1.6.3 in my Qt project. I've tried everything I can think of. TagLib claims that it is supported through CMake but I'm not having any luck. Furthermore, I'm confused about what kinds of files I even need for my Qt libs! I've built *.a files, *.lib, and *.dll. Fro...
Since Mac works for you, I'm just talking about Win32. Ok, this are my Taglib.pro and an excerpt of my project.pro: https://gist.github.com/449ea81ce92f52399f41. Check them out. My Taglib may be a bit outdated, so take care, some files you may have could be missing there. Also take care of the relative paths. They are ...
3,878,884
3,878,924
Templated function being reported as "undefined reference" during compilation
These are my files: --------[ c.hpp ]-------- #ifndef _C #define _C #include<iostream> class C { public: template<class CARTYPE> void call(CARTYPE& c); }; #endif --------[ c.cpp ]-------- #include "c.hpp" template<class CARTYPE> void C::call(CARTYPE& c) { //make use of c somewhere here std::cout<<"Car"<...
A way to solve this problem is to a. remove '#include "c.hpp"' from c.cpp AND b. include 'c.cpp' at the end of 'c.hpp' (strange sounding '#include "c.pp"') This way the template definitions are availabe to each translation unit that includes 'c.hpp' without explicitly doing so in each .cpp file. This is called the 'in...
3,879,055
3,879,066
how to execute an for loop till the queue is emptyin c++
i need to execute an for loop till the queue is empty my code queue<string> q; for(int i=0;i<q.size(),i++) { // some operation goes here // some datas are added to queue }
while (!q.empty()) { std::string str = q.front(); // TODO: do something with str. q.pop(); }
3,879,129
3,882,293
Select & Copy firefox content to clipboard in C or C++
I found a few questions similar to mine but none of the answers are satisfactory and they are a few years old. So I am hoping that perhaps some progress has been made on that front since then. What I am interested in is the ability to access the content of an active Firefox window and copy it to the clipboard -- using ...
The DOM in firefox is exposed to C++ via XPCOM but beware, unlike MSHTML (in IE) the interfaces in Mozilla are not always frozen the unfrozen interfaces are version specific and may change from release to release. The XPCOM equivalent of IHTMLDocument2 is nsIDOMDocument. XPCOM is very similar to COM, the base class is ...
3,879,162
3,879,276
How to forward declare a template class in namespace std?
#ifndef __TEST__ #define __TEST__ namespace std { template<typename T> class list; } template<typename T> void Pop(std::list<T> * l) { while(!l->empty()) l->pop(); } #endif and used that function in my main. I get errors. Of course, I know that there are more template params for std::list (alloc...
The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly: namespace std { template<class T, class Allocator = std::allocator<T>> class list; } But to make even such a forward declaration...
3,879,266
3,879,283
cin skipping in while
Why is my cin being skipped in the following while? int main() { int option; cin >> option; while(!cin.good()) { cout << "Looping" << endl; cin >> option; } }
Errors in iostreams are sticky. You need to clear the error state before cin works again. int main() { int option; cin >> option; while(!cin.good()) { cout << "Looping" << endl; cin.clear(); // ignore erroneous line of input: cin.ignore(numeric_lim...
3,879,277
3,972,979
Hardware accelerated audio decoding with OpenAL
Is it possible to use the iPhone's hardware accelerated decoding of mp3s and AAC when using the OpenAL library? I suppose there are two possible approaches if this is possible. iPhone specific OpenAL extensions. iPhone APIs to decode audio into raw bytes. I have two specific use cases. Completely decode a short sound ...
There is at least one hardware (or hardware assisted) decoder in all iPhone device models. It can be accessed to convert mp3 and AAC files into raw PCM bytes by using the Audio Queue Services API. From thence you can process those bytes or send them to OpenAL.
3,879,294
3,881,034
Windows C/C++ Drive Init/Partition/Format
I am trying to build an application for Windows XP 64bit which is able to detect drives of a particular model in the system, and if they are not initialized & formatted perform these processes. I would also like to be able to query and set the partition information(including the volume label). I have started putting to...
Sounds like you are looking for Disk Management Control Codes.
3,879,591
3,880,187
QML ListView multiselection
How can I select a few elements in the QML ListView and send its indices to C++ code?
I am pretty sure there is no way to make a QML ListView multi-selectable. Qt Declarative is focused on touch screen use and there is no meaningful way to multiselect in a pure touch UI.
3,879,675
3,879,699
problem in threading c++
i am running 2 threads and the text i display first is displayed after the execution of thread string thread(string url) { mutex.lock(); //some function goes here mutex.unlock(); } int main() { cout<<"asd"; boost::thread t1(boost::bind(&thread)); boost::thread t2(boost::bind(&thread)); ...
std::cout << "asd" << std::flush;
3,879,775
3,880,208
List of boost::Unique_Ptr objects
Why can I not do this? typedef boost::interprocess::unique_ptr<QueueList, QueueListDeletor> UQList; typedef boost::intrusive::list<UQList> List; // Compiler (VS 2003) complains The QueueList is a class that derives from public boost::intrusive::list_base_hook<> to make it part of an intrusive linked list. I want to...
QueueList may be derived from list_base_hook, but UQList certainly isn't. Since you try to create an intrusive list of UQList (which is a unique_ptr) and not an intrusive list of QueueList objects, this won't work.
3,879,793
3,879,839
The best Linux tool for disassembling C++ executables
Which tool is the best for disassembling C++ executables? I'm looking for something like OllyDbg but for Linux. EDIT: Sorry, forgot to tell that I want to be able to debug, too, not just to see the asm code. EDIT2: By "best" I mean something like - "the best for windows is OllyDbg - can see the asm code and can debug, ...
Here are some. Good luck with your debugging! UPS Debugger Evan's Debugger Assembly Language Debugger (ALD) Insight Data Display Debugger (ddd) AsmBug Dissy
3,879,970
3,880,009
A weird expression in c++ - what does this mean?
I've seen this code for finding a Minor of a matrix: RegMatrix RegMatrix::Minor(const int row, const int col)const{ //printf("minor(row=%i, col=%i), rows=%i, cols=%i\n", row, col, rows, cols); assert((row >= 0) && (row < numRow) && (col >= 0) && (col < numCol)); RegMatrix result(numRow-1,numCol-1); // copy the c...
(row >= numRow) is a boolean expression. If operator>= has not been overloaded, it should evaluate to true if row is greater or equal to numRow, and to false otherwise. When casting this boolean to an integer for subtraction, it will become 1 if true, 0 else.
3,880,366
3,880,421
Linear congruential generator: How important is setting seed?
I'm learning about linear congruential generator in an algorithms and data structures course. After thinking about RNG implementation we've been using (a=429493445, c=907633385, mod=4294967296, X is _uint32), one thing came to my mind: Program has a function for setting seed. How important would that function be in C ...
While for unserious playing around with RNGs, seeding with "junk in memory" probably will work OK. But it is really a bad way to do things: You have no guarantee that the data in memory is random, even though it can be. In security applications (which I guess are not relevant here, since you're using a linear congruenc...
3,880,380
3,889,346
Static lib loading related issue
Suppose I want to version the libs in binaries made. For static libs, I thought this approach would work but it does not: LibInfo.h - Base class for all libinfo classes. Registers an object in gvLibInfo vector when a child is constructed. #ifndef IFACE_H #define IFACE_H #include <vector> class LibInfo; extern std:...
The first answer to this question propose to use the --whole-archive flag. The main difference is, instead of referring to an external object, the library refers to an external function. Linking does not occur with -L, but with -l, i.e. it should be : -L/path/to/libdir -lname If your library is : /path/to/libdir/libna...
3,880,425
3,888,854
Is there a performance penalty for creating Direct3D vertices with all semantic types?
In Direct3D, you can create any type of Vertex you like. You can have a simple Vertex with just positional information, or you could add colour info, texture info, etc etc. When creating your input layout, you define what parts of a Vertex you've implemented: D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, D...
I solved it by generating a chunk of memory on the heap and only filling it with the required elements. The code is available here: http://code.google.com/p/woof/source/browse/trunk/Libraries/WOOF3D/Direct3D10Vertices.cpp?r=24
3,880,594
3,880,740
How can I add a gradient to a tab control background?
I have a tab-based application for windows, which I am developing by myself. I would like to add a subtle gradient to the background of my tab control. How would I go around doing this? What is the best method for me to use? I think that implementing a custom control that takes up the space of the tab control would wor...
To use GDI you'll need the GradientFill function. You can also use GDI+ to get gradients. Here's a plain GDI example: TRIVERTEX vert[2] ; GRADIENT_RECT gRect; vert [0] .x = 0; vert [0] .y = 0; vert [0] .Red = 0x0000; vert [0] .Green = 0x0000; vert [0] .Blue = 0x0000; vert [0] .Alpha = 0x0000;...
3,880,669
3,880,712
A problem overloading [] in 2 variations
this is my generic class: template<class T, class PrnT> class PersonalVec { public: PersonalVec(); T &operator[](int index) const; const T &operator[](int index) const; private: std::vector<T> _vec; }; I'm required to implement 2 versions of [] operator: one that will return a const reference and a ...
Return type of a function is not a criteria that can be used for overloading of functions. A function can be overloaded if: 1. Different no of arguments 2. Differnt Sequence of arguments or 3. Different types of arguments You are trying to overload the function based on return type and hence it gives the error. The...
3,880,683
3,880,756
Confused about implicit template instantiation
This is the statement from the C++03 standard, §14.7.1p5: If the overload resolution process can determine the correct function to call without instantiating a class template definition, it is unspecified whether that instantiation actually takes place. [Example: template <class T> struct S { ...
During overload resolution it is determined that the correct function to call when you write f(sr) is void f(S<int>&); without explicitly instantiating the definition of class template S, it is unspecified whether your class is actually instantiated. Undefined behaviour and Unspecified behaviour are two completely diff...
3,880,735
3,880,823
Floyd's cycle-finding algorithm
I'm trying to find this algorithm on C++ in .NET but can't, I found this one: // Best solution function boolean hasLoop(Node startNode){ Node slowNode = Node fastNode1 = Node fastNode2 = startNode; while (slowNode && fastNode1 = fastNode2.next() && fastNode2 = fastNode1.next()){ if (slowNode == fastNode1 || slo...
The idea in the code you've found seems fine. Two fast iterators are used for convenience (although I'm positive such kind of 'convenience', like putting a lot of 'action' in the condition of while loop, should be avoided). You can rewrite it in more readable way with one variable: while (fastNode && fastNode.next()) {...
3,880,748
3,880,888
Getting started with smart pointers in C++
I have a C++ application which makes extensively use of pointers to maintain quite complex data structures. The application performs mathematical simulations on huge data sets (which could take several GB of memory), and is compiled using Microsoft's Visual Studio 2010. I am now reworking an important part of the appl...
Here are the 3 varieties found in the new C++11 standard (unique_ptr replaces auto_ptr) http://www.stroustrup.com/C++11FAQ.html#std-unique_ptr http://www.stroustrup.com/C++11FAQ.html#std-shared_ptr http://www.stroustrup.com/C++11FAQ.html#std-weak_ptr You can read the text for each pointer and there is an explanation of...
3,880,924
3,880,986
How to view symbols in object files?
How can I view symbols in a .o file? nm does not work for me. I use g++/linux.
Instead of nm, you can use the powerful objdump. See the man page for details. Try objdump -t myfile or objdump -T myfile. With the -C flag you can also demangle C++ names, like nm does.
3,880,927
3,881,177
num_get facet and stringstream conversion to boolean - fails with initialised boolean?
I have inherited a template to convert a string to a numerical value, and want to apply it to convert to boolean. I am not very experienced with the stringstream and locale classes. I do seem to be getting some odd behaviour, and I am wondering if someone could please explain it to me? template<typename T> T convert...
Initialising a bool with 0 will reliably set it to false, and this has no effect on the stream extraction. What is causing your problem is that streams by default only recognize the values 0 and 1 when dealing with booleans. To have them recognize the names true and false, you need to tell that explicitly to the stream...
3,881,022
3,881,032
Visual Studio C++ Express 2010 - does it work with unmanaged code?
Does Visual Studio C++ Express 2010 work with unmanaged code? Or is it only managed?
Yes, it does work with unmanaged code.
3,881,165
3,881,277
How do I validate template parameters in compile time when a templated class contains no usable member functions?
I have a following templated struct: template<int Degree> struct CPowerOfTen { enum { Value = 10 * CPowerOfTen<Degree - 1>::Value }; }; template<> struct CPowerOfTen<0> { enum { Value = 1 }; }; which is to be used like this: const int NumberOfDecimalDigits = 5; const int MaxRepresentableValue = CPowerOfTen<Number...
template<bool> struct StaticCheck; template<> struct StaticCheck<true> {}; template<int Degree> struct CPowerOfTen : StaticCheck<(Degree > 0)> { enum { Value = 10 * CPowerOfTen<Degree - 1>::Value }; }; template<> struct CPowerOfTen<0> { enum { Value = 1 }; }; Edit: without infinite recursion. // Help...
3,881,264
3,881,523
How to initialize a const char* and/or const std::string in C++ with a sequence of UTF-8 character?
How to initialize a const char* and/or const std::string in C++ with a sequence of UTF-8 characters? I'm using a regular expression API that accepts UTF8 string as const char*. The initialization code should be platform independent.
This should work with any compiler: const char* twochars = "\xe6\x97\xa5\xd1\x88";
3,881,300
3,882,076
is there is any way to get xml value by tag in rapid xml using c++
is there is any way to get the value of tag by its tagname in rapidxml using c++ <?xml version=\1.0\ encoding=\latin-1\?> <book>example</book> <book1>example1</book1> i need to get the book value ie example and book1 value ....we can use this doc.first_node()->value() get first node and next node but i need to is ther...
You should be able to call first_node using a node name to be matched. From the docs: function xml_node::first_node Synopsis xml_node* first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; Description Gets first child node, optionally matching node name. Parameters name Name o...
3,881,325
3,887,625
Variable dissapears in binary which is available in static lib
I have the problem mentioned. I create an object inside a static lib, it is there when I run nm on the static lib, but when i link the lib to a binary and run nm it has disappeared. I know this problem has been asked before, but I could not find any answers. It is important for me to be able to retain that variable in ...
I found what I was looking for :D. It seems that linker flag --whole-archive is there to make sure all symbols in static lib regardless of whether they are accessed by app or not get into app. Though I still have trouble getting this to work, I guess I am on the right path.
3,881,488
3,881,552
how to convert a boost::weak_ptr to a boost::shared_ptr
i have a shared_ptr and a weak_ptr typedef boost::weak_ptr<classname> classnamePtr; typedef boost::shared_ptr<x> xPtr; how to convert a weak_ptr to a shared_ptr shared_ptr = weak_ptr; Xptr = classnameptr; ?????
As already said boost::shared_ptr<Type> ptr = weak_ptr.lock(); If you do not want an exception or simply use the cast constructor boost::shared_ptr<Type> ptr(weak_ptr); This will throw if the weak pointer is already deleted.
3,881,583
3,881,648
struct reference and operator=
I have a class like this: template <class T> class bag { private: typedef struct{T item; unsigned int count;} body; typedef struct _node{_node* prev; body _body; _node* next;}* node; struct iterator{ enum exception{NOTDEFINED, OUTOFLIST}; body operator*(...
References can't be assigned, only initialised. So you will need to initialise them in the constructor's initialisation list: bag() : begin(_begin), end(_end) {} However, it's more conventional (and also reduces the class size) to get these using accessor functions rather than public references: const iterator& begin(...
3,881,633
3,882,088
Reducing number of template arguments for class
I have a method and two classes defined like this: template<template<class X> class T> void doSomething() { T<int> x; } template <class T> class ClassWithOneArg { T t; }; template <class T1, class T2> class ClassWithTwoArgs { T1 t1; T2 t2; }; I can now doSomething<ClassWithOneArg>(); but I cannot ...
Indirection is a solution. Instead of a template template parameter you pass a "meta function" -- a function that maps one type to another in form of a struct with a nested class template: struct mf1 { template<class Arg1> struct eval { typedef ClassTemplateWithOneArg<Arg1> type; }; }; template<class Arg2> s...
3,881,678
3,881,830
shared_ptr gets destroyed before I can use it properly
I have the following code, which is supposed to add a shared_ptr instance to an intrusive linked list by thread A. Some other consumer thread will then use it later on by removing it from the list. However at a certain point my shared_ptr seems to get destroyed and the reference to it in the linked list is no longer ...
If BaseHookQueueList is an intrusive list like you said, then you should remember that intrusive list doesn't take the ownership of the objects. In this case your shared pointers have the ownership, and when they are destroyed, the object is destroyed too. edit: Instead of intrusive list you could use a container like...
3,881,937
3,881,993
Unary Operator-() on zero values - c++
I wrote this code to overload the unary operator- on a matrix class: const RegMatrix RegMatrix::operator-()const{ RegMatrix result(numRow,numCol); int i,j; for(i=0;i<numRow;++i) for(j=0;j<numCol;++j){ result.setElement(i,j,(-_matrix[i][j])); } return result; } When i ra...
Signed zero is zero with an associated sign. In ordinary arithmetic, −0 = +0 = 0. However, in computing, some number representations allow for the existence of two zeros, often denoted by −0 (negative zero) and +0 (positive zero). This occurs in some signed number representations for integers, and in mos...
3,882,186
3,882,455
Trouble with inheritance of operator= in C++
I'm having trouble with the inheritance of operator=. Why doesn't this code work, and what is the best way to fix it? #include <iostream> class A { public: A & operator=(const A & a) { x = a.x; return *this; } bool operator==(const A & a) { return x == a.x; } virtu...
If you do not declare copy-assignment operator in a class, the compiler will declare one for you implicitly. The implicitly declared copy-assignment operator will hide any inherited assignment operators (read about "name hiding" in C++), meaning that any inherited assignment operators will become "invisible" to the unq...
3,882,249
3,899,697
How google docs shows my .PPT files without using a flash viewer?
I want to show .ppt (PowerPoint) files uploaded by my user on my website. I could do this by converting them into Flash files, then showing the Flash files on the web page. But I don't want to use Flash to do this. I want to show it, like google docs shows, without using Flash. I've already solved the problem for .pdf ...
Now i found a solution to showing .ppt file on my website without using the flash the solution is: just convert the .ppt file to .pdf files using any language or using software(e.g. open office) and then use Imagemagick to convert that .pdf into image and show to your web page once again thanks to you all for answeri...
3,882,257
3,882,354
Is there a version of the VC++ 2008 Redistributable Package with the DEBUG dlls?
We have a (mainly) C#/WPF application that invokes some C++ libraries via interop. For testing purposes (and because of some inconsistencies in a third party library), we would like to distribute a debug version or our application on a target machine, partially for remote debugging. In any case, when doing so, the prog...
If the target machine is under your control, you may want to install Visual Studio on it. That will deploy the debug version of the runtime. Alternatively, copy the side-by-side libraries from your development machine to the target machine. Look in %windir%\WinSxS. On my dev machine (VS 2008 SP1), they reside in the fo...
3,882,280
3,882,297
Is there a ReSharper-like tool for C++ projects?
I'm searching tool like ReSharper for C++. I want to have a more flexible refactoring tool than Visual Assist. It is really really good but if there exists a tool like ReSharper for C++, I want to know the tool's name.
In this question a while back someone suggested "Refactor Pro", but this is 2008 there may be more modern tools that are better suited to what you are after. ReSharper (or something like it) for Visual C++?
3,882,304
3,882,420
Replace\remove character in string
string DelStr = "I! am! bored!"; string RepStr = "10/07/10" I want to delete all '!' on DelStr and I want to replace all '/' with '-' on the RepStr string. Is there any way to do this without doing a loop to go through each character?
Remove the exclamations: #include <algorithm> #include <iterator> std::string result; std::remove_copy(delStr.begin(), delStr.end(), std::back_inserter(result), '!'); Alternatively, if you want to print the string, you don't need the result variable: #include <iostream> std::remove_copy(delStr.begin(), delStr.end(),...
3,882,346
3,882,422
Forward declare FILE *
How do I forward declare FILE * in C? I normally do this using struct MyType;, but naturally this doesn't appear to be possible. If behaviour differs between C standards or compilers and with C++, this is also of interest. Update0 Why I want to do this aside: What I'm asking is how to forward declare a non-struct/"type...
You can't. The standard just states that FILE is "an object type capable of recording all the information needed to control a stream"; it's up to the implementation whether this is a typedef of a struct (whose name you don't know anyway), or something else. The only portable way to declare FILE is with #include <stdio....
3,882,366
3,882,389
Joining two programs one with main() one with WinMain()
I want to combine two programs into a single executable. One is an open source program that has a rather complex project file, the other is one of mine with a much simpler structure. Because of the relative complexities of the project files I feel it would make most sense to start with the open source project and modif...
If your program has WinMain(), it is presumably a Windows program, while the other is a command-line app. Depending on what the original apps actually do, this may make it difficult to merge them. E.g. if the other app uses standard input/output extensively, it is challenging to transform it into a Windows app. However...
3,882,414
3,885,685
Expression template operator overloading problem with std::vector
I'm currently working on a numerical library that uses expression templates. Unfortunately I encountered a problem with my operator overloads. Consider the following stripped down example. #include <vector> namespace test { class test {}; template<class A, class B> class testExpr {}; template<class A...
This is because end() returns a type that is a class template specialization which has one argument of type test::test *. Thus when operator- is applied in the expression end() - 1, argument dependent lookup looks also in the namespace of test::test. It finds your operator- and passes it the iterator and an int. You c...
3,882,467
16,090,720
Defining operator< for a struct
I sometimes use small structs as keys in maps, and so I have to define an operator< for them. Usually, this ends up looking something like this: struct MyStruct { A a; B b; C c; bool operator<(const MyStruct& rhs) const { if (a < rhs.a) { return true; } e...
This is quite an old question and as a consequence all answers here are obsolete. C++11 allows a more elegant and efficient solution: bool operator <(const MyStruct& x, const MyStruct& y) { return std::tie(x.a, x.b, x.c) < std::tie(y.a, y.b, y.c); } Why is this better than using boost::make_tuple? Because make_tup...
3,882,551
3,883,360
Understanding the design of std::istream::read
std::istream has the prototype istream& read (char* s, streamsize n) the actual number of bytes read should be gotten by calling istream::gcount(), also the validity of the istream can be known from ios::good. I was discussing another stream class' implementation I was trying to write with a colleague of mine, where I ...
I assume it's because C++ doesn't typically force an interface that may not be needed by everyone. If you require read to accept a parameter that some people don't care about, then it causes extra coding work (declaring an extra int to pass as a parameter). It also always saves the bytes read regardless of whether the ...
3,882,682
3,882,837
Transparently manipulating strings inserted into an ostream
I'd like to provide an std::ostream that may or may not, from the user's point of view, encrypt its contents. Imagine some random function that uses an std::ostream&: void write_stuff( std::ostream& stream ) { os << "stuff"; } Whether stuff is output in cleartext or is encrypted is dependent on how the stream argu...
A streambuf can be implemented in terms of another arbitrary streambuf that's either passed in as an argument to the constructor or set with a special member function. And that allows you to stack streambuf implementations like you were thinking of. You could even make a manipulator that uses the ostream's rdbuf funct...
3,883,086
3,883,103
C++ Interop: How do I call a C# class from native C++, with the twist the class is non-static?
I have a large application written in native C++. I also have a class in C# that I need to call. If the C# class was static, then it would be trivial (there's lots of examples on the web) - just write the mixed C++/CLI wrapper, export the interfaces, and you're done. However, the C# class is non-static, and can't be ch...
C++/CLI or COM interop work just as well with non-static classes as with static. Using C++/CLI you just reference your assembly that holds the non-static class and then you can use gcnew to obtain a reference to a new instance. What makes you think that this is not possible with your non-static class? EDIT: there is ex...
3,883,135
3,883,327
For locale-sensitive functions, is it more common to pass the std::locale or the needed facet object(s)?
Recently I wrote a family of functions for trimming leading and trailing whitespace off of an input string. As the concept of "whitespace" is locale-dependent, I realized that I would need to either pass in a const std::ctype<char_t> reference or a const std::locale reference and call std::use_facet<std::ctype<char_t> ...
Seeing how the standard library's isspace() is actually std::isspace(charT, const std::locale&), I would think it would follow the principle of the least surprise if your trim whitespace functions also took const locale&. But what's stopping you from allowing both?
3,883,191
3,883,372
What is the recommended way of working with QActions in multiple level hierarchy of widgets?
I'm planning on using qActions for use globally in my application. The idea is to have an action to be available at any level in the widget parent/child hierarchy. Let's say I have the following GUI: +--------------+ | +----------+ | | | +----+ | | | | | W2 | | | | | +----+ | | | | W1 | | | +----------+ | |...
Personnally, I'd go with a modified version of the second option, in the other way, because it keeps the hierarchy of your program. I say the other way because I would make the w2 pushButton propagate the signal up to the mainWindow. An advantage to this option is that if you add another w2 in w1, you simply have to co...
3,883,380
3,883,683
Namespace refactoring tool for Eclipse?
I'm doing some housekeeping on some files, and I need to move some classes to a new namespace. Currently I have to manually edit the files, but I was wondering if there's a more efficient way of doing this? I heard about ReSharper for Visual Studio does what I need, but is there a similar tool for Eclipse?
I'm not really sure if Eclipse does that but IntelliJ IDEA (from the same vendor as ReSharper) does have a refactoring to move classes between packages. It is available from Refactor > Migrate menu if I remember correctly.
3,883,561
3,883,602
C++ whether a template type is a pointer or not
Possible Duplicate: Determine if Type is a pointer in a template function I am looking for a method to determine whether a template is a pointer or not at compiling time. Because when T is not a pointer, the program will not compile as you cannot delete a normal type variable. template <typename T> void delete(T &a...
That is a handy utility, but I think it's better just to get used to assigning NULL after using native delete. To get a function that only is considered for modifiable pointer type arguments, use template< typename T > // The compiler may substitute any T, void delete_ref( T *&arg ); // but argument is still a pointer ...
3,883,585
3,883,645
typeinfo / typeid output
I'm currently trying to debug a piece of simple code and wish to see how a specific variable type changes during the program. I'm using the typeinfo header file so I can utilise typeid.name(). I'm aware that typeid.name() is compiler specific thus the output might not be particularly helpful or standard. I'm using GCC ...
I don't know if such a list exists, but you can make a small program to print them out: #include <iostream> #include <typeinfo> #define PRINT_NAME(x) std::cout << #x << " - " << typeid(x).name() << '\n' int main() { PRINT_NAME(char); PRINT_NAME(signed char); PRINT_NAME(unsigned char); PRINT_NAME(short...
3,883,842
3,883,872
Overloading increment operator, looping, and edge cases
I have an enum, that looks like this: enum Suit {Clubs, Diamonds, Hearts, Spades}; I want to overload the increment operator, so I can easily loop over these four dudes. When the variable is Clubs, Diamonds, or Hearts there no issue. Its the Spades condition that is giving me a little trouble. My first instinct was to...
You could add enum values for start and termination conditions, and an alternative to ++ which doesn't cycle back to the beginning. enum Suit { FirstSuit, Clubs = FirstSuit, Diamonds, Hearts, Spades, AllSuits }; for ( suit i = FirstSuit; i != AllSuits; i = iterate_suits( i ) ) Since for and while loops always check t...
3,883,922
3,883,952
C++ simple polymorphism issue
Ok I admit it, I'm a total C++ noob. I was checking the book Data Structures and algorithms in C++ by Adam Drozdek, in the section 1.5 : "Polymorphism" he proposes the next example: class Class1 { public: virtual void f() { cout << "Function f() in Class1" << endl; } void g() { cout...
If that's really the code the book uses, throw the book in the trash immediately. Polymorphism works over inheritance, such as class Class2 : public Class1 Without that, there is no hope of a correct program. The author appears to try and circumvent the requirement (i.e., get an incorrect program to compile) by using ...
3,883,949
3,884,003
Create a vector of pointers to abstract objects
I'm sure there's a better way to do this. I'm trying to create a class HashTable that is given a size at instantiation, so it can't be given a size at design time, so I can't use an array as my internal representation of the table, as far as I know. So here's what I'm trying to do: #include <vector> #include <iostream>...
Move the asterisk around: vector<TableNode<T>*> myTable; myTable = vector<TableNode<T>*>(size,NULL);
3,884,124
3,884,179
convert a console app to a windows app
(its a long story) but I have a large complex project file containing a windows program. Unfortunately the project was originally built as a console app. The program compiles and links ok but when runs brings up a console instead of the collection of windows I was hoping for. I looked at the command line and saw "/SUBS...
Right-click the project icon in the Solution Explorer, then Properties > Linker > System > SubSystem, and set that to Windows. You'll also have to change your main() method to WinMain(). And you'd better create some windows or there won't be much to look at.
3,884,491
3,884,530
Overloading virtual functions in two different interfaces
I have an issue where I have an interface that has parts that make sense as templated, and parts that make sense as not-templated. I'm in the middle of a refactor where I'm splitting that out into two different interfaces where the more specific (the templated one) inherits from the other one. E.g., say I have an int...
Have you tried adding a using directive? IA::X is a hidden by A::X. class A : ... { public: using IA::X; virtual void X(DataType d) = 0; };
3,884,572
3,884,648
How to modify key values in std::map container
Given std::map<int,std::string> myMap; fillMyMapWithStuff(myMap); // modify key values - I need to add a constant value to each key for (std::map<int,std::string>::iterator mi=myMap.begin(); mi != myMap.end(); ++mi) { // ... } Whats a good way apply some re-indexing? Must I remove the old entry and add a new one ...
Looks like you are better off building a new map and swapping it afterward. You'll have only n insert operations instead of n deletions and n insertions.
3,884,770
3,885,061
C++ unrestricted union workaround
#include <stdio.h> struct B { int x,y; }; struct A : public B { // This whines about "copy assignment operator not allowed in union" //A& operator =(const A& a) { printf("A=A should do the exact same thing as A=B\n"); } A& operator =(const B& b) { printf("A = B\n"); } }; union U { A a; B b; }; i...
C++ does not allow for a data member to be any type that has a full fledged constructor/destructor and/or copy constructor, or a non-trivial copy assignment operator. This means that structure A can only have a default copy assignment operator (generated by the compiler) or not have it at all (declared as private with ...
3,884,775
3,885,080
C++ preprocessor concatenation
I have a function build with function pointers. I think it might be faster to try to exchange this function with pre processor macro. At least, I would like to try out the macro so I can measure if it generates faster code. It's more or less like this: typedef int (Item::*GetterPtr)(void)const; typedef void (Item::*Set...
Token-pasting means "combining two tokens to form a single token". You don't want that. ptr_to_item->a() isn't one token. Assuming ptr_to_item is a variable name, it's 5: ptr_to_item, ->, a, (, ). Your macro should just be: #define DO_STUFF(item, getter, setter, k) do { \ int value = (item)->getter(); \ //... \...
3,885,095
3,885,136
Multiply vector elements by a scalar value using STL
Hi I want to (multiply,add,etc) vector by scalar value for example myv1 * 3 , I know I can do a function with a forloop , but is there a way of doing this using STL function? Something like the {Algorithm.h :: transform function }?
Yes, using std::transform: std::transform(myv1.begin(), myv1.end(), myv1.begin(), std::bind(std::multiplies<T>(), std::placeholders::_1, 3)); Before C++17 you could use std::bind1st(), which was deprecated in C++11. std::transform(myv1.begin(), myv1.end(), myv1.begin(), std::bind1st(std::...
3,885,317
3,885,392
std::transform using C++0x lambda expression
How is this done in C++0x? std::vector<double> myv1; std::transform(myv1.begin(), myv1.end(), myv1.begin(), std::bind1st(std::multiplies<double>(),3)); Original question and solution is here.
std::transform(myv1.begin(), myv1.end(), myv1.begin(), [](double d) -> double { return d * 3; });
3,885,482
3,885,638
Does a vector sort invalidate iterators?
std::vector<string> names; std::vector<string>::iterator start = names.begin(); std::vector<string>::iterator end = names.end(); sort (start,end); //are my start and end valid at this point? //or they do not point to front and tail resp?
According to the C++ Standard §23.1/11: Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within t...
3,885,580
3,885,639
C++: access to container of shared_ptr should return raw or shared ptr?
If I use a container of shared_ptrs and explicitely allow access to its elements, should I return shared_ptrs or raw pointers if I intend the container to be the one responsible for "cleaning up"? class Container { private: std:vector<shared_ptr<Foo> > foo_ptrs; public: shared_ptr<Foo> operator[](std::size_t i...
return a reference Only return a shared_ptr if you intend the accessors to share in the lifetime management. That is a valid design but as you said Container is solely responsible for the cleanup. shared_ptr is just an implementation detail of Containter, that fact that there is a vector of shared_ptrs used to implem...
3,885,883
3,885,954
template class + operators + friends = unresolved externals
I have a class called fraction, and I'm declaring some operators as friends. I declared the friend operators beforehand, as http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16 told me to do, but it only fixed +, -, *, and /. << and >> still don't work. template <class T> class Fraction; template <class T> Fr...
As "dark_charlie" says, but remove the const. I'd rather have made this as just a comment, but unfortunately StackOverflow does not yet allow me to comment (to the person feeling the urge to comment that I shouldn't make this comment: it's aimed at you).
3,886,105
3,886,128
How to print to console when using Qt
I'm using Qt4 and C++ for making some programs in computer graphics. I need to be able to print some variables in my console at run-time, not debugging, but cout doesn't seem to work even if I add the libraries. Is there a way to do this?
If it is good enough to print to stderr, you can use the following streams originally intended for debugging: #include<QDebug> //qInfo is qt5.5+ only. qInfo() << "C++ Style Info Message"; qInfo( "C Style Info Message" ); qDebug() << "C++ Style Debug Message"; qDebug( "C Style Debug Message" ); qWarning() << "C++ Sty...
3,886,194
3,886,208
Are C++ template-functions threadsafe?
Googling don't find anything. Are they created at point of use, or are the generic parts shared between instances? (Same for template classes?)
Template functions are created at compile time. The template property is completely orthogonal to thread-safety.
3,886,287
3,886,326
parallel calculation of infinite series
I just have a quick question, on how to speed up calculations of infinite series. This is just one of the examples: arctan(x) = x - x^3/3 + x^5/5 - x^7/7 + .... Lets say you have some library which allow you to work with big numbers, then first obvious solution would be to start adding/subtracting each element of the ...
You need to break the problem down to match the number of processors or threads you have. In your case you could have for example one processor working on the even terms and another working on the odd terms. Instead of precalculating x^2 and using lastX*(x^2), you use lastX*(x^4) to skip every other term. To use 8 proc...
3,886,415
3,886,459
What is the simplest way to asynchronously communicate between C++ and C# applications
I have a C++ application that needs to communicate to a C# application (a windows service) running on the same machine. I want the C++ application to be able to write as many messages as it wants, without knowing or caring when/if the C# app is reading them, or even if it's running. The C# app be able to should just wa...
Well, the simplest way actually is using a file to store the messages. I would suggest using an embedded database like SQLite, though: the advantage will be better performance and a nice way to query for changes (i.e. SELECT * FROM messages WHERE timestamp > last_app_start).
3,886,438
3,886,537
Problematic vector return value - not really updated?
I'm having this weird problem: when my program reach this method: //Returns the transpose matrix of this one RegMatrix RegMatrix::transpose() const{ RegMatrix result(numCol,numRow); int i,j; for(i=0;i<numRow;++i) for(j=0;j<numCol;++j){ result._matrix[j][i] = _matrix[i][j]; } ...
Assuming that MyDouble has a correct copy constructor, you should be able to reduce your copy constructor to just this: RegMatrix::RegMatrix(const RegMatrix &other):numRow(other.getRow()), numCol(other.getCol()), _matrix(other._matrix) { } See what that gets you. Edit: Your assignment operator might be a problem i...
3,886,506
3,886,639
Why would connect() give EADDRNOTAVAIL?
I have in my application a failure that arose which does not seem to be reproducible. I have a TCP socket connection which failed and the application tried to reconnect it. In the second call to connect() attempting to reconnect, I got an error result with errno == EADDRNOTAVAIL which the man page for connect() says m...
Check this link http://www.toptip.ca/2010/02/linux-eaddrnotavail-address-not.html EDIT: Yes I meant to add more but had to cut it there because of an emergency Did you close the socket before attempting to reconnect? Closing will tell the system that the socketpair (ip/port) is now free. Here are additional items too l...
3,886,561
3,886,885
OpenCV - cvExtractSURF is causing a memory leak?
I am using the OpenCV function: cvExtractSURF but I am finding a major memory leak. Has anyone successfully implemented this call? My code is as follows: IplImage *cvImage = [self CreateIplImageFromUIImage:image grayscale:YES]; CvMemStorage* storage = cvCreateMemStorage(0); CvSeq *objectKeypoints = 0; //CvSeq *objec...
The function cvExtractSURF creates a list of objects of type CvSURFPoint and puts a pointer to it in objectKeypoints. You have to free that up. Add a call... cvRelease((void **)&objectKeypoints);
3,886,585
3,888,772
capture video from a built-in camera programatically
I was wandering how could capture video from the built-in camera of my netbook, under Linux, ubuntu. The programming language could is not an issue (but I prefer Java or the old school c) Thanks in advance for your answers, Gian
In Linux the canonical way of talking to webcams are via v4l. Here is a library called libfg for a simple high level C API on top of v4l.
3,886,593
3,886,599
How to check if std::map contains a key without doing insert?
The only way I have found to check for duplicates is by inserting and checking the std::pair.second for false, but the problem is that this still inserts something if the key is unused, whereas what I want is a map.contains(key); function.
Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want. Alternately my_map.find( key ) != my_map.end() works too.
3,886,737
3,886,845
Trick Windows To See Second Monitor
is there anyway to trick windows into thinking that a second monitor is connected to the computer, even if there isnt one? Example: Laptop also has an external screen connected into it. The external screen is the primary screen. When the screen is disconnected the laptop becomes primary even if the external screen is r...
For work, I actually had the same situation -- on an embedded PC, we needed a second monitor to always be available. I put a considerable amount of time into researching it, but I wasn't able to find any solution other than with hardware. If you have a VGA port (or DVI-I), you're in luck. You can find directions on ho...
3,886,757
3,886,842
Why doesn't unary_function define operator()?
I was just looking for a handy base class for a set of functors to be based on taking and int and returning void. Thinking to use std/functional the functors are basically going to be unary_function<int,void> with operator(). Why is virtual result_type operator()(const argument_type& _Left) const = 0; not defined on t...
Template concepts are duck-typed. The fact that a class satisfying the UnaryFunction concept needs operator() is specified in the documentation and inferred from the templates which use template parameters satisfying that concept. There's no need to spell out the function signature, or to require that it be virtual, th...