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,603,446
6,603,503
how to call a thread member function from main ( )
I'm getting errors while compiling a program that uses threads. Here is the part that is causing problems.It would be nice if anybody told me if I'm calling the thread function in the right way . In main.cpp: int main() { WishList w; boost::thread thrd(&w.show_list); thrd.join(); } In another_file.cpp: cl...
The syntax to take the address of a member function is &ClassName::FunctionName, so it should be &WishList::show_list, but now you need an object to call the function pointer on. Best (and easiest) is to use boost::bind: #include <boost/bind.hpp> WishList w; boost::thread t(boost::bind(&WishList::show_list, &w));
6,603,615
6,603,689
What C++ library can I use to convert a PDF to an image on windows?
I am working on a project in which I need to analyze images; the primary source of these images is the webcam, but recently we've been ask to add support for uploaded files and scanners. This is fine, for the most part, except they'd like us to be able to use documents in PDF format. I need a raw pixel bitmap for the ...
ImageMagick. Far and away the best library for reading and writing as many formats as possible http://www.imagemagick.org/script/index.php
6,603,644
6,603,741
Finding where std::out_of_range is thrown by std::vector.at()
Normally I would leave it unhandled and the debugger (gdb, Eclipse CDT) would show me the call stack. Unfortunately the code is being called by a third party library which absorbs all exceptions. I can catch the exception before the third party library however I cannot see the call stack (stack-unwinding?). How can I f...
Would catchpoints help? You can break whenever an exception is thrown by entering the catch throw command in gdb. In Eclipse, you can do this through the gdb console. See this question.
6,603,670
6,613,205
Switched from Visual Studio 2008 to Visual Studio 2010 and unable to link to boost filesystem now
I just switched from Visual Studio 2008 to Visual Studio 2010 and one of my projects is now getting a linker error: LINK: fatal error LNK1104: cannot open file 'libboost_filesystem-vc90-mt-gd-1_46_1.lib' I did rebuild boost and I see the vc10 libraries in the lib folder, but I can't figure out why/how it's still refere...
After I updated to Visual Studio 2010 Service Pack 1 the linker issues went away. BUilding boost with the msvc flag or the msvc-10.0 flag resulted in the same output, so that had no effect on the issue. Additionally, I had to remove the _ITERATOR_DEBUG_LEVEL macro because it was causing a mismatch when linking (Linker ...
6,603,696
6,644,176
How do I use overloaded functions with default arguments in algorithms?
I know the answer to the frequently-asked How do I specify a pointer to an overloaded function?: Either with assignment or with a cast, and every other C++ tutorial uppercases a string like this (give or take static_cast): transform(in.begin(), in.end(), back_inserter(out), (int(*)(int)) std::toupper); Or like this: i...
It's funny, I was doing something similar. The best way I found to do it was using lambdas as follows, because otherwise, you have to use a typedef to get the right overload and a std::bind to get rid of the locale, or not use the locale. However, this works much more cleanly: static const std::locale loc; transform(in...
6,603,843
6,603,947
Drawing Text Using OpenGL and Allegro 5
How can I draw 2d text using openGL and Allegro 5 in C++? I want to be able to specify a font file to load, and not have to put all the characters into an image file by hand.
Use the Allegro 5 font addon.
6,603,905
6,604,618
Use two different versions of a .lib file in one C++ project?
I'm working on a Volume Shadow Copy program. I have just found out that I need to use a different set of .h files (vsbackup.h) and associated .lib files (vssapi.lib) to compile the project for Windows XP (in comparison to Vista and 7). This is due to a series of subtle changes in the .h files: in XP, a call such as Cre...
If you need to work with two different versions of the dll (because if I understood correctly the problem lies there, the different lib/headers are just the tip of the iceberg) you should dynamically load it with LoadLibrary, check the presence of the entrypoints you need with GetProcAddress and call the functions you ...
6,604,022
6,604,256
Exposing an STL Queue to Lua via Luabind
I'm attempting to replace an existing implementation of a queue class written in Lua with the STL Queue class. I'm not sure why this is failing, or how to approach fixing it. Below is some sample code that exhibits the same behavior, along with the error output. Thanks in advance! #include <luabind/luabind.hpp> #inclu...
Most likely, you have an overloaded function in your queue implementation. Thus, when you take the address, the compiler doesn't know what to do because you could mean any overloaded function.
6,604,136
6,604,163
Initializing with a subclass's ctor
struct A { B b; A(int x):b(x){} A(int x, float g) // how to implement this? I want to init b as a C. }; struct B { enum {e_c, e_d} type; int i; B(int i_):i(i_){} }; struct C : public B { float f; C(int i_, float f_):B(i),f(f_){} }; struct D : public B { double ff; D(int i_, doub...
Your example is a bit confused. But maybe you want a pointer? struct A { B *b; A(int x):b(new B(x)) {} A(int x, float g):b(new C(x,g)) {} ~A() { delete b; } // Very important! }; Note that if you do this, B must have a virtual destructor. You will also need to think about what it means to copy an A o...
6,604,372
6,604,444
How do I pass an object to the CreateThread function?
I want to pass an object of a class as argument to the CreateThread function. The object is created this way in main: Connection *connection = new Bluetooth(); Brick *nxt = new Brick(connection); The function that I pass to CreateThread is: DWORD WINAPI recieveFunct(Brick nxt) Finally, CreateThread is called in main:...
You need to cast nxt to LPVOID, not HANDLE. MSDN says "LPVOID lpParameter [in, optional] - A pointer to a variable to be passed to the thread." This design pattern for passing data to a callback function or thread is commonly called a "user data" pointer. http://msdn.microsoft.com/en-us/library/ms682453%28v=vs.85%29.a...
6,604,647
6,604,678
How to add two pointers?
How to add parameterB and pictureName? I got an error that says: '+': cannot add two pointers. CString parameterA = _T("\"") + mycustompath + _T("identify.exe\""); CString parameterB = _T(" -format \"%w\" ") + _T("\"") + mycustompath; CString parameterC = parameterB + pictureName + _T("\"");
if you replace all _T("...") with CString( _T("...") ) it will work 100%
6,604,881
6,606,270
Mocking the C++ Standard Library
I'm unit testing a class in C++ and some of the public methods call private ones. I know convention is to test the public interface, but the classes' functionality depends on how these private methods in turn invoke other classes and their methods. This is similar to the public interface in the sense that no matter w...
If you really wish to mock the standard library then the easiest (possibly only) approach is to instrument your code correctly. That is, instead of using the headers and std namespace directly you'll have to use an intermediary name. So invent a namespace, call it mstd. In your mocked mode this will be your mock namesp...
6,604,911
6,604,949
Is it possible to create a function pointer to the a function's `new` operator/constructor?
If I were to wanted to parameterize creating an object, I could of course make a function which called new on a particular class and passed out a pointer. I am wondering if it's possible to skip that step and pass a function pointer to the new operator itself.
boost::lambda provides function wrappers for new and delete. These can be used to easily convert an new call into a function object.
6,605,147
6,610,890
Get printf to ignore the negative sign on values of zero
I'm trying to write a (mostly)* C program that sorts numerical results and eliminates duplicates. The results are stored as STRUCTS that contain a string, an integer, and 4 doubles. The doubles are what is relevant for determining if two results are duplicates. To do this, I sprintf a string using the 4 doubles to some...
#include <string> #define PRECISION 5 #define LIMIT 5e-6 std::string string_rep (double x) { char buf[32]; double xtrunc = ((x > -LIMIT) && (x < LIMIT)) ? 0.0 : x; std::sprintf (buf, "%.*f", PRECISION, xtrunc); return std::string(buf); } std::string make_key (double x, double y, double z, double w) { ...
6,605,234
6,605,345
loop through hash_map using iterator in multithreaded program
Linux GCC: I have a hash_map H, and a function F that using an iterator to loop through H, the problem is that function F can be executed in multithreaded mode. I don't know why it's working not stable, it seems that iterator is not safe in multi-threaded program. Any idea? MY_HASH::iterator endIter = m_hash.end(); ...
I can't see that the hash iteration would be having problems, but I suspect assigning to pList->pData[i] is where your multi-threading issue exists.
6,605,259
6,605,334
understanding RegOpenKeyExA parameters
I was taking a look at some disassembly and I found the following section :- push eax push 0F003Fh push ebx push ecx push 80000002h mov [esp+70h+var_4], ebx call ds:RegOpenKeyExA In order to understand the parameters I look at the documentation of the API call here. The possible values for hkey seem to be HKEY_CLASSE...
http://www.serverwatch.com/tutorials/article.php/1476831/Managing-Windows-Registry-with-Scripting-Part-1.htm Const HKEY_CLASSES_ROOT = &H80000000 Const HKEY_CURRENT_USER = &H80000001 Const HKEY_LOCAL_MACHINE = &H80000002 Const HKEY_USERS = &H80000003 Const HKEY_CURRENT_CONFIG = &H80000005 though yo...
6,605,282
6,605,305
How can I check if a string has special characters in C++ effectively?
I am trying to find if there is better way to check if the string has special characters. In my case, anything other than alphanumeric and a '_' is considered a special character. Currently, I have a string that contains special characters such as std::string = "!@#$%^&". I then use the std::find_first_of () algorithm ...
Try: std::string x(/*Load*/); if (x.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_") != std::string::npos) { std::cerr << "Error\n"; } Or try boost regular expressions: // Note: \w matches any word character `alphanumeric plus "_"` boost::regex test("\w+", re,boost::regex::per...
6,605,556
6,605,638
Are synchronization objects cacheable?
I am new to multithreading world and started getting into it. I found threading requires synchronization. Volatile is no more a reliable thing. I would like to know if synchronization object are cacheable by compiler or at any stage? Platform/languages used : c++, win32, Windows In c++, volatile keyword is used for obj...
I'm not sure I follow your question: compiler cache has almost nothing to do with multithreading. The only thing that a compiler cache would do is to increase your compilation speed by caching previous compilations. Synchronization objects can be "cached" since they're any arbitrary object that you've decided to use fo...
6,605,706
6,605,747
how to exhaust memory?
It might look silly, but I'm kind of confused about this now. Why this program won't consume all the memory? For example: I have the following program running in a Linux(2G RAM) terminal, #include <iostream> #include <cmath> using namespace std; int main() { cout<<sizeof(int*)<<endl; for(int i=0; ...
Your calculations seem suspect. 220 = 1,048,576 211 = 2,048 To allocate a billion integers, try 230. Note that your vector<int*> will take a significant amount of space (at least as much as the integers you're allocating). To simply exhaust memory, you don't need that at all. You can call new int(i) and throw away the ...
6,605,754
6,617,896
building boost on linux
using the instructions at http://www.boost.org/doc/libs/1_46_1/more/getting_started/unix-variants.html I am at the instructions at ./bjam install Just received the error "skipped 831 targets" I am pretty sure something is wrong. Anyone done this before on Ubuntu? Can any one help me?
I highly recommend you to use Personal Package Archives (PPAs) if you're on Ubuntu. This one provides the absolute latest bleeding edge versions of boost, currently 1.47, that works great for my development. To add this archive to your package database just do sudo add-apt-repository ppa:purplekarrot/ppa; sudo apt-get ...
6,605,815
6,607,352
How do I set up a metatable to inherit from another metatable while at the same time changing the userdata to another type?
This is something I want to do in C++ using the Lua C API. I'm trying to figure out a good way to make userdata derive from a base userdata object. I want to be able to do this: local item = me:GetCurrentItem() print(item:GetPos()) instead of: local item = me:GetCurrentItem() print(item:GetBaseObject():GetPos()) In ...
The obvious solution would be defining an item:GetPos() function that does the redirect. function Item:GetPos() return self:GetBaseObject():GetPos() end Where Item is the item's metatable. This is as efficient as making changes on the metatable, and less problematic. EDIT: I can help you a bit with the repetitivenes...
6,605,865
6,606,007
c++ getline cin issue
while (true) { int read = recvData(clientSocket, buf, sizeof(buf)); if(read == SOCKET_ERROR) { cout<<"Connection with the server is lost. Do you want to exit?" << endl; string input; getline(cin,input); if(input == "yes") cout<<"test"; } if(read == SHOW ...
Well, you don't seem to have any way of exiting the loop if you enter yes, it simply prints test and continues on its merry way, trying to read more data. If you mean that it's not printing test the first time you enter yes then you need to temporarily change: getline(cin,input); to: getline (cin, input); cout << "["...
6,606,259
6,775,527
how can i verify the self signed certificate using openssl library in C++?
i need to verify the X509 v3 certificate .the Certificate is self signed so i have the private key and public key with me . I tried ki=X509_verify(Cert,X509_get_pubkey(Cert)); i always getting the Ki = -1 . can any one tell me how to do this verification.
I am answering my own question. before call X509_verify(,) function OpenSSL_add_all_digests(); this function set the digests algorithm in the local table which is used internally for verification.
6,606,496
6,607,670
Design a Multidimensional Array in C++
I want to design a C++ class for multidimensional arrays. By multidimensional I mean 1d, 2d, 3d, etc. The class supports element by element addition and scalar multiplication operators. Assume A and B are instances of the class (of the same size & dimension). I'd like to use the objects in expressions like this: C = A ...
This question should probably be in Code Review rather than here. But some things on the design: It is usually not a good idea to manage memory manually, you should prefer using existing containers instead of dynamically allocated arrays. The fact that the constructor acquires ownership of the passed in pointer is not ...
6,606,657
6,606,701
Why not have all the functions as virtual in C++?
I know that virtual functions have an overhead of dereferencing to call a method. But I guess with modern architectural speed it is almost negligible. Is there any particular reason why all functions in C++ are not virtual as in Java? From my knowledge, defining a function virtual in a base class is sufficient/necess...
There are good reasons for controlling which methods are virtual beyond performance. While I don't actually make most of my methods final in Java, I probably should... unless a method is designed to be overridden, it probably shouldn't be virtual IMO. Designing for inheritance can be tricky - in particular it means you...
6,606,884
6,607,371
Setting Console to Maximized in Dev C++
Possible Duplicate: Changing the width of a Windows console window? Im writing a simple brick breaker program. How do I maximize the console window, when the program starts. #include <iostream> #include <windows.h> #include <algorithm> #include <conio.h> #define _WIN32_WINNT 0x500 using namespace std; int lives = 2;...
Call the SetConsoleDisplayMode() function with the CONSOLE_FULLSCREEN_MODE flag. [If you want to make the window maximise but not go into full screen mode then it is a lot more complicated because you have to calculate how many columns and rows will exactly fit the screen at the current screen resolution, taking into a...
6,607,138
6,607,398
How much of an increase in size do inline functions cause?
I have recently started making a C++ Wrapper of GTK+ (Nothing special, just wrapping everything into C++ classes for easy development, to be used in-house) and to cause minimum performance bloat to the already slow Gtk+ I used inline functions almost everywhere. Take a look at a few class functions... class Widget : pu...
I strongly suspect you're comparing apples to oranges. Did you compiler with exactly the same compiler, the same compile flags, and making an application with the exact same functionality? If so, disassemble the executable, and see what the extra code is. My guess is that it's some one-off library code used to support ...
6,607,160
6,607,244
Empty array declaration - strange compiler behavior
I've found a strange looking piece of code in a project I have to maintain. There's an empty array member of a class which doesn't lead to an compiler error. I've tested some variations of such a code with MSVC 10.0: template<class T> struct A { int i[]; }; // warning C4200: nonstandard extension used : zero-sized ...
EDIT: your doubt is explained by the definition of the extension to the language, which allows for zero-sized arrays at the end of structs/unions. I have not tried it, but if you declare another member after the zero-sized array, it should fail. so, if you allocate a variable on the stack, you have to know its size; th...
6,607,193
7,359,289
Is it possible to develop an Entity Layer with ANSI C/C++ or Embedded C to be used both in Android & iPhone platforms?
I need to create a common entity layer for my mobile phone application developments.(especially iPhone and Android platforms).Later on I want to develop some parts of business logic and interfaces with specific tools /languages used to develop for those two platforms. (I've been searching about cross mobile frameworks ...
By using ANSI C/C++, i.e. standard C/C++ without extensions, it will make an easier porting, but it also depends on the libraries (libc version an so on). With Android you can either use the JNI or code a native activity, but obviously that isn't portable and the idea of using native code is performance, not portabilit...
6,607,207
6,610,820
Android NDK with C++ Graphics Engine
I would like to use the C++ Graphics Engine (Ogre3D) I am familiar with to write some games for Droid (I just cannot get used to Java) and there are plenty of write ups on how to build the applications. However, I have been unable to get an answered at all concerning input. Does the NDK provide the Droid functionality ...
What NDK provides is only the lowest part of frame buffer processing in C with available casting from java objects using jini. IMO you should wait for a ogre port to android (which can never happen) or die trying to write it.
6,607,410
6,607,469
Understanding "Buffer Security Check /GS" compiler option in MSVC++
I was recently surprised to note that compiling with /GS (Enable buffer security check) in MSVC++ 2010 seems to have a non-negligible effect on run-time performance in some cases. Has anyone else had this experience?? For a large scientific-style application (a mesh generation library) it seems that compiling with /GS-...
/GS adds code that tries to detect if a write overrun or similar stack attack has happend during a function, and to stop execution after a write overrun. The patterns that it aims to find are ones that have been seen in real-world attacks. There are a bunch of real world security bulletins that would not have happened ...
6,607,627
6,608,066
Bitmask switch statement
I have this code in a section of my project: enum myEnum { invalid = -1, val1 = 1, val2 = 2, val3 = 4 }; int bitmask = val1 | val3; if(bitmask & val1) ... if(bitmask & val2) ... if(bitmask & val3) ... This is fine, and it works perfectly, but i've always wondered if it could be done with ...
I see several problems: it adds preprocessor cruft with no real benefit it adds a lot of slow code (shifts, loops, tests) it prevents you from adding special cases such as "if bit 2 is on and bit 3 is off" (if ((bitmask & (val2 | val3)) == val2)) the compiler will miss almost every possibility to optimise the generate...
6,607,656
6,610,397
QT special comments //: //[num] etc
What means this special comments in qt examples folder? I know about "//:" this is a comment than would be taken to a translation program if the next line contains tr(""). The code between //[] seems to be taken to the generated html documentation. Is there a document with full description of special comments?
Qt uses Doxygen Special Commands in it's code comments. [Okay, to be correct, Doxygen extends Qt's comment special commands.] The special commands are used to control the generation of the documentation when it is run on the code. The Trolls who maintain Qt have their own tool they use to generate documents from the...
6,607,730
6,608,024
"Unable to find an entry point" exception when trying to import a native DLL in C#
I wanted to use a native Dll in my C# .net application as this: public const int WFSDDESCRIPTION_LEN = 256; public const int WFSDSYSSTATUS_LEN = 256; [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] public struct LPWFSVERSION { [MarshalAs(UnmanagedType.U4, SizeConst = 4)] int WVersion; ...
35 22 00004FA0 WFSStartUp That's Up, not UP.
6,607,762
6,607,988
C++ Subpattern Matching
can anyone please show me an example about using regex (regex.h) in C/C++ to search and/or extracting subpattern in a regex. in javascript, it will be something like this, var str = "the string contains 123 dots and 344 chars"; var r = /the string contains ([0-9].*?) dots and ([0-9].*?) chars/; var res = r.exec(str); ...
There is no regex.h in standard C or standard C++, so I'm assuming you mean the POSIX regular expression library. C example: char const *str = "the string contains 123 dots and 344 chars"; char const *re_str = "the string contains ([0-9].*?) dots and ([0-9].*?) chars"; regex_t compiled; regmatch_t *groups; regcomp(&co...
6,607,803
6,607,868
C++, Functors, specific task/scenario, mapping user input to functions
I already know the basics about functors, how they are created and so on. I now have a specific code that would probably benefit from being converted to functors: It's about a console input. If the user enters text and presses enter than it tries to execute the entered text as a command. Currently the available command...
I would suggest using a std::map<std::string, boost::function<void(std::string)> >. Or, if you have access to a C++0x standard library, you can use std::function instead of boost::function. A boost/std::function is a callable object that can store anything that is callable with the function type you specify. So the use...
6,607,842
6,607,901
What else does the condition operator in C++ do for me?
I have got a strange compile error while using condition operator. a,b are int value, and the following expression get compile error. (a>b)?( std::cout << a ) : ( b=MAX ); 16 (b <unknown operator> 5)' (a>b)?( a=MAX ) : ( std::cout<<b ); 16 (&std::cout)->std::basic_ostream<_CharT, _Traits>::operator<< [with _CharT ...
The conditional operator must always return the same type. In your first example, (a > b) ? (std::cout << a) : (b = MAX); the first branch yields the type std::ostream and the second branch yields the type of b (which is likely an integer, given its context). Your second example, (a > b) ? (std::cout << a) : (std::cou...
6,608,212
6,610,738
permutations of N balls in M boxes in C++
I asked a question last week about permutations in C++ (List of combinations of N balls in M boxes in C++). The answers have helped me a lot but my problem has now changed. What i would like to do is a translation from this python function to C++, keeping the same order in the result : def combinations_with_replacemen...
This C++ code seems to have the same results as your python sample. It is far from the perfect one, still you could understand the algorithm and even use this implementation. #include <deque> typedef std::deque<size_t> BoxList; class Generator { size_t boxNum, ballNum, ownBox; Generator* recursive; public: ...
6,608,366
6,608,392
Question about Types Conformity in C++?
I am reading some C++ text and got the following code: class A { }; class B : public A { }; void main() { A* p1 = new B; // B may be larger than A :OK [Line 1] B* p2 = new A; // B may be larger than A :Not OK [Line 2] } I have 2 questions: I do not understand what the author mean by commenting in Line 1 and Li...
Well, "larger" is not the key here. The real problem is "is a" relationship. Any object of class B is also of type class A (class B is also class A due to inheritance), so the first line is okay (the pointer to class A can just as well point to an object of class B), but the inverse is not true (class A is not class B ...
6,608,511
6,608,627
Data structure/Container choice
I have the following scenario: Data from multiple video files needs to be held in a data structure/collection. A video file can have 1 to many video streams. Each stream has a field and value pair. For example: Video1: Stream1: format mpeg bitrate 700kb/s resolution 1024x764 Stream2: format mpeg ...
Why not write classes as you need? class Stream { Format format; Resolution res; Bitrate br; }; class Video { QVector<Stream> v_stream; }; class VideoContainer { QVector<Video> v_video; };
6,608,569
8,027,379
can cmake and netbeans play nice?
I'm working on a big project, some might say awesome. The project is being developed in c++ with cmake and netbeans. Everything is working fine except from the fact that every time I do updates to the project, add or remove source files, netbeans runs cmake and adds a new project to 'projects' list. This is somewhat an...
Good news! As of NetBeans 6.8, CMake is handled gracefully, just like any other configure script: Make a new "C/C++ Application from existing sources". Specify the directory of the project (where CMakeLists.txt resides). In the "Select configuration mode", select "Automatic". And NetBeans will run cmake to build the ...
6,608,697
6,646,422
Not sure how to add opencv library to CMakeLists.txt
I hope someone can help me. I have a simple CMakeLists.txt in order to build my project on Ubuntu. I'm using CMake 2.8.1 and at the moment this is the code: cmake_minimum_required(VERSION 2.4.6) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} /home/user/workspace) include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake) # Set ...
#include "opencv2\opencv.hpp" #include "opencv2\highgui\highgui.hpp" #include "opencv2\imgproc\imgproc.hpp" the include files above are included in the vision_opencv in ROS. so to include it, add the opencv dependency in the manifest file. That would help.
6,608,835
6,614,439
Doubts using an object pool
I'm thinking in use a boost::object_pool, but the types of objects to store are all in the same hierarchy. My question is how do I need to store and use the pool to convert each object into the desired type. My guest that store the ancestor as a type of the pool, then convert the returned object with a dinamyc cast to ...
To store polymorphic objects, the idiomatic solution is to store pointers of a base class in a value based container. Your current solution of storing polymorphic objects by value does not work because it suffers from slicing. The boost object pool is no more than a fancy allocator and deallocator, it does not provide ...
6,608,942
6,609,492
How can CString be passed to format string %s?
class MyString { public: MyString(const std::wstring& s2) { s = s2; } operator LPCWSTR() const { return s.c_str(); } private: std::wstring s; }; int _tmain(int argc, _TCHAR* argv[]) { MyString s = L"MyString"; CStringW cstring = L"CString"; wprintf(L"%s\n", (LPC...
CString is specifically designed such that it only contains a pointer that points to the string data in a buffer class. When passed by value to printf it will be treated as a pointer when seeing the "%s" in the format string. It originally just happened to work with printf by chance, but this has later been kept as par...
6,608,964
6,609,006
C++ char/string reading problem
Again, I'm trying to make a simple program. It will read some kind of board, at the size of RxC. Each items on the board are letters, separated with spaces. This is a sample board: A B C D E F G H I After that, it will read an integer N, and for next N lines, read a string and process them one by one based on the g...
In addition to the problems already noted by others, you haven't allocated any memory for tes - it's just a dangling pointer. Change: char *tes; to, e.g.: char tes[80];
6,609,205
6,611,958
boost::serialization to serialize only the keys of a map
I have a class with a map, and I want to serialize the class using boost serialize. std::map<int, ComplicatedThing> stuff; ComplicatedThing is derivable just by knowing the int. I want to serialize this efficiently. One way (ick, but works) is to make a vector of the keys and serialize the vector. // illustrative, n...
you can serialize it as list of ints (I don't mean std::list) instead of serializing it as a container (map or vector). fist write number of elements and then them one by one, deserizalize accordingly. it's 10 mins task. if you need this solution in many places, wrap map in your class and define serialization for it
6,609,271
6,609,319
How to get intellisense for C++ in eclipse while developing for android?
I am developing for android using eclipse and android's plug-in for eclipse. I am getting proper intellisense for Java code. The application I am developing consists of both Java and C++ code. How can I get intellisense for C++ in this environment. Thanks
Try downloading the C Developement Tools for eclipse (CDT). The update site can be found here. This module provides syntax higlighting and code completion for C/C++ and works fine for me. EDIT: Sorry, the above link is dependent on my eclipse version. Here you can find CDT distributions for all other eclipse versions.
6,609,337
6,609,511
Why might std::bind1st be considered "almost unusable"?
During a conversation on boost::bind, it was noted that std::bind1st exists in C++03, but that it is "almost unusable". I can't find anything solid to back this up. The boost::bind documentation says: boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary f...
If we look at C++03 20.3.6.1 and 20.3.6.2, then we see that for the functor argument to bind1st we have a requirement of three typedefs (for the result type, first and second argument), and that the resulting operator only takes one argument. This means that we cannot just use bind1st easily on plain function pointers ...
6,609,412
6,609,467
What is the meaning of 6E 00 when I send a command to a SmartCard
I try to access a SmartCard via C++. I got already the Connection and the CardHandle. But when I send an APDU Command via SCardTransmit, i'll get 6E 00 as the answer from the card. No matter which APDU Command i send. Everytime 6E 00. For Example: FF CA FA 00 00 (Card's ATR - Answer To Reset) or FF CA FF 82 00 (Produ...
According to ISO 7816-4 0x6E00 means "Class not supported". Are you using the correct CLA value in the APDU? The class (CLA) byte is usually 0x00, 0xA0, 0xC0 or 0xF0 and sometimes masked with 0x0C that indicates Secure Messaging on some cards. AFAIK, the only invalid CLA value is 0xFF. But this varies from one card to...
6,609,676
6,609,815
Is it possible to use type_traits to differentiate between char & wchar_t?
I am trying to write a function that can handle both char & wchar_t using the type_traits feature of C++0x. Yes, I know how to do it without type_traits, but I want to do it using type_traits for better understanding of the feature. template <typename T> void SplitIt(T* base, T* ext, const std::basic_string<T>& fullFil...
I think there's a is_same property, so SplitIt(base, ext, fullFilePath, is_same<T, char>()); should work.
6,609,968
6,613,117
Real life examples of xvalues, glvalues, and prvalues?
I was wondering if anyone could tell or explain some real life examples of xvalues, glvalues, and prvalues?. I have read a similar question : What are rvalues, lvalues, xvalues, glvalues, and prvalues? but I did not understand what everyone meant. Can anyone explain in what cases these values are important and when one...
Consider the following class: class Foo { std::string name; public: Foo(std::string some_name) : name(std::move(some_name)) { } std::string& original_name() { return name; } std::string copy_of_name() const { return name; } }; The expression some_foo.copy_of_...
6,610,046
6,610,165
std::function and std::bind: what are they, and when should they be used?
I know what functors are and when to use them with std algorithms, but I haven't understood what Stroustrup says about them in the C++11 FAQ. Can anyone explain what std::bind and std::function are, when they should be used, and give some examples for newbies?
std::bind is for partial function application. That is, suppose you have a function object f which takes 3 arguments: f(a,b,c); You want a new function object which only takes two arguments, defined as: g(a,b) := f(a, 4, b); g is a "partial application" of the function f: the middle argument has already been specifie...
6,610,548
6,611,018
std::atoll with VC++
I have been using std::atoll from cstdlib to convert a string to an int64_t with gcc. That function does not seem to be available on the Windows toolchain (using Visual Studio Express 2010). What is the best alternative? I am also interested in converting strings to uint64_t. Integer definitions taken from cstdint.
MSVC have _atoi64 and similar functions, see here For unsigned 64 bit types, see _strtoui64
6,610,839
6,611,204
GCC 3.42 and VC2008 treat std::transform differently, take a reference or a copy of the functor?
I have Googled this functor-related topic, and it seems that people would generally say that the Standard Library will take a functor as a copy by default. Many examples have been found, and this is true for std::for_each. GCC and VC2008 compilers have yielded the same result: both take a copy of the functor. But for s...
The result seems to suggest that GCC takes MyFunctor as a reference while vc2008 takes it as a copy You cannot infer this from your results. We have things like "copy elisions". The C++ standard explicitely allows the compiler to optimize unnecessary copies away in certain cases. It is entirely possible that libstdc+...
6,611,030
6,611,092
C++, ternary operator, std::cout
How to write the following condition with a ternary operator using C++ int condition1, condition2, condition3; int / double result; //int or double .... std::cout << ( condition1: result1 : "Error" ) << ( condition2: result2 : "Error" ) << ( condition3: result3 : "Error")...;
Depends on what type is result1, result2 etc. expressionC ? expression1 : expression2 isn't valid for all types of expression1 and expression2. They must necessarily be convertible to a common type, roughly speaking (exact rules and exceptions can be read in the standard). Now, if results are strings, then you do it li...
6,611,157
6,611,556
Function to return SQL query into a vector<double> in C++
I have a query in T-SQL which returns 300 records. Each record has 2 columns (date, int) What is the easiest way in C++ to put all the dates in one vector and all the integers in another one? I would like to do it in a function.
It's hard to provide full code without knowing your SQL client library - this affects how you populate the vectors, but basically you loop through the rows read from the DB doing push_back on your two vectors for the values retrieved in each row. The main question is how are you going to handle the returned parameter...
6,611,158
6,611,257
C++ templated class and init in constructor
I have a templated class, Foo : template <class A, class B> class Foo { public: Foo(A &aInstance); private: Attr<Foo> _attr; }; Then I have another templated class called Attr which is an attribute of my Foo class and which takes as template parameter the Foo class itself. template <class C> class Attr { ...
0) (Attr<Foo<A, B> >::SomeType *) A) at that point, A is a typename, i.e. the name of a type, thus, not anything you can cast. 1) Also, Foo<A,B> is dependent upon A and B, therefore, Attr<Foo<A, B> > is a dependent name, too. Hence, you need a typename there so as to tell the compiler that SomeType is a type: (typenam...
6,611,678
6,612,249
Need fast c++ qt/qwt scatter plot
I have a huge array of 2D points (about 3 millions of pairs), which I need to render with reasonable speed in a Qt-based application. I've tried using QGraphicsScene, but its very slow even on 400000 primitives, so I was looking into the qwt library instead. It has a scatter plot example screenshot on its sourceforge p...
Scatter plot is contained in the "realtime" example: what you want is the IncrementalPlot class. I'd also suggest that drawing all the 3 million points isn't reasonable, since modern screens have only about 2 million pixels :) Thus it seems better to simplify the plot beforehand by merging the adjacent points into one ...
6,611,710
6,611,757
2d container for polymorphic objects in c++
I am aware of boost ptr_containers for 1D: http://www.boost.org/doc/libs/1_46_1/libs/ptr_container/doc/reference.html Should I extend to 2D using a vector<ptr_vector<BaseClass> > ?
Yes, using a vector of ptr_containers is easy and safe. I don't believe there's a special class for 2D polymorphic container anywhere.
6,611,880
6,612,011
When I `throw` something, where is it stored in memory?
I understand that when something is thrown, the stack is 'unwound' to the point where it is caught, and the destructors of class instances on the stack in each function context are run (which is why you should not throw an exception from a destructor - you could end up throwing a second one)...but I wonder where in mem...
Yes, the answer is compiler-dependent. A quick experiment with my compiler (g++ 4.4.3) reveals that its runtime library first tries to malloc memory for the exception and, failing that, attempts to allocate space within a process-wide "emergency buffer" that lives on the data segment. If that doesn't work out, it calls...
6,612,063
6,717,005
How to check if WCF client channel (service) terminated or not?
I have simple WCF service hosted on Windows Service. When the client of wcf service is idle for 10 minutes or more WCF service terminated at client side [ not at server side, server service is still alive] and i got famaous time out error. I do not want to increase timeout time . I just wanted to know is there is an ...
Unfortunately the only way to know that a proxy is no longer usable is to attempt to use it. What's actually happening is you are using a binding which is sessionful (say NetTcpBinding or WSHttpBinding) for which the service maintains resources for the client connection. If the client doesn't talk to the service for th...
6,612,148
6,614,142
Boost multi_array range compilation
A range can be used to slice a Boost Multidimensional array (multi_array). According to the documentation there are several ways of defining a range, however not all of them will compile. I'm using GCC 4.5.2 on Ubuntu 11.04. #include <boost/multi_array.hpp> int main() { typedef boost::multi_array_types::index_rang...
The operator< and operator<= being invoked here are templates; consequently, the value supplied to said operators for the Index argument must be the exact same type as the Index template parameter of the range being supplied. The boost::multi_array_types::index_range::index type ultimately boils down to a typedef for s...
6,612,404
21,843,346
Xcode converting project from C++ to Objective-C++
how to convert a Xcode C++ project to an Xcode Objective-C++ project, because now it doesn't threat ".mm" files like Objective-C++ files, but as C++ files generating lots of errors:) also cannot use the ObjC++ goodies
I think this is what you should do:
6,612,772
6,656,829
unable to load a DLL in MATLAB through Java
I am working on a Java GUI application that uses MATLAB code for calculations. However, the MATLAB code itself uses a DLL file. I packed all my MATLAB functions into a class and created a jar file. I added the C header file and DLL file in the project root folder of the Java project and added the jar containing MATLAB ...
I posted this question in the Matlab forum and finally got some answers. For those who have the same problem in future, refer to this link. http://www.mathworks.com/matlabcentral/answers/11321-loading-a-dll-in-mathlab-through-java
6,613,039
6,613,094
How do I get Visual Express 2010 to find my python.h header file?
I already did a search, but I just couldn't find what I searched for. I want to create a Python Module using C++ and Visual C++ Express 2010. Now, I need to include Python.h, but when I compile it says it couldn't find Python.h. How do I give my VC the Python header file ?
Tell IDE where header is located: Project -> Properties -> C/C++ -> Additional Include Directories
6,613,277
6,613,388
Enabling a button only if two fields are filled
How to implement such functionality that a button is enabled only if two lineEdit's are filled with text?
You want to monitor both line edits for changes: connect(lineEdit1, SIGNAL(textChanged(const QString&)), SLOT(checkShouldEnableButton())); connect(lineEdit2, SIGNAL(textChanged(const QString&)), SLOT(checkShouldEnableButton())); And then you need to enable/disable the button when text is present in both: void YourWidg...
6,613,372
6,613,391
How can i set same int value to an array of ints
I have a variable: unsigned int* data = (unsigned int*)malloc(height * width) I want to set same int to all array values. I can't use memset because it works with bytes. How can i do that?
Using C++: std::vector<unsigned int> data(height * width, value); If you need to pass the data to some legacy C function that expects a pointer, you can use &data[0] or &data.front() to get a pointer to the contiguous data in a well-defined manner. If you absolutely insist on using pointers throughout (but you have no...
6,613,478
6,613,959
is using cudaHostAlloc good for my case
i have a kernel launched several times, untill a solution is found. the solution will be found by at least one block. therefore when a block finds the solution it should inform the cpu that the solution is found, so the cpu prints the solution provided by this block. so what i am currently doing is the following: __g...
Issuing a copy from GPU to CPU and then waiting for its completion will slow your program a bit. Note that if you choose to send 1 byte or 1KB, that won't make much of a difference. In this case bandwidth is not a problem, but latency. But launching a kernel does consume some time as well. If the "meat" of your algorit...
6,613,546
6,618,144
Opengl program sample crash
I compiled the following code: // Triangle.cpp // Our first OpenGL program that will just draw a triangle on the screen. #include <GLTools.h> // OpenGL toolkit #include <GLShaderManager.h> // Shader Manager Class #ifdef __APPLE__ #include <glut/glut.h> // OS X version of GLUT #else #define FREE...
To use glCreateShader(GL_VERTEX_SHADER) you must be running OpenGL 2.0 or higher. One way to tell is to check the value of GLEW_VERSION_2_0 (after your call to glewInit()). If the value is true then OpenGL 2.0 is supported. Otherwise, you may need to update your graphics driver or use a newer graphics card.
6,613,620
6,614,731
Are there any GOOD tutorials showing how to write a program using SNMP in C++?
I've searched tirelessly for the past 4 days, and I've come up with nothing. I tried using net-snmp but i can't figure out how to install or use it. I'm completely lost, I don't know where to start. please help :(
If you are on Windows, why not use Windows API for SNMP? Check this out: Windows SNMP API
6,613,769
6,614,259
Include additional directories in Qt
Where in Qt can I specify additional directories I want to be included to build my project?
If you are using the Qt Creator IDE then I believe you must edit the .pro file directly. See the following link for details: http://doc.qt.io/qt-5/qmake-project-files.html If you are using a different IDE, such as Visual Studio using the add-in, you can edit the include path as you would for non-Qt projects.
6,613,779
6,613,839
Can CRTP completely replace virtual functionality for smaller designs?
Is CRTP capable enough to outsmart virtual functionality completely ? The only disadvantage I see with CRTP is notable amount of code generated for every recurring pattern. For smaller designs, (where 2-3 classes are derived from a base), is CRTP a better idea ?
CRTP does not provide runtime polymorphism. If you need runtime polymorphism, you need virtual methods. Worse, since the base class is templated, you can't even really use the subclass objects as if they were of the same type as the base class since you can't cast them to that base class — it doesn't exist; it's just...
6,613,815
6,613,926
Tool for determining version of Win32 APIs used by C++ code?
I'm modifying a large C++ project whose first release was Windows 7-only to work on Vista and XP. The main work will be to change the W7 API calls to use GetProcAddress at runtime (to avoid static linking with methods that are not available on the other platforms), and so I'm wondering if there are any tools that can ...
#define WINVER 0x501 Now everything that is newer than Windows XP will cause a compilation error. Replace everything that causes an error until none remain. If you have some sed-fu, you can probably write a filter that directly finds all #if WINVER > 0x501 blocks in the windows headers, but for me, this is a bit out o...
6,613,846
6,613,899
Random element in STL set/map in log n
Since C++ STL set/map are implemented as red-black trees, it should be possible to not only do insert, delete, and find in O(log n) time, but also getMin, getMax, getRandom. As I understand the former two have their equivalent in begin() and end() (is that correct?). How about the last one? How can I do that? The only ...
begin() is equivalent to a getMin operation, but end() returns an iterator one past the maximum, so it'd be rbegin(). As for getRandom: assuming you mean getting any item randomly with uniform probability, that might be possible in O(lg n) time in an AVL tree, but I don't see how to do it efficiently in a red-black tre...
6,613,870
6,614,369
GNU GCC (g++): Why does it generate multiple dtors?
Developing environment: GNU GCC (g++) 4.1.2 While I'm trying to investigate how to increase 'code coverage - particularly function coverage' in unit testing, I've found that some of class dtor seems to be generated multiple times. Does some of you have any idea on why, please? I tried and observed what I mentioned the ...
First, the purposes of these functions are described in the Itanium C++ ABI; see definitions under "base object destructor", "complete object destructor", and "deleting destructor". The mapping to mangled names is given in 5.1.4. Basically: D2 is the "base object destructor". It destroys the object itself, as well as ...
6,614,039
6,614,139
Block Level Atomic Write
is it possible to do an atomic write on the block level? as an example consider the following: __global__ kernel (int atomic) { atomic+=blockid.x; //should be atomic for each block }
While unclear what you mean with block/block level, it sounds like you just need an atomic add. Those are found in the kernel in #include <asm/atomic.h> your code would be __global__ kernel (int atomic) { atomic_add(blockid.x,&atomic); } atomic would have to be of type atomic_t and blockid.x an int.
6,614,315
6,614,387
Calling template function pointer with variable argument number
I want to write a function that calls another function with its arguments. See how I want that it work: int sum(int a, int b) { return a + b } int succ(int a) { return a + 1 } int size(char* str) { return strlen(str) } int call(???) { ??? } int main() { cout << call(sum, 1, 2) << endl; cout << call(succ, ...
C++0x variadic templates: template<typename Func, typename... Args> auto call(Func func, Args&&... args) -> typename std::result_of<Func(Args...)>::type { return func(std::forward<Args>(args)...); }
6,614,324
6,614,397
Get text from a windowsless control
I was wondering how can I read text of a control that doesn't have an HWND. For instance, the print dialog in office 2007 doesn't have HWND on all of its controls (only a few). Is there anyway to get the text from these controls? I believe they're simply drawn on the window and react using HITTEST, but I'm not sure, so...
Generally, there is no guaranteed way to do that. However, chances are you can get the text (and other info about the controls) using the IAccessible interface. Most Microsoft products implement this interface on most of the UI elements: this is how screen readers for disabled people work
6,614,702
6,614,847
C++ templatize output: iostream or fstream
How to templatize iostream and fstream objects? This way (see the code, please) is not correct... Thanks for your help. template <typename O> void test(O &o) { o << std::showpoint << std::fixed << std::right; o << "test"; } int main(int argc, _TCHAR* argv[]) { std::iostream out1; //Write into console std:...
Your template function works perfectly for me, although your main function had some serious errors in it. After fixing your errors, this program works for me: #include <iostream> #include <fstream> template <typename O> void test(O &o) { o << std::showpoint << std::fixed << std::right; o << "test"; } int mai...
6,614,765
6,614,859
Best way to create a standalone-exe (Forms) (C++)
I have to create an application for testing that is relatively simple. If a user plugs in a device into a USB (hid library), the form will say "Pass". If no device is detected, it will say "Fail". I want to create the app to run on WinXP+. It must be a forms application as it needs to be visual and have colors. The big...
I would suggest Borland C++ Builder 5 or 6. Visual C++ lacks the functionality to create C++ form apps, if we dismiss MFC
6,614,985
6,637,996
Should I separate CMakeList.txt from source folder?
I'm new to build tool, when I come across Autotool, I have an option to write only one Makefile.am in the top build folder and leave the source folder containing all cpp files clean. I could use VPATH to tell automake to look for the source code inside that folder instead of write /src/ every where. (refer to my old qu...
In our company we're using the first option, having a CMakeLists.txt in every subdirectory and building the tree from a root-CMakeLists.txt by using the add_subdirectory command. This is a modular approach where each subcomponent (think about the project has different parts like boost is split up into system, thread, d...
6,615,193
6,615,298
Virtual methods on a virtual base class
Something that has been confusing me about virtual base class inheritance... Given the following classes: class A { virtual void foo() = 0; } class B : virtual A { void foo() { /* do X */ } } class C : virtual A { void foo() { /* do Y */ } } class D : B, C { } Will this compile? If so, what would be the result o...
It should not compile, the function foo will be ambiguous. Since A::foo() is pure virtual function, the ambiguity has to be resolved.
6,615,444
6,615,472
How to implement an operator usable before an instance (pre position)
I have a class with the operator* taking a scalar as argument, that allow me to perform the multiplication of an instance of my class with a scalar. I'd like to be able to multiply a scalar by an instance of my class (inverse order with the same result). How can I do that ? Here an example : class Vector3d { public: ...
You must declare your operator* as a nonmember function (outside class) with inverse argument order and call the other one from it template<typename T> Vector3d<T> operator*(T& s, const Vector3d<T> &v) { return Vector3d(v.v[0] * s, v.v[1] * s, v.v[2] * s); } template<typename T> Vector3d<T> operator*(const Vector3...
6,615,621
6,615,865
C++ Non copyable except sometimes
I find that making a class non-copyable helps me a lot with my code quality. Initially I did this with boost::noncopyable, but I found the VC++ compiler errors to be not as helpful as with private members (double clicking lead to the wrong place in the code). T(T const&); T& operator=(T const&); Indeed, it has alerted...
Not sure if it's exactly what you want, but if you mark the copy constructor explicit then the class can't be passed by value or copy-initialized, but you can copy-construct using direct initialization. You'd presumably want to keep the assignment operator private, maybe a NonAssignable base would be useful for that.
6,615,751
6,617,392
Use ShutdownBlockRequestCreate in Win32 Console application
What is the proper method of blocking premature termination of a Win32 Console Application running on Windows 7? When Vista was introduced, there were changes regarding how Application Shutdown happened. Contrary to the behavior in XP, which was to open up a UI requesting whether the user wants to force close or not, ...
As a workaround, could you create a message-only window at startup and use ShutdownBlockReasonCreate on its window handle?
6,615,787
6,615,842
Advantages and Disadvantages of hashmap and tree map?
C++ by default provides a tree based map. With Boost you can get a hashmap. What are the advantages and disadvantages of C++'s Tree Based Map and Boost's Hashmap ?
C++0x/TR1 also provides the unordered_map which is usually implemented as a hash map. The differences are twofold: The key type. In the ordered map, the key type must obey a strict weak ordering, and entries are maintained in that order. In the unordered map, the key type must be equality-comparable and you must provi...
6,615,823
6,616,216
Uniform initializer used in default argument to const reference
Is this legal c++0x syntax? class A { public: void some_function( const std::set<std::string> &options = {} ); // note that this is legal, which binds the const reference to a temporary: void some_function( const std::set<std::string> &options = std::set<std::string>() ); } Because if so, I just found a bu...
It is valid in C++11, but it was a very late addition to the working paper that Bjarne put through. So it's not surprising that GCC doesn't support brace default arguments yet.
6,616,398
6,616,849
Finding python function parameters from C++
I am calling python functions from C++. I was wondering if it is possible to determine the number of parameters and the names of these parameters. I have read the link How to find the number of parameters to a Python function from C? however I do not really understand. I have this C++ function that calls the function '...
This answer to the question you linked to seems to be what you want. inspect.getargspec does exactly what you want on the Python side, and as the answer states, you can use PyObject_CallMethod or one of the related functions described at that link target to call inspect.getargspec from your C++ code, get the returned t...
6,616,618
6,616,730
Performance and safety of local array as parameter
I just want to make sure there aren't any potential problems with this. It compiles and runs fine, but am I risking any weird memory effects? Do I need to be especially concerned about exceptions in this case? //...constructor of some class myobj(int length, int *vars) { // do stuff with vars } // inside some othe...
There's nothing inherently wrong with this. However, there are a few things you need to be careful of: Don't keep a pointer to vars around after you return (or at least, after it goes out of scope). vars is only valid until you leave the scope that it was declared in. Make sure you don't run off the end of the vars ar...
6,616,732
6,616,785
Reverse Engineer Serial Communication
I have a device which when a certain application is on send data to that application. I need to take a sniff that data and retrieve certain information which is not being shown. The device is custom and for one reason or another has no data sheets. So have to sniff the communication and reconstruct the commands being s...
The easiest way to do this is to put your software in between the device and the other software. Then, pass-through all of the data, capturing out whatever you need. To do this, you would need to utilize serial port loopback software. There is a lot of it out there. See http://www.virtual-serial-port.com/virtual-ser...
6,616,859
6,617,003
Is there a way to make sure an array variable (unsigned int*) will be in memory?
I need to set some default value for all entires in a very large array. It takes me quite long time (110-120 ms) and i suspect it happens because of misses in memory. I use memset/std:fill to set the default value. Is there a way to make sure that the array will reside in memory before the memset/fill?
Assuming this is a large memory-mapped file, you can use the madvise() libc call with the MADV_WILLNEED argument to hint to the OS that you'll be wanting to access the region mentioned soon. However YMMV, as the array needs to be large enough that the benefit of the resulting syscall isn't outweighed by the cost of ma...
6,616,885
6,616,986
What's the point of a width smaller than a precision in printf()?
I came across some code with a line looking like: fprintf(fd, "%4.8f", ptr->myFlt); Not working with C++ much these days, I read the doc on printf and its ilk, and learned that in this case 4 is the "width", and 8 is the "precision". Width was defined as the minimum number of spaces occupied by the output, padding wi...
The width format specifier only affects the output if the total width of the printed number is less than the specified width. Obviously, this can never happen when the precision is set greater than or equal to the width. So, the width specification is useless in this case. Here's an article from MSDN; the last sentenc...
6,616,914
6,616,975
Expected unqualified-id before '&' token
(extremely) inexperienced in C++ but I've been getting along ok until now and this has me stumped. I'm unsure if I've included enough code to diagnose this but I believe it's syntax and might be figured out from the following. I'm getting the error mentioned from the line below: #pragma once #include "cinder/Vector.h" ...
Try adding #include "cinder/Channel.h" http://libcinder.org/docs/v0.8.2/_channel_8h.html
6,617,017
6,619,338
multicast basics - lost data
Is it a basic principle on reading multicast data that if your application doesn't process the next datagram that's come in before another one comes in that the first one is essentially overwritten? I've done some experimenting and increasing receive_buffer sizes has no effect on what I'm describing. In other words the...
Windows XP has a 8KB default socket buffer, Vista and later has a 64KB default socket buffer. You can override this with SO_RCVBUF, it is recommended to never set to 0 unlike SO_SNDBUF for zero-copy when using IOCP. Usually with socket buffers the queue fills up and starts dropping new packets, so with a large buffer ...
6,617,031
6,617,083
How to mix boost::bind with C function pointers to implement callbacks
I'm trying to shoehorn in some boost::bind to substitute member functions for straight up C function pointer style callbacks, but I'm running into problems doing the obvious thing. Can someone tell me why the following code snippet can't seem to match up the types in the function call? #include <iostream> #include <bo...
The result type of bind is not a function pointer, it's a function object which does not happen to be implicitly convertible to a function pointer. Use a template: template<typename ToRunT> void runit(ToRunT const& torun, std::string const& message) { torun(message); } Or use boost::function<>: static void runit(b...
6,617,224
6,646,336
C++ Extensions in Android.mk Files
Is it possible to compile C++ source files with multiple extensions in a single Android.mk file in the ndk? You can modify the C++ extension (which is .cpp by default) via the LOCAL_CPP_EXTENSION variable, but it appears you can only have it set to one single extension (aka, you couldn't have both .cc and .cpp files c...
No. In build/core/build-binary.mk, 'LOCAL_CPP_EXTENSION must be one word only.' # # Check LOCAL_CPP_EXTENSION, use '.cpp' by default # LOCAL_CPP_EXTENSION := $(strip $(LOCAL_CPP_EXTENSION)) ifeq ($(LOCAL_CPP_EXTENSION),) LOCAL_CPP_EXTENSION := .cpp else ifneq ($(words $(LOCAL_CPP_EXTENSION)),1) $(call __ndk_inf...
6,617,375
6,630,806
How to rotate Widgets in the FLUID gui editor
I'm following this tutorial (page 98) and i'm having a lot of trouble. It seems to be a bit dated or something, but what is troubling me at the moment is that it tells me to add the following to the CubeViewUI constructor: • A horizontal roller named hrot • A vertical roller named vrot • A horizontal slider named xpan ...
Under properties, click the C++ tab, and in the upper right, there's a chooser for Vertical and Horizontal.
6,617,688
6,617,789
Speed up float 5x5 matrix * vector multiplication with SSE
I need to run a matrix-vector multiplication 240000 times per second. The matrix is 5x5 and is always the same, whereas the vector changes at each iteration. The data type is float. I was thinking of using some SSE (or similar) instructions. I am concerned that the number of arithmetic operations is too small compared...
The Eigen C++ template library for vectors, matrices, ... has both optimised code for small fixed size matrices (as well as dynamically sized ones) optimised code that uses SSE optimisations so you should give it a try.
6,617,845
6,619,193
How do I set a breakpoint for when a vector<int> increases in length?
I have a vector that is empty, something is filling it somewhere and I cant find it. I want to set a memory breakpoint so that when the push_back occurs the program will break. I'm using Visual Studio 2008, and the problem is that the vector doesnt display its internal members in the watch window (it seems to have a ...
This answer is for VS 2010 - details might differ in other versions. Since the debugger uses a data visualizer (or whatever it's called) to display the state of a std::vector, you have to look in the <vector> header to determine the names of the actual members of the class and which one(s) might be responsible for trac...
6,618,037
6,618,121
Problem with passing object as an argument to createProcess
I am trying to correct a program that makes to other programs with the createProces call. The problem is when I pass an object of the Brick class as a parameter of the createProcess call. I create the object (in the main) this way: char IpApplicationName[1000]; STARTUPINFO StartInfo; PROCESS_INFORMATION ProcessInfo; ...
You are passing, as a command line argument, a pointer to a pointer to a class. This is broken in quite a few ways: CreateProcess's lpCommandLine argument takes a text string. There cannot be embedded NUL bytes. There must be a NUL byte to mark the end of the string. No such guarentee is present with a pointer-to-a-po...