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
6,054,092
6,054,445
How to add authentication to a socks5 proxy server?
I am trying to build a socks5 proxy server using codes I found googling and customizing them. Everything works fine so far but now I want to add authentication to the socks5. This is the code that handle the requests: SOCKET socks5Handler( SOCKET Client, char* Buffer ) { SOCKS5AUTH sAuth; char *Host = NULL...
The SOCKS5 protocol is defined in RFC 1928. The 0x02 user/password authentication method is defined in RFC 1929. An excerpt: Once the SOCKS V5 server has started, and the client has selected the Username/Password Authentication protocol, the Username/Password subnegotiation begins. This begins with the cli...
6,054,181
6,054,301
Assign value using curly braces/bracket to std::string
If this is valid: unsigned char buffer[] = { 0x01, 0x02, 0x03, 0x04 }; Does this apply to std::string as well, e.g. std::string buffer = { 0x01, 0x02, 0x03, 0x04 }; If not, how do I insert such values?
Not in C++03, but you can do this in C++011: std::string buffer = { 0x01, 0x02, 0x03, 0x04 }; //C++011 ONLY Demo : http://www.ideone.com/1cOuX. In the demo, I used printable characters ('A', 'B' etc) just for the sake of demonstration. In C++03, since the solution given by @andrewdski is admittedly ugly, you can do ...
6,054,397
6,054,520
Question about bool in C++
I was wondering why the code below only returns "Test" four times, instead of five? #include <iostream> #include <cassert> using namespace std; class CountDown { public: //Application Programmer Interface CountDown(int start); // it is set to start void next(); // subtracts on...
There is no point in doing this double initialization: CountDown::CountDown(int start) { it = 0; it = start; } This is enough: CountDown::CountDown(int start) { it = start; } Or even this, using the initialization list: CountDown::CountDown(int start):it(start) { } As for end() you don't return any value...
6,054,438
6,054,797
How can I create a window (HWND) without using CreateWindow(Ex)?
I'm using a proxy DLL to intercept calls to CreateWindowExA/CreateWindowExW. This works quit nicely, except that some applications (most notably some Visual Basic 6 applications) seem to be able to create windows without going through either of the two functions. Tools like Spy++ are able to show the Window, but my hoo...
Three simple guesses: 1) Is it possible that VB apps are really calling a "DialogBox" API (e.g. DialogBoxParam, CreateDialogIndirect, etc...) underneath the hood? 2) You are running a 64-bit OS and are hooking the 64-bit user32.dll. 32-bit apps aren't getting hooked as a result. There's a 32-bit copy of user32.dll in...
6,054,780
6,055,147
Initializing struct within a class
Is this allowable? class object { public: struct st_example { int i; int j; int c[d]; st_example(int i_i, J_j, d_d) : i(i_i), j(j_j), d(d_d) {} }; object(int i_ii, int j_jj, int d_dd) { struct st_example test(i_ii, j_jj, d_dd); }; // Constructor }; So that:...
What's d in st_example? I don't see any variable d, so you can't initialize it, nor use it in an expression. If you simply want st_example to contain an array whose size is determined at runtime, use std::vector. Trying to do it as you do cannot be made to work; you define a local st_example, and the compiler has to ...
6,054,854
6,180,631
Boost serialization/deserialization archive "stream error" exception
I've the following problem.. I have a file called A.h and a file B.h. each contains some struct like this: (the structs inside the two classes are different) struct Base { friend class access; template <typename Archive> void serialize(Archive& ar,const unsigned int version) { ar & fieldLength...
Have you serialised the base data in the derived class serialize function? ar & boost::serialization::make_nvp( "base", boost::serialization::base_object< Base >( *this ) ); And I dont know if this would help, but I use BOOST_CLASS_IMPLEMENTATION(x, boost::serialization::object_serializable); BOOST_CLASS_TRACKING(x, b...
6,054,909
6,055,732
To find the nearest perfect square if the number entered is not a perfect square?
#include <iostream> #include <limits> #include <cmath> using namespace std; int main() { int number; cout << "Enter the number whose sqare root needs to be calculated"; cin >> number; cout << "Square root of " << number << " is " << (int)sqrt((float)number) << " OR " << sqrt((float)number) << endl; ...
Actually, here is the better answer: int number = 13; int iRoot = static_cast<int>(sqrt(static_cast<float>(number)) + .5f); You don't need to check between the ceil or the floor of which is greater, doing a simple round does the trick. sqrt(13) is 3.6 and when you add .5 casts to 4. sqrt(12) is 3.46 and when you add ...
6,055,026
6,055,094
How can we prevent console windows from being displayed under Visual Studio?
Is it possible (and how) to disable the display of the Console window when we launch an application under Visual Studio? EDIT: Some precisions: I have at the beginning of this project no GUI system. In a second time I have added QT gui to this project. Currently when I launch my application, I have the console system a...
You will have to use just an application and not a console application. To do that: Change SubSystem to Windows. You can find it under: Properties ---> Linker ---> System and replace int _tmain(int argc, _TCHAR* argv[]) with int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, in...
6,055,154
6,055,168
C++ - How do I initialize a constructor of a separate class from the constructor of a class?
Basically what I am trying to achieve is to create a local (and private) instance of the class deltaKinematics in the class geneticAlgorithm In the geneticAlgorithm.h file I have: class DeltaKinematics; //class is defined in separate linked files class GeneticAlgorithm { //private DeltaKinematics deltaRobot; ...
Member initializer list: GeneticAlgorithm::GeneticAlgorithm() : deltaRobot(100) { }
6,055,305
6,055,331
platform independent GUI
I want to make GUI for my application. It should work on multiple platforms. I want most of the code to be portable for all the OS (unix, windows, MAC). GTK and GLib looks as a good solution. I want to use native APIs too How to do this all??
Qt may be good for that.
6,055,496
6,057,028
Are multiple ASIO io_services a good thing?
I've begun using Boost.ASIO for some simple network programming, my understanding of the library is not a great deal, so please bear with me and my newbie question. At the moment in my project I only have 1 io_service object. Which use for all the async I/O operations etc. My understanding is that one can create multip...
We use multiple io_service's because some of the components in our application need to run all their worker threads at certain fixed priorities, different for each component. Thus each component is given its own io_service, and each component has its own pool of threads executing run(). Other designs I could think of w...
6,055,541
6,060,161
How to get the automatically calculated font width from a CFont Object?
I'm using a fixed size font ( eg: "Courier New" ). When I initialize the CFont object by calling CFont::CreateFont function, I want to specify only the font height. CFont Font; Font.CreateFont( nFontHeight, 0, 0, 0, 0, false, false, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXE...
Have you tried CDC::GetTextMetrics()? I've never used it, but it seems to be what you're looking for. You can get the average and maximum character width, which I guess should be the same for Courier New.
6,055,648
14,802,635
rotating an object with opticalflow?
I am rather new to C++ and openframeworks. I am beginning to play with manipulating objects using the Lucas Kanade technique. I am having some success with pushing objects around but unfortunately I cannot figure out how to go about rotating them properly or even detect when rotational movement is occurring for that ma...
To compute the 2x3 affine transformation matrix of your motion could be a solution. The affine transformation matrix contains tranlational and rotational movements as far as scaling. If you are using OpenCV than cv::getAffineTransform is what you are looking for where you can directly input the tracked feature points.
6,055,682
6,055,701
Comparing forward and reverse loop for int with one limit as 0
Consider the example with for loop: for(int i = 0; i <= NUM; i++); // forward for(int i = NUM; i >= 0; i--); // reverse I tested this loops with gcc (linux-64). Without any optimization flag, forward loop was faster and with optimization to O3/O4, reverse loop was faster. Somewhere I heard that due to better cache r...
No, there is absolutely no deterministic answer for this. You're looking at two different levels of abstraction. C++ has absolutely nothing to say about what happens under the covers, performance-wise. It specifies a virtual machine which executes C++ code and, while it covers functionality, it does not cover performan...
6,055,755
6,055,782
STL algorithm function name resolution
I'd expect in the example bellow compiler will fail to compile the code, since it doesn't know what is "find()", which defined in std namespace in algorithm header. However this code compiles on RHEL 5.3 with gcc 4.1.2. What do I miss? #include <string> #include <algorithm> int main() { std::string s; find...
This works due to Argument Dependent Lookup. The function-template is searched in the namespace of the arguments types. In this case, the arguments are std::string::iterator, so the function is searched in the namespace std.
6,055,820
6,094,169
Strange net paths in WHOIS
As a self-learning project, I'm implementing a C++ whois client. I'm using a couple of ancient C implementations for reference, e.g. koders.com. One thing puzzles me. As well as the expected path format, like example.com, example.co.uk, 192.0.32.10 or 2620:0:2d0:200::10, the old C implementations accept some other ...
These extra strings are (mostly) for recognising the object types maintained by the Regional Internet Registries, such as RIPE, ARIN, APNIC. Their databases are also accessible via the whois protocol, even though the entries within them are not domain names.
6,055,929
6,056,013
Unit testing framework for C++ that doesn't need to preprocess the code
There are several major unit tests frameworks, but as far as I know all of them needs to process the source code in some way. For example, I am using cxxunit, and it requires the unit tests to be processed using some python script. The problem with this is that it increases the build time. Does anyone know of a unit te...
You could use google test framework. You need just build library source code one time. Then you can create your tests as .cpp files, then compile and link them with gtest and needed project libraries as ordinary c++ sources. Besides that, it is multiplatform.
6,056,014
6,056,338
Some problem with serial programming in vc++ mfc
When I connect my embedded device to my system, I am running my program which will write to the port my embedded is connect and it prints the reply to console. When I connect my device and run this program it is not giving any output. But when I connect my device and use PUTTY to send some commands first and then run m...
Try this... you will probably need to do the code for exceptions (ex: if the response is bigger than 2024) bool SendModemATCommand(const string &strCommand, int iModemPort, string &strRetValue) { bool bRetValue = false; strRetValue = ""; char cBuffer[2024]; HANDLE hCom = NULL; char cComPort[64]...
6,056,047
6,056,084
C++ namespace alias in entire class scope
I expected to be able to use a namespace alias in a class declaration but get a compiler syntax error. struct MyClass { namespace abc = a_big_namespace; void fn() { abc::test(); } }; The only way I can get it to work is to put the alias in every function. void fn() { namespace abc = a_big_names...
Namespace alias in the class definition is illegal, as specified by the language specification. Its allowed in only in namespace scope or function scope. You can make alias at namespace scope. But that will be make permanent alias which can be used from other files as well. But the solution is simple : you can use unn...
6,056,322
6,056,772
How to diagnose ambiguous call to sqrt(int&) in g++ 4.3.4
My code is as follows: #include <cmath> #include <iostream> float foo(float f) { std::cout << "float\n"; return f; } double foo(double d) { std::cout << "double\n"; return d; } int main() { int i = 16; // foo(i); // ambiguous call, of course return (int) std::sqrt(i); } The call in the last ...
This "helpful" Standard Library addition by GCC is non-conforming in C++03, according to [lib.global.functions]/2: A call to a global function signature [described in the Standard Library definition] behaves the same as if the implementation declares no additional global function signatures. Which means that the impl...
6,056,545
6,056,654
how to check that inlining occurred
I would like to massively use inline in my project to speed up performance. As far as I know the compiler might apply inline or not; it is up to the compiler. It is not clear to me what I can do to make this possible, but before going that direction, do you know a way to check that inlinining really occurred or not in ...
Use gcc -Winline to get warnings when an inline function is not inlined. Use __attribute__ ((always_inline)) to force functions to be inlined. Having said that, be warned that you can screw up performance, compile time and get huge code bloat if you use inlining injudiciously.
6,056,607
6,056,709
Problem linking netpbm library
Hi stackoverflow community now I am part of you with my first question. My problem is quite simple: I want to use the netpbm library in a c++ program but can't link. g++ test.cpp -o test -lnetpbm /tmp/ccZsqYHK.o: In function `main': test.cpp:(.text+0x39): undefined reference to ppm_readppm(_IO_FILE*, int*, int*, unsign...
ppm.h is not c++ friendly. Try including it as follows: extern "C" { #include <ppm.h> }
6,057,037
6,072,652
Windows Mobile: automatically copy files on reboot
I have a Java app that runs on a Windows mobile device. At startup the app talks to our server to see if any files need updating and downloads them if they do. If any of the files are dlls they need to be stored in a temp directory and the device is rebooted because they might be currently in use. When the app start...
In the absence of another answer, I have written a simple app to do it and put it in the startup directory. Was pretty easy, just didn't want to reinvent the wheel.
6,057,245
6,057,281
Remove space chars from end of string C++
Possible Duplicate: What's the best way to trim std::string I have a string: std::string foo = "This is a string "; // 4 spaces at end How would I remove the spaces at the end of the string so that it is: "This is a string" // no spaces at end please note this is an example and not a representation of my code. ...
Here you can find a lot of ways to trim the string.
6,057,548
6,057,617
value of a hash map element not printing properly
I insert a pair (key,value) to my hashmap but it seems like it doesn't have the value when trying to print it The thing is i don't know why i can't print the second element in the following code. Let's see some code : .h typedef hash_map<const string, string, strptrhash, strptrequal> StringHashMap; StringHashMa...
What does m_memberNameMap[name] do in the if condition? If the key name doesn't exist in the map, it creates a new slot with that key, and value equal to empty string. That is, the expression m_memberNameMap[name] invokes operator[] which inserts an item equal to string_pair(name, "") to the map if the key name doesn'...
6,057,563
6,057,619
What could go wrong if you don't pass objects by reference into a function
I am trying to teach some students that in the following case you should pass by reference, otherwise the objects will be copied. note: They don't know about copy-constructors yet, so if possible I would not like to mention them in the example. int sumOfSizes(CObject const & a, CObject const & b) { return a.getSize...
As @Space_C0wb0y implied in his comment, the only way this could do something "unexpected" when passing by value is if the copy constructor for CObject did something "unexpected" (such that the local CObject instances were not equivalent (in whatever sense) to the original instances). This in turn would indicate bad d...
6,057,653
6,058,169
Wrapper contains() function for different containers
Inspired by contains(), I want do declare contains(), fitting misc containers. // for std::vector, std::list, .. (1) template<typename C, typename T> bool contains(const C& container, const T& val) { return ::std::find(container.begin(), container.end(), val) != container.end(); } // partial specializat...
(1) Don't add anything to the std namespace (2) As Space_C0wb0y points out, (2) is not a partial specialization, but an overload. I'm not sure if this is standard behaviour, but on VS2008 this is resolved correctly (the overloaded version is used for map). In either case, I think a slighly better version would be: tem...
6,057,668
6,057,698
Linking error in C++
I'm just putting the finishing touches on a project I've been working on to render a scene in OpenGL - I based some of it on some old code I wrote for a Camera class (since I didn't want to have to re-figure out the maths!), however I'd included the Camera class as part of main.cpp before, and I wanted to move it to it...
Maybe you included that definition of moveCamera() in a .cpp file with the "inline" keyword. This may be interpreted that this method is local to the .cpp in which it is defined. Try removing the inline.
6,057,689
6,061,337
StartService takes a very long time on startup
I have a windows service S1 with dependency X. The service is automatic and it starts without any problems. This service starts another service S2 with same dependency X. The problem is that when I call StartService() to start S2, I don't return from the function for about a minute, and only than I start the entrance c...
When do you start the other service S2? You cannot call StartService() until your service has reported a successful start. Is S2 a dependency of S1? If so, just mark it as such and let SCM worry about it.
6,057,696
6,057,798
How to convert fom string to hexadecimal?
I have the following string: s="80". I need to put this in an unsigned char k[]. The unsigned char should look like this: unsigned char k[]={0x38,0x34}, where 0x38=8 and 0x34=0 These are the hexadecimal values for 8 and 0. How to do this? Need some help! Please give some code. Thx I am working on ubuntu c++ code. THX!...
Assuming you want this string converted as ASCII (or UTF-8) it is already in the correct format. std::string s="80"; std::cout << "0x" << std::hex << static_cast<int>(s[0]) << "\n"; std::cout << "0x" << std::hex << static_cast<int>(s[1]) << "\n"; If you want it in an int array, then just copy it: int data[2]; std:...
6,057,893
6,070,524
Extending a vector iterator to access data members of the contained class/structure
So, I have a class that does string manipulation based on metadata attached to each character in the string. Internally, I represent this with a std::vector<CharacterType> where CharacterType contains, among other things, the character in question. This internal representation is useful to me, but at the end of the man...
A few different people suggested that I look into conversion operators, which I must admit I totally forgot about. A conversion operator based solution is considerably cleaner: #include <iostream> #include <vector> #include <string> struct mytype { char c; inline operator char () { return c; } }; int main() {...
6,057,900
6,058,208
Getting errors when trying to compile qt-labs-qt3d in windows with visual studio 2008
Hi i followed the instructions from the sites using Qt 4.7.3 compiled from source : http://doc.qt.nokia.com/qt3d-snapshot/qt3d-building.html and http://www.johanpaul.com/blog/2011/03/compiling-qt3d-for-windows but when compiling the qt3d im getting this error: .\qdeclarativeeffect.cpp(263) : error C2039: 'Options' : is...
It seems this was indeed a known issue for 4.7.2 and has been fixed: https://bugreports.qt-project.org/browse/QTBUG-17872
6,058,014
6,058,068
how to customize the nested class's methods in C++
I have a class A with nested class Inner_vector, class A: { public: class Inner_vector:public Vector { bool append(const class Element& element); }; }; bool A::Inner_vector::append(const class Element& element) { add(element); } Now I want to derive a child class from A and also customize the "app...
In C++, inner classes are unrelated to the classes containing them except for scoping. So you have to derive the base's inner class in the derived class.
6,058,226
6,503,717
How to convert a double to a C# decimal in C++?
Given the reprensentation of decimal I have --you can find it here for instance--, I tried to convert a double this way: explicit Decimal(double n) { DoubleAsQWord doubleAsQWord; doubleAsQWord.doubleValue = n; uint64 val = doubleAsQWord.qWord; const uint64 topBitMask = (int64)(0x1 << 31) << 32; //...
I think you guys will be interested in an implementation of a C++ wrapper to the Intel Decimal Floating-Point Math Library: C++ Decimal Wrapper Class Intel DFP
6,058,248
6,058,289
Passing string through stat() function
I have following code: #include <stdio.h> // For printf() #include <sys/stat.h> // For struct stat and stat() struct stat stResult; if(stat("Filename.txt", &stResult) == 0) { // We have File Attributes // stResult.st_size is the size in bytes (I believe) // It also contains some other inform...
If you are talking about a C++ std::string, you might want to use string myStr = "MyFile.txt"; stat(myStr.c_str(), &stResult) so use the c_str() member-function of your string object in order to get a C string representation.
6,058,509
6,058,715
Operator new overloading in windows
I am trying to replace the global operator new and delete. In Linux this works fine, but in windows( MSVC 10 ), it sometimes allocates using the system version of operator new and then tries to deallocate it using my operator delete. Since i am storing some context information while allocation, my operator delete expec...
Overridding the global new/delete in C++ is a tar baby. Yeah, it looks simple enough, but then you make one exception after another and you keep digging a deeper and deeper hole for yourself. The reason why you're getting 'their new' and 'your delete' is that you're probably using some DLL that's already loaded and 'l...
6,058,654
6,059,608
How do I take the output of one program and use it as the input of another on C++?
I have a program that takes the counts of experiments as command string argument and outputs the sequence of floating numbers. Example: im_7.exe 10 10.41 13.33 8.806 14.95 15.55 13.88 10.13 12.22 9.09 10.45 So, i need to call this program in my program and analyze this sequence of numbers.
If your are on windows then you need to do the following Create a Pipe1 using CreatePipe api of windows. Use this pipe for reading data from STDOUT of the child process. Create a Pipe2 the same way and use that pipe for writing data to the STDIN of the child process. Create the child process and in the startup info pr...
6,058,909
6,059,182
Catching delete of a stack object?
Are there tools to catches deletion of a stack object, how likely that gcc and Visual Studio debug build will break on that event immediately? I deal with big, old projects, so that is not a question on how to write code, but how to detect and fix problems.
Most of the heap implementations are not tolerate to invalid pointers (i.e. when you delete an address which was not returned to you by the heap). Almost for sure standard windows heap, and CRT's heap (implemented by MSVC) cause a debug breakpoint in such a case. You may also replace the implementation of new/delete op...
6,059,105
6,059,375
Retrofitting existing code with a floating point arbitrary precision C++ library, any chance of success?
Let say I have a snippet of code like this: typedef double My_fp_t; My_fp_t my_fun( My_fp_t input ) { // some fp computation, it uses operator+, operator- and so on for type My_fp_t } My_fp_t input = 0.; My_fp_t output = my_fun( input ); Is it possible to retrofit my existing code with a floating point arbitrary pre...
This might be tough. I used a template approach in my PhD thesis code do deal with different numerical types. You might want to take a look at it to see the problems I encountered. The thing is you are fine if all you do with your numbers is use the standard arithmetic operators. However, as soon as you use a square ro...
6,059,175
6,061,290
Looking for example code integrating Qt4 and v4l2 library
As topic , i tried source code from official website ( c language based ) , but not so complete , i'd like to see some examples which can dump an image and transfer to a Qt class , QImage or so. Many thanks.
If I were you, I would have a look at kopete. This is a multiprotocol messaging client designed for kde --which libs relies on Qt--. I know it can use v4l2. Hope that helps. EDIT: even better actually is kapture EDIT 2: or maybe this one v4l2ucp?
6,059,196
6,059,261
Line - Circle intersection test in 3d world?
i have a 3d world where i have several 2d circles laying on the ground facing to the sky. how can i check if a line will intersect one of those circles frop top-to-down? i tried to search but all i get is this kind of intersection test: http://mathworld.wolfram.com/Circle-LineIntersection.html but its not what i need, ...
If you are in a coordinate system, where the ground is given by z = c for c some constant, then you could simply calculate the x, y coordinates of the line for z = c. Now for a circle of origin x0, y0 and radius R, you would simply check if (x - x0)^2 + (y - y0)^2 <= R^2. If this is true, the line intersects the circle...
6,059,260
6,059,322
When is it appropriate to use virtual methods?
I understand that virtual methods allow a derived class to override methods inherited from a base class. When is it appropriate/inappropriate to use virtual methods? It's not always known whether or not a class will be sub classed. Should everything be made virtual, just "in case?" Or will that cause significant ov...
When you design a class you should have a pretty good idea as to whether it represents an interface (in which case you mark the appropriate overrideable methods and destructor virtual) OR it's intended to be used as-is, possibly composing or composed with other objects. In other words your intent for the class should b...
6,059,289
6,069,720
Game screen management
I am working on a screen manager for a miniature game engine, and so far I cannot find a proper solution to managing screen objects without using the 'blob' for each one of the screens. Is blob tolerable in such circumstances where I need a list of renderable objects in one controller?
I would consider using the MVC pattern in this situation. Otherwise, if you're not careful, it's very easy to end up with a bunch of spaghetti code where the screen code is reaching into the game code, and vice versa.
6,059,302
6,059,342
How to check if a file is gzip compressed?
I have a C / C++ program which needs to read in a file that may or may not be gzip compressed. I know we can use gzread() from zlib to read in both compressed and uncompressed files - however, I want to use the zlib functions ONLY if the file is gzip compressed (for performance reasons). So is there any way to programa...
There is a magic number at the beginning of the file. Just read the first two bytes and check if they are equal to 0x1f8b.
6,059,535
6,059,635
Finding a median of a collection of values in c++
Possible Duplicate: Compute Median of Values Stored In Vector - C++? I need to store a collection of values and then have the ability to calculate its median value. What is the best container in c++ to store these values, and how do I find the median? (I might also want to be able to remove specific elements, so I ...
Short of any other specific requirements, you should default to a std::vector. You mention that you want to remove items later; this implies that you may want to consider a std::list instead. To find the median, you can use std::nth_element, asking it to pivot on the N/2-th (or (N-1)/2-th) element. This runs in O(N) ...
6,059,613
6,059,654
tools to visualize an abstract tree
I wonder there are any tools or online tools which one can construct tree just giving datas. ex ; after giving datas, I want get a picture like ; google picture
Look into Graphviz, and its descriptive language DOT.
6,059,731
6,059,888
Extraction of filenames with dirent
Could You tell me, how to put only filenames (without directories) into my vector within following code?: int getDir (string dir, vector<string> &files) { DIR *dp; struct dirent *dirp; if ((dp = opendir(dir.c_str())) == NULL) { cout << "Error (" << errno << ") with " << dir << endl; return ...
Try with this: struct stat eStat; stat(dirp->d_name, &eStat); if(S_ISDIR(eStat.st_mode)) printf("found directory %s\n", dirp->d_name); Better to use S_ISREG in place of S_ISDIR
6,059,838
6,059,961
Calling C++ template function from C#
I have very limited knowledge of C#. My goal is to provide a C++ dll API to my C# co-worker. The dll has to be in C++ for legacy reasons. Question - Can a C++ template function (shown below from VS) be marshaled in C#? class __declspec(dllexport) Foo { public: template <typename T> T* getFoo(T* fooData){return f...
Question - Can a C++ template function (shown below from VS) be marshaled in C#? No. There is no compatible binary interface from C# to C++. You can only call exported C symbols from C#. Theoretically, you could explicitly instantiate the templates in the C++ DLL, which will cause them to get external linkage and ent...
6,059,941
6,060,059
HowTo connect FS Minifilter Driver and my application on Vista & Win7?
Here what I have: the user application - it's MSVC project, service, written on C++ with small Boost & STL (app are using hooks to get users actions) the driver - it's a FS Minifilter Driver, that monitors USB mount/umount actions, and file movements Problem: On XP, this two guys works great together, but when I'm st...
Your driver should expose a virtual device for the user-mode application to open and interact with (often via IOCTLs). This is completely independent of the filesystem device layers you are already working with. When your driver creates this new virtual device, it can set permissions to allow any user to open it, only ...
6,059,970
6,060,049
A tricky OOP problem I never got my head around
Say I have two .cpp files: oranges.cpp and basket.cpp. They have the classes orange and basket, respectively. My main program generates many baskets which in turn generate many oranges. So basically, main will have many objects of Baskets; and baskets will have many objects of Oranges. If I have a function in orange th...
Static functions are almost certainly not the answer here. You would probably need to pass a reference to the "parent" Basket to the Oranges object, which it can then interrogate to find the colour. For example: class Basket { public: void Basket() { Oranges *o = new Oranges(*this); } color getColo...
6,060,163
6,060,189
memcpy function in C++ to Java equivalent
I have in C++ memcpy (&wkpm, (PMSK *)pr_masks + (long)(x - 1), sizeof(PMSK)); where PMSK is a struct. It will be a class in Java. Now assuming that here I am copying the whole chunk of memory into pr_masks i.e creating an additional instance of the PMSK class. How to do this in Java. Example: In a java code at line 2...
In Java you need to either do a shallow clone() of the object or copy every field individually. There is no low level, make one object a copy of another object.
6,060,208
6,061,319
Using boost::serialization greatly increases binary size
I use rather complex data structures (mostly using STL containers) in my app, and serialize them using Boost (v1.34). Whenever I compile with debug symbols (gcc -g), the resulting executable gets huge - around 25 MB. Stripping all the debug symbols reduces the size to ~3 MB. I tried to nail down the cause of the size i...
Put your code with serialization calls to separate modules, compile them to large object files. Use strip --strip-debug on them to remove only this big debugging symbols (which you will definitely need later to debug crashes inside serialization library :) Profit! Link stripped wrappers and unstripped other modules to...
6,060,824
6,060,877
Why can't the template argument be deduced when it is used as template parameter to another template?
What is wrong in this code? #include <map> template<typename T> struct TMap { typedef std::map<T, T> Type; }; template<typename T> T test(typename TMap <T>::Type &tmap_) { return 0.0; } int _tmain(int argc, _TCHAR* argv[]) { TMap<double>::Type tmap; tmap[1.1] = 5.2; double d = test(tmap); //Error: co...
That is non-deducible context. That is why the template argument cannot be deduced by the compiler. Just imagine if you might have specialized TMap as follows: template <> struct TMap<SomeType> { typedef std::map <double, double> Type; }; How would the compiler deduce the type SomeType, given that TMap<SomeType>:...
6,060,836
6,061,343
Running on multiple cores using MPI
I use the present command to submit MPI jobs: mpirun -np no.of processors filename My understanding is that the above command lets me submit to 4 independent processors that communicate via MPI. However, at our setup, each processor has 4 cores which go un-utilized . The questions I had are the following: Is it possi...
So 1 is a question about launching processes, and 2+3 are questions about, basically, performance tuning. Performance tuning can involve substantial work on the underlying code, but you won't need to modify a line of code to do any of this. What I understand from your first question is that you want to modify the dis...
6,060,948
6,061,607
Overriding page replies in QWebView
I'm attempting to intercept a page/form request within Qt's QWebView and respond in some cases with alternative content. QNetworkReply* ngcBrowser::createRequest(Operation operation, const QNetworkRequest& request, QIODevice* ioDevice) { view->page()->setNetworkAccessManager(this); QNetworkReply* respo...
There are many ways of doing this . This is one way. connect(networkAccessManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyReceived(QNetworkReply*))) .... void replyReceived(QNetworkReply* reply) // reply slot { if(reply->request().url().path().endsWith("ajax")) { QByteArray array = reply...
6,061,211
6,061,249
How to make the compiler use the right template specialization?
Consider the following simplified version of my code. I have a template class A, a template function Fill, and a specialization of the function to work with basic types like int or char, and another specialization to work with A: #include <sstream> #include <string> #include <iostream> template<size_t C> class A { pub...
Template specializations are not inferred via where you're assigning the return value to. You'll have to explicitly instantiate the correct version: a12 = Fill<A<12> >("xyz", def); (or whatever it is that you need...)
6,061,352
6,061,749
Creating a custom message/event with Qt
I have an RPC thread that is calling back to me from that thread. I need to somehow inform Qt that it needs to make a function call from the main thread. In straight Windows I could do this by using a custom message and then posting that message to the message queue, e.g., I could create a WM_CALLFUNCTION message and...
In Qt 3, the usual way to communicate with the GUI thread from a non-GUI thread was by posting a custom event to a QObject in the GUI thread. In Qt 4, this still works and can be generalized to the case where one thread needs to communicate with any other thread that has an event loop. To ease programmin...
6,061,364
6,061,411
How can I use GetType() for CheckBox?
I'm currently working with C++ and .NET 1.1 (Don't ask...), and I'd like to check if an object is a CheckBox. GetType seems the obvious choice, but for some reason I can't get it to work like I want. Using GetType() on an instance of a CheckBox works fine, but trying to use Type::GetType("System.Windows.Forms.CheckBox"...
It looks like you're using C++ with managed extensions. If so try the following if (this->checkBox1->GetType() == __typeof(CheckBox)) { ... }
6,061,374
6,061,423
Duplicate last entry when reading a file using fread
Possible Duplicates: Why is this C code buggy? Problem with EOF when determine stream end I'm trying to read a binary file in 4 byte chunks. However the first implementation (shown below) will duplicate the last entry and only the last entry. FILE* f = fopen("test.a", "r+b"); char buffer[4]; while (!feof(f)) { f...
This is because the eof mark is set in the file once nothing can be read from it. This causes the last fread to read "some", but not stablishing the eof mark. Then, the next loop, fread will read nothing, and then cause the eof mark to be set in the file. As fread has not changed the buffer, you have in it the last lin...
6,061,473
6,061,544
Calling C# .NET Service From C++ Application?
I have an old MFC app written in Visual Studio 6. This will at some point be rewritten in C# .NET. However, before then I have to write a couple of new Windows services for the existing application. The others were written in ATL. What I would prefer to do is write these new services in C# .NET so that when the rest of...
Absolutely. You're looking for a feature of .NET called COM-Interop. http://msdn.microsoft.com/en-us/library/kew41ycz%28v=vs.71%29.aspx http://msdn.microsoft.com/en-us/magazine/cc163494.aspx The second link has an ATL example. EDIT: Based on your feedback in the comments, let me expand on this... Ah - you're right a...
6,061,553
6,100,469
C++ Code Executes Only When the Program Is Run From The Terminal
I have a strange bug that appears to happen only when the program isn't executed from the terminal. Here is my project: https://github.com/elliotpotts/Troll/ https://github.com/elliotpotts/Troll/issues/2 Look at the Troll::State::keyPressed() function. For some reason when I run the program from the terminal, everythi...
It turns out it was the IDE causing the problem, thanks for your help anyways, ell :)
6,061,648
6,061,677
Concatenate two string literals
I am reading Accelerated C++ by Koenig. He writes that "the new idea is that we can use + to concatenate a string and a string literal - or, for that matter, two strings (but not two string literals). Fine, this makes sense I suppose. Now onto two separate exercises meant to illuminate this . Are the following definit...
const string message = "Hello" + ",world" + exclam; The + operator has left-to-right associativity, so the equivalent parenthesized expression is: const string message = (("Hello" + ",world") + exclam); As you can see, the two string literals "Hello" and ",world" are "added" first, hence the error. One of the first t...
6,061,780
6,061,950
If condition , doesn't code execute code properly
This code takes a string from a dialog box , and compares it to data in a list,and if succesfull sets the selection on the element from list . The problem i am having is with the if , it works if i only search the first element , if i try to search any other , it just ignore the if condition and goes till the end o the...
You are only ever comparing the first element move advance(seek,i); like this: while(flag) { seek = agenda.first_element(); advance(seek,i); ...
6,062,040
6,191,197
MPI_Isend/Recv- Is there a deadlock?
I have a total of 8 messages being passed on 4 nodes using MPI. I noticed that there were two messages whose arrays did not provide meaningful results. I have copied an excerpt of the code below? These are some related questions I had based on the code/results below: Does the MPI_Isend also require a wait? I am not su...
Yes, All non-blocking calls (MPI_Isend, MPI_Irecv etc) require a matching MPI_Wait. The call is not guaranteed to complete until MPI_Wait is called. You should not change the contents of the buffer until after MPI_Wait returns. https://computing.llnl.gov/tutorials/mpi/ To use SendRecv, same task has to send a message a...
6,062,054
6,062,089
read a specific number of chars from stdin
HI I'm writing a program that acts as a server and has the ability to interact with the user via the terminal. if i read from the stdin i want up to 140 chars. if the user enters more than 140 i would like to take only the first 140 chars and ignore the rest. i try something like the following code: struct timeval time...
Pretty much the only choice is to read the characters and discard them until end-of-line is reached.
6,062,270
6,062,437
Reason for requiring typename in a template definition
Possible Duplicate: Where and why do I have to put “template” and “typename” on dependent names? This is a specific instance of the question: Officially, what is typename for? I am asking for the specific reason that the compiler is NOT aware that the following is a type: #include <set> #include <vector> template<t...
While you've links to a thorough answer, it's a lot to wade through. So - put as simply as I can - the point is that the compiler does indeed know that T is a type as you say, but using that information and even having seen the included source code for std::set, it can't be sure whether the iterator identifier inside ...
6,062,432
6,062,524
Using boost.accumulators to count objects that have a certain attribute set to a value
Here's a snippet of code setting the context to my question (this is C++) enum Gender { Gender_MALE, Gender_FEMALE, Gender_UNKNOWN }; enum Age { Age_CHILD, Age_ADULT, Age_SENIOR, Age_UNKNOWN }; struct Person { int id; Gender gender; Age age; }; std::list<Person> people; After populating the list of people, I w...
Use std::count_if and a suitable predicate. E.g., to find the number of Person objects with an age of Age_ADULT in C++11, std::count_if( people.cbegin(), people.cend(), [](Person const& p){ return p.age == Age_ADULT; } ); For C++03, std::count_if( people.begin(), people.end(), boost::bind(&Pers...
6,062,690
6,062,904
C++ boost logging compile error (linux)
Can anyone tell me what I'm doing wrong? Running this on the console yields the following error: # c++ -I /var/local/boost_1_46_1/ log.cpp -o log -lboost-log log.cpp: In function âvoid init()â: log.cpp:11: error: âboost::loggingâ has not been declared log.cpp:13: error: âboost::fltâ has not been declared log.c...
You need the following namespace redefinitions to use the tutorials: namespace logging = boost::log; namespace sinks = boost::log::sinks; namespace src = boost::log::sources; namespace fmt = boost::log::formatters; namespace flt = boost::log::filters; namespace attrs = boost::log::attributes; namespace keywords = boost...
6,062,862
6,063,608
cocoa touch -- test if object is an objective-C object
Suppose I have an object. Might be an objective-C object; might be a C++ object. Is there a way to test which it is that won't throw any exceptions? EDIT: I'm happy to use any construct that works, including templates if they will do the job.
A friend found this on the Cocoa with Love blog. Apparently, the problem is not trivial.
6,063,112
6,063,187
passing member functions as parameters / c++
I would like to implement, in c++, a class b where it would be possible to do some kind of iteration through a member set encapsulating the type of that iterator. Like: b_object.for_each_x_do(function_f); so function_f would get everyone of the x members and do anything. Let's say: void function_f(x_member_type x){ ...
It should just be: b_inst.foreach_x_do(f); You also need to make f static, not a non-static member method since the original signature for your foreach_x_do function is for a stand-alone function pointer, not a pointer-to-member-function. So i.e., static void f(int x) { }
6,063,113
6,100,956
CMutex::Lock vs. CSingleLock::Lock
I've been tapped to support some legacy code, and I'm seeing some things that cause me to scratch my head in confusion. In some sections of code, I see that a class instance uses a CMutex instance to synchronize method execution. For instance class CClassA : public CObject { public: void DoSomething(); private: ...
In general mutexes can be used to control thread access across processes via a named mutex while critical sections are only for synchronizing thread access in the same process space. Neither of these classes truly get the benefit of RAII without wrapping them because in that case you would never need to explicitly call...
6,063,391
6,063,822
Is it possible to make a shallow copy of very large STL strings?
Good afternoon, We are building a prototype of a deduper. We are using a array of STL strings to store the records to be depuped. The array looks like this: std::string* StringArray = new std::string[NumberDedupeRecords] The records are very large, as large as 160,000,000 bytes. When we try to store a std::string ve...
I think the real answer to your problem is to use a rope - see http://www.sgi.com/tech/stl/Rope.html - std::string is not really designed to be use for very large strings.
6,063,446
6,098,751
Reading Zebra printer status via USB on Ubuntu
After a lot of posts in SO and Google, I could not find an answer to my problem. Most of similar questions are Windows/VB/.Net/C#/Java centric. I need to send an ESC command to a Zebra USB printer (TTP2130) and get the status back using C/C++ . I am able to print fine (with Zebra generic driver set as default printer)...
Found a solution after searching for 'Swecoin'. This is the old manufacturer of Zebra's TTP line of printers. Swecoin on Wikipedia. This guy made a simple and direct app to communicate with TTP printers (ttputil): http://www.rainbow-software.org/linux/ After downloading and compiling, I was able to send commands direct...
6,063,472
6,063,552
Would learning COM with C/C++ help me understand .NET better?
Often when learning about .NET I run into things that hail from the COM world, or C/C++ (handles, gdi, interop, STA/MTA, etc., the list goes on!). Would it be worth my time to go learn how to program in COM with C or C++, thus killing two birds with one stone? Would this deepen my knowledge of developing with .NET? I a...
Learning COM will help you understand certain portions of .NET better, but they are mainly the portions that deal with COM interop. It will not help (much) for general .NET development overall, other than in certain scenarios. That being said, if your primary goal is to learn and be focused in .NET, I would focus on l...
6,063,499
6,063,549
C++ functor templates
Given the following class, which simply maps an internal functor f to a function to be run later: class A { private: int (A::*f)(int); int foo(int x) { return x; } int bar(int x) { return x*2; } public: explicit A(bool foo=true) { f = foo ? &A::foo : &A::bar; } int run(int x) { return (this->*f)(x); } };...
I am not exactly sure what you are trying to achieve, but you may want to look into: Boost.Function - can wrap any kind of callable Boost.Bind - can be used to bind a member function to an instance
6,063,619
6,153,835
CUDA Device To Device transfer expensive
I have written some code to try to swap quadrants of a 2D matrix for FFT purposes, that is stored in a flat array. int leftover = W-dcW; T *temp; T *topHalf; cudaMalloc((void **)&temp, dcW * sizeof(T)); //swap every row, left and right for(int i = 0; i < H; i++) { cudaMemcpy(temp, &d...
I ended up writing a kernel to do the swaps. This was indeed faster than the Device to Device memcpy operations
6,063,888
6,063,982
Can Boost.Spirit be theoretically/practically used to parse C++(0x) (or any other language)?
Is it theoretically up to the task? Can it be done practically and would the resulting parser be used with sufficient performance and output (say, LLVM IR or GCC's gimple) to be integrated in a competing compiler?
No. C++ is too hard to parse for most automatic tools, and in practice usually is parsed by hand written parsers. [Edit 1-Mar-2015: Added 'most' and 'usually'.] Among the hard problems are: A * B; which could be either the definition of a variable B with type A* or just the multiplication of two variables A and B. A ...
6,063,937
6,064,082
How To Pass Handler with Variable Number of Arguments To A Class Using Boost Library If Needed
This question has been haunting me for several days. It looks very simple, but it's very difficult for me to figure it out. Basically, I want to do something like the async_wait function in the following code snippet boost::asio::io_services io; boost::asio::deadline_timer timer(io); timer.expires_from_now(boost::p...
class A { public: A() {} typedef boost::function<void()> Handler; void Do(Handler h) { h(); } }; ... A a; int arg1; std::string arg2; a.Do(&FreeFunctionWithNoArguments); a.Do(boost::bind(&FreeFunctionWithOneArgument, arg1)); a.Do(boost::bind(&FreeFunctionWithTwoArguments, arg1, arg2)); If ...
6,064,057
6,064,275
Help with boost::regex trim
This regex will trim the string at line breaks. I want it to trim both end only and preserve any line breaks in the middle. string s(" Stack \n Overflow "); boost::regex expr("^[ \t]+|[ \t]+$"); std::string fmt(""); cout << boost::regex_replace(s, expr, fmt) << endl;
If you want to make the regular expression match at the beginning and the end of the input string(want to preserve spaces around the in-between \n), \A and \z instead of ^ and $ might meet the purpose. For example: boost::regex expr("\\A[ \t]+|[ \t]+\\z");
6,064,415
6,065,233
How to terminate an application using the HINSTANCE
I am spawning an application from c++ with ShellExecute, so I have the HINSTANCE of the app. How can I close it now using that HINSTANCE? And can I use WaitForSingleObject() to wait for the app to finish?
First of all, an HINSTANCE is of very little use in modern versions of Windows -- but what you have isn't really an HINSTANCE anyway. The return from ShellExecute is really just a value greater than or less than 32, to indicate success or failure respectively. Fortunately, if you use ShellExecuteEx, you can get a proce...
6,064,890
6,065,777
Reading a Linux device with fstream
I'm attempting to get feedback from some hardware that is used over USBTMC and SCPI. I can read and write to the device using /dev/usbtmc0 in a C++ [io]fstream, alternating by reading and writing to send and receive messages. Most commands are terminated by a single newline, so it's easy to tell when the end of a respo...
The problem with using fstream for this is that fstream has internal buffering, there's no 1:1 correlation between device fileOps->read calls and fstream operations. For interacting with device drivers, you really need to use the low-level open, read, write functions from unistd.h and fcntl.h.
6,064,935
6,065,006
TerminateProcess() doesn't close the application
I am trying to use the TerminateProcess to terminate an app launched by ShellExecuteEX like this: SHELLEXECUTEINFO ExecuteInfo; ExecuteInfo.fMask = SEE_MASK_FLAG_NO_UI; /* Odd but true */ ExecuteInfo.hwnd = NULL; ExecuteInfo.cbSize = sizeof(ExecuteInfo); ExecuteInfo.lpVerb = NULL; ExecuteInfo.lpFile = "http://www.micro...
According to MSDN, fMask must be set to SEE_MASK_NOCLOSEPROCESS for .hProcess to get set. I would add a test to see if it is NULL. As a side note I've always had better luck using CreateProcess. Edit: This is how you do it using CreateProcess: PROCESS_INFORMATION pi = {0}; STARTUPINFO si = {0}; si.cb = sizeof(si); si.d...
6,065,332
6,065,640
Pointer to Pointer with Custom Struct
I Have a similar issue like the one listed here pointer-to-a-pointer-to-a-struct-giving-headache my issue is different because i don't want multi instances from LISTOFONES i want Multi instances of ONE's Pointers like class ONE { int id; char *name; }; class LISTOFONES { ONE **pointers; char *n...
If it were me, I would allocate an array of ONE*s thus: pointers = new ONE*[reserve]; I would arrange that the first several members of the pointers array pointed to valid ONE objects. The last remaining members would all be zero (not essential, since they will never be derferenced.) When I needed to grow the array, I...
6,065,463
6,065,712
C++ Timers for a game
I have been looking into different types of timers that i could use for QueryPerformanceCounter() / QueryPerformanceFrequency(), after looking into this a bit more i found an example of someone using the timer class...which has a timer that is vanilla...would this be better to use then the windows one (i am trying to k...
The Windows High Performance Timer has excellent accuracy and reliability compared to other timers. You won't find better for use in a game. If you want to go on other operating systems, then you can worry about that when the time comes- components like the rendering display system, audio, or even input will all need t...
6,065,466
6,065,516
Replace in string iteration (out_of_range)
I wrote a function which percent-encodes a string, as follows: string percent_encode(string str) { string reserved = // gen-delims ":/?#[]@" // sub-delims "!$&'()*+,;=" ; for(string::iterator i = str.begin(); i < str.end(); i++) { int c = *i; // replaces reserved, unreserved non-ascii and...
replace invalidates current iterator, so it may go beyond the end. There are several ways of writing this code right. For example, generating (and returning) a new string would be the easier, and maybe even more efficient (note that replace has to move the rest of the string one position too). Also, playing with update...
6,065,810
6,069,630
How to implement folding with variadic templates
I have an almost working solution. However, it fails to compile some simple cases, and I can't decipher the error message. My current solution: #define AUTO_RETURN( EXPR ) -> decltype( EXPR ) \ { return EXPR; } template< typename BinaryFunc, typename First, typename Second > auto foldl( BinaryFunc&& func, First&& fir...
The problem is that the decltype in the return type of the variadic foldl cannot see the variadic foldl, as it hasn't been fully declared yet, so it cannot recurse to another instantiation of itself. You can do it with a helper struct: template<typename BinaryFunc, typename... Args > struct folder; template<typename B...
6,065,814
6,065,961
Standard compliant custom allocator
Is OK to throw an exception when 0 is passed to allocate method? Thank you. P.S. If n == 0, the return value is unspecified. Does it mean that allocate shouldn't throw an exception? I am inclined to think that if throwing wasn't allowed for n==0, then the standard would clearly spell it out.
All the standard has to say (§20.1.5/2) is that given T – any type X – an Allocator class for type T a – a value of type X& n – a value of type X::size_type, the return value of the expression a.allocate(n) is unspecified if n equals 0. One one hand, given that X::allocate doesn't have any mandated exception specific...
6,065,957
6,066,731
Data structure for topic list of clients
I need a data structure with O(1) add, find, and delete operations for a topic subscribed by a list of clients. Some of the functions it needs to support are: isTopicExists, isClientExists, getClientsForTopic, addClientForTopic, removeClientForTopic, and getTopicsForClient. Given a topic name, a client id that we can a...
A hash map may seem not a bad idea. Its expected complexity is O(1) but a pessimistic scenario with many collisions can get you to O(n) depending on how chaining is implemented. A logarithmic search will be hard to beat here, so I would go for a self-balancing binary search tree, even std::map (red-black tree in most S...
6,066,140
6,068,727
Input buffer structure in an AudioUnit
I've written a simple audiounit that should swap the left and right channels of a stereo source. A ported version of this code worked fine in C for a command-line program that used the BASS library, but I'm having trouble getting the same code to work in Xcode for an audiounit. For a buffer input of, for example, {1, 2...
The reason that this code isn't working is because you are using AudioUnit kernels, which call your plugin to process a single channel of audio data (if I understand correctly). While kernels can be quite convenient in some cases, it's definitely not going to work for a plugin which does interdependent stereo processin...
6,066,214
6,066,226
MT or MD for static release?
In the static release of my application, I do not want the user to need the msvcrt runtime. My application depends on another library that I compile myself. Should this library use multithreaded or multithreaded DLL when compiling it? The library is static compiled. Thanks
VC++'s license agreement prohibits the distribution of debug builds on any computer that doesn't already have VC++ installed, so your only option is to use /MTd or /MDd for debug builds while developing the application and /MT for the release build meant for distribution.
6,066,228
6,066,254
Disallow the explicit copy of data members without user defined ctor
I have a question about copy constructors/copying objects. I have a class that has a few properties that I don't want to be copied. class Action : public Cloneable<Action> { public: //Constructors and other methods are ommitted std::vector<BattleCharacter*> Users; std::vector<ActionTargetTuple> Targets; pr...
The default copy constructor will copy everything, so yes - you will need to implement the copy constructor manually to achieve this. As this replaces the default copy ctor, you will not need to define one for each inherited class (unless you want different behavior).
6,066,273
6,066,299
Pointer into vector, but not into a valarray?
I'm trying to extract a const pointer to part way through an array. I found it works fine when using a vector, but won't compile (VS 2008) when using a valarray. Can somebody explain what the problem is? struct vector_test { std::vector<int> v; const int *pointy(const int i) const { return &(v[i]...
std::valarray<T>::operator [](std::size_t) returns a T&, which will work fine. std::valarray<T>::operator [](std::size_t) const returns a T, which will be an rvalue and consequently cannot have its address taken. Because valarray_test::pointy is itself const, valarray_test::v is treated as const and consequently the co...
6,066,386
6,066,399
Creating recursively std::map of std::maps
I would like to know the best way or better ways of doing something like this: template <int N,typename T,typename X> class MyMap : public map<T,MyMap<N-1,T,X>>{}; template <typename T,typename X> class MyMap<1,T,X> : public map<T,X>{}; int main(int argc, char* argv[]) { MyMap<4,string,double> myMap; myMap["...
Do not inherit. Use a class to create the type with metaprogramming, then use it. I've compiled this code and it should work: #include <map> #include <iostream> template <int N, typename T, typename X> class MyMapCreator { public: typedef ::std::map<T, typename MyMapCreator<N - 1, T, X>::type> type; }; templat...
6,066,430
6,066,470
reading input from stringstream
I'm reading input to a char array of size 5, stringstream ss; char a[5]; if (!ss.read(a, 5)) { // throw exception } if (!ss.get(a, 5)) { // throw exception } Both of these functions seem to work, is there any difference?
ss.read will read 5 bytes from the stream, unless it hits the end of the stream. ss.get will read 4 bytes, unless it hits the delimiter ('\n') or end of the stream. It will also null-terminate the string.
6,066,588
6,066,817
Matrix Multiplication Using win32 threads
I have no idea what's wrong with my code ... It always return zeros in all the elements. A hint of where is the problem would be great :) #include <iostream> #include <stdio.h> #include <cstdlib> #include <ctime> #include <windows.h> using namespace std; int nGlobalCount = 0; int thread_index = 0; int num_of_thr=5; ...
A few things I found while poking about in addition to the other issues noted previously: What are you compiling this with? With VC++ 2010 it "works", as in it outputs non-zeroes, although it complains about the DWORD ThreadIds[num_of_thr]; array declaration with a non-constant array size (I just made num_of_thr a con...
6,066,676
6,066,826
SQL Server 2008, numeric library, c++, LAPACK, memory question
I am trying to send a table of numbers in SQL Server 2008 like: 1att 2att 3att 4att 5att 6att 7att ... attn -------------------------------------------- 565 526 472 527 483 529 476 470 502 497 491 483 488 488 483 496 515 491 467 516 480 477 494 497 478 519 471 488 466 547 498 477 466 475 ...
LAPACK requires the data sent to it, to be in a FORTRAN style (Column-order) array. You won't be able to pass the data directly from SQL to LAPACK but will need to read the data into a column-ordered contiguous memory array, and pass a pointer to the first element of the array to the LAPACK routine of interest. There ...
6,066,736
6,066,768
Multiply defined symbols found?
I made my own library and compiled it as a static library in MSVC using the MD multithreaded DLL runtime. I then compiled my application and included myLib.lib and when I do I get tons of multiply defined symbols relating to MSVCRTLIB, what am I doing wrong? Thanks
The application and all libraries must be compiled with the same settings. Make sure they all use the MD option.
6,066,774
6,066,794
How does file streaming actually work?
I've been wondering for a while now, how exactly does file streaming work? With file streaming, I mean accessing parts of a file without loading the whole file into memory. I (believe to) know that the C++ classes (i|o)fstream do exactly that, but how is it implemented? Is it possible to implement file streaming yourse...
At the lowest level (at least for userland code), you'll use system calls. On UNIX-like platforms, these include: open close read write lseek ...and others. These work by passing around these things called file descriptors. File descriptors are just opaque integers. Inside the operating system, each process has a fil...
6,066,816
6,066,911
Matrix Multiplication Using win32 threads
I have a running code with 9 threads to operate on a 3*3 matrix .. I want to make the number of threads an input from the user .but I can't divide the matrix on for example 4 threads only. Any help would be appreciated. thanks :) #include<iostream> #include <stdio.h> #include <cstdlib> #include <ctime> #include<window...
As some of the comments point out, you won't see any performance boot on a 3x3 matrix. The cost of spawning new threads is too high. In general though, you might try a thread-safe queue of tasks. Essentially, just an ordinary queue with semaphores in the right places. Put all the indexes which still need to be computed...
6,066,847
6,066,875
C++ Identifier "_var" is undefined
I am attempting to learn C++ (currently only know PHP and some C#) and have run into my first issue. I am trying to call a class inside a switch, then use that defined variable after the switch. However, I get the error described in the title. #include <iostream> #include <string> using namespace std; class Hero { pr...
_hero is defined only within the scope of that switch statement. You need to create objects in the same or higher up scope that you'll be using them. One way you can get around this is define a pointer to Hero before the switch (initializing to null) and then set it to a value inside the switch. For instance: Wizard *_...