question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,206,229
3,206,369
Change input locale (keyboard -- left shift+ alt + 1) key sequence PROGRAMMATICALLY
On XP, if you go to control panel -> regional and language Options -> Languages Tab -> Details -> If you have more than one keyboard in use, then, click Key Settings. Those are the settings I would like to change. I would like to set it up so that the DVORAK keyboard is Left Alt + Shift + 1. I can use C++, C# or whatever. I already know how to load a keyboard: HKL dvorakhkl = LoadKeyboardLayout(TEXT("00010409"), 0); That loads the dvorak keyboard. This sets it to default: SystemParametersInfo(SPI_SETDEFAULTINPUTLANG, 0, (PVOID)&dvorakhkl, 0); Also, I can change the top part of said dialog box "Switch between Input Languages" UINT val = 1;//"1" = ALT+SHIFT, "2" = CTRL+SHIFT, and "3" = none. System.ParametersInfo(SPI_SETLANGTOGGLE, 0, 0, val); Let me know if you can help. Thanks! Aaron
By default all programs use the C local (Because we all program in C dialects I suppose) You can imbue streams with an appropriate local. Just remember that you must imbue the stream before opening/using it. An attempt to imbue a stream after it has been opened/used will be silently ignored. This means that for std::cin and std::cout you should probably do it immediately on startup in main() to avoid the potential of them being used. When creating a locale object if you specify the empty striung it will pick up the name of the local from the environment (ie one of the environment variables). See: http://www.cplusplus.com/reference/iostream/ios_base/imbue/
3,206,302
3,206,387
C++ template determine function return type
How can I go about determining return type of a member generic function? template<class E> struct result<E> { // E has member function data(), I need to know its return type typedef typename &E::data type; }; is it possible to do it in generic way? I know there is boost:: result_of but for my purposes it lacks specializations (if I understood correctly, return type must be specialized). boost implementation would be great.
GCC's nonstandard typeof operator can do this, as can Boost.TypeOf.
3,206,310
3,206,641
How to filter characters from a string with C++/Boost
This seems like such a basic question, so I apologize if it's already been answered somewhere (my searching didn't turn up anything). I just want to filter a string object so that it contains only alphanumeric and space characters. Here's what I tried: #include "boost/algorithm/string/erase.hpp" #include "boost/algorithm/string/classification.hpp" std::wstring oldStr = "Bla=bla =&*\nSampleSampleSample "; std::wstring newStr = boost::erase_all_copy(oldStr, !(boost::is_alnum() || boost::is_space())); But the compiler is not at all happy with that -- it seems that I can only put a string in the second argument of erase_all_copy and not this is_alnum() stuff. Is there some obvious solution I'm missing here?
With the std algorithms and Boost.Bind: std::wstring s = ... std::wstring new_s; std::locale loc; std::remove_copy_if(s.begin(), s.end(), std::back_inserter(new_s), !(boost::bind(&std::isalnum<wchar_t>, _1, loc)|| boost::bind(&std::isspace<wchar_t>, _1, loc) ));
3,206,347
3,206,386
Small issue with creating a process ( CreateProcess or ShellExecuteEx) with parameters
Related question: CreateProcess doesn't pass command line arguments. Is there a difference between passing an argument vs. passing a parameter to an EXE when using CreateProcess (and/or ShellExecuteEx)? I'm trying to call something like: myExe.exe /myparam with the code like : TCHAR Buffer[MAX_PATH]; DWORD dwRet; dwRet = GetCurrentDirectory(MAX_PATH, Buffer); CString sCmd; sCmd.Format ( "%s\\%s", Buffer, command); CString sParam( "/myparam" ); sCmd += " " + sParam; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); if (CreateProcess( NULL, sCmd.GetBuffer() , NULL, NULL, TRUE, 0, NULL, Buffer, &si, &pi)) { ::WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { LPVOID lpMsgBuf = NULL; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); CString msg; msg.Format("Failed to start command line (error: %s) : %s\n",lpMsgBuf,sCmd); AfxMessageBox(msg); LocalFree(lpMsgBuf); } From what I understand from the other thread and MSDN is that it should be working properly and call the EXE with the parameter; doing the above code without adding the "/myparam" works like it should. I've tried the EXE from the command line and from Explorer (by creating a shortcut and adding /myparam to the target name) and it's working alright.
Try this in case there are spaces in the path: CString sCmd; sCmd.Format ( "\"%s\\%s\"", Buffer, command); Or else pass the parameters via the parameters argument.
3,206,526
3,208,466
Windows LDAP Authentication in C++
I am currently trying to authenticate users in a c++ application in Windows. I need to display a dialog for username and password and verify that they are an authenticated user on the Windows machine. Are there any libraries that allow for this functionality or a good way to go about it?
Probably CredUIPromptForWindowsCredentials (see http://msdn.microsoft.com/en-us/library/aa375178.aspx) or old CredUIPromptForCredentials (see http://msdn.microsoft.com/en-us/library/aa375177.aspx) could solve your problem? UPDATED: Another the most old way to authenticate a user is using of SSPI. It will not help with displaying a dialog but this can you implement yourself. You can find a very old code example (probably the first one published by Microsoft) here http://support.microsoft.com/kb/180548. If you do want use LDAP API (see http://msdn.microsoft.com/en-us/library/aa366102.aspx) you can use ldap_bind_s (see http://msdn.microsoft.com/en-us/library/aa366156.aspx) to verify user authentication. See http://msdn.microsoft.com/en-us/library/aa366106.aspx as a code example (it is not exactly what you want, but you can understand how these API work)
3,206,578
3,206,635
Exporting C++ classes from DLL
I came across this article on Code Project that talks about using an abstract interface as an alternative to exporting an entire class from a C++ DLL to avoid name mangling issues. The author has a Release() method in his interface definition that is supposed to be called by the user to free the class object's resources after using it. To automate the calling of this method the author also creates an std::auto_ptr<T>-like class that calls the Release() method before deleting the object. I was wondering whether the following approach would work instead: #include <memory> #if defined(XYZLIBRARY_EXPORT) // inside DLL # define XYZAPI __declspec(dllexport) #else // outside DLL # define XYZAPI __declspec(dllimport) #endif // XYZLIBRARY_EXPORT // The abstract interface for Xyz object. // No extra specifiers required. struct IXyz { virtual int Foo(int n) = 0; //No Release() method, sub-class' destructor does cleanup //virtual void Release() = 0; virtual ~IXyz() {} }; // Factory function that creates instances of the Xyz object. // Private function, do not use directly extern "C" XYZAPI IXyz* __stdcall GetXyz_(); #define GetXyz() std::auto_ptr<IXyz>( GetXyz_() ) Of course, GetXyz() can be a global function defined in the header instead of a #define. The advantage to this method would be that we don't need to cook up our own derivative of auto_ptr that calls the Release() method. Thanks for your answers, Ashish.
by doing this, you risk calling delete (in your process, within auto_ptr's destructor) on an object that is not created by the matching call to new() (that is done inside the factory function, hence inside the dll). Trouble guaranteed, for instance when your dll is compiled in release mode while the calling process in debug mode. The Release() method is better.
3,206,745
3,207,330
connecting a function to a boost::signal runs, but doesn't call the function
I have a class Yarl in my code with a member function refresh that I want to bind to two boost::signals. One of these signals is a member of a class EventHandler defined like this: class EventHandler { public: boost::signal<void()> sigRefresh; }; The other is a free floating signal in another file declared like this: namespace utility { static boost::signal<void()> signal_refresh; } in a member function of Yarl, I connect refresh to the signals like this: events::EventHandler eventHandler; eventHandler.sigRefresh.connect(boost::bind(&Yarl::refresh, this)); utility::signal_refresh.connect(boost::bind(&Yarl::refresh, this)); and later on I call both signals like this: sigRefresh(); signal_refresh(); This code compiles and runs, and sigRefresh works exactly as expected. However, nothing happens when I call signal_refresh. As far as I can tell, refresh never actually got connected to signal_refresh. Anyone see what I'm doing wrong?
I'm taking a guess that you are multiply defining signal_refresh. The static keyword before it's declaration suggests to me the code snippet is in a header file and you had to put the static there to get it to compile without redefined symbol errors. If you have done this then every source file including the header will get a unique copy of signal_refresh and thus the instance you are calling may not be the instance you connected it to. I may be totally off mark here but it is possible.
3,206,846
3,207,181
How to join in a WMI Query (WQL)
I want to get the serial number of the boot-harddisk via a WQL query. The boot-partition can be retrieved using the following query: SELECT * FROM Win32_DiskPartition where BootPartition=True The serial number is in Win32_DiskDrive: SELECT DeviceID, SerialNumber FROM Win32_DiskDrive Win32_DiskDriveToDiskPartition has the mapping of Win32_DiskDrive to Win32_DiskPartition. They are mapped Win32_DiskDrive.DeviceID to Win32_DiskPartition.DeviceID in Win32_DiskDriveToDiskPartition How can I build a WQL query that inner joins Win32_DiskPartition and Win32_DiskDrive? Do I have to use Associators or does it work with INNER JOIN?
WQL doesn't support the JOIN clause. You need to use the ASSOCIATORS OF statement as you guessed. Here's an example in VBScript: strComputer = "." Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set colPartitions = oWMI.ExecQuery( _ "SELECT * FROM Win32_DiskPartition WHERE BootPartition=True") For Each oPartition in colPartitions Set colDrives = oWMI.ExecQuery( _ "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" _ & oPartition.DeviceID & "'} WHERE ResultClass=Win32_DiskDrive") For Each oDrive in colDrives WScript.Echo oDrive.SerialNumber Next Next Note, however, that the Win32_DiskDrive.SerialNumber property isn't available prior to Windows Vista. So, if you want your code to work on earlier Windows versions as well (e.g. Windows XP or Windows 2000) you should consider using APIs other than WMI. Edit: (reply to comment) Yes, you can add a nested ASSOCIATORS OF query to get the Win32_PhysicalMedia instances corresponding to the Win32_DiskDrive instances; something like this: ... For Each oDrive in colDrives Set colMedia = oWMI.ExecQuery( _ "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" _ & oDrive.DeviceID & "'} WHERE ResultClass=Win32_PhysicalMedia") For Each oMedia in colMedia WScript.Echo oMedia.SerialNumber Next Next You haven't said what language you're using - I guess in PowerShell or C# the whole thing can be done more elegantly, but VBScript is pretty verbose.
3,207,018
3,208,184
Register keyword in C++
What is difference between int x=7; and register int x=7; ? I am using C++.
In C++ as it existed in 2010, any program which is valid that uses the keywords "auto" or "register" will be semantically identical to one with those keywords removed (unless they appear in stringized macros or other similar contexts). In that sense the keywords are useless for properly-compiling programs. On the other hand, the keywords might be useful in certain macro contexts to ensure that improper usage of a macro will cause a compile-time error rather than producing bogus code. In C++11 and later versions of the language, the auto keyword was re-purposed to act as a pseudo-type for objects which are initialized, which a compiler will automatically replace with the type of the initializing expression. Thus, in C++03, the declaration: auto int i=(unsigned char)5; was equivalent to int i=5; when used within a block context, and auto i=(unsigned char)5; was a constraint violation. In C++11, auto int i=(unsigned char)5; became a constraint violation while auto i=(unsigned char)5; became equivalent to auto unsigned char i=5;.
3,207,064
3,207,083
Need Help Creating Multiple Directories in Makefile
I have the following block of code in a makefile: param_test_dir: @if test -d $(BUILD_DIR); then \ echo Build exists...; \ else \ echo Build directory does not exist, making build dir...; \ mkdir $(BUILD_DIR); \ fi @if test -d $(TEST_DIR); then \ echo Tests exists...; \ else \ echo Tests directory does not exist, making tests dir...; \ mkdir $(TEST_DIR); \ fi @if test -d $(TEST_DIR)/param_unit_test; then \ echo Param unit test directory exists...; \ else \ echo Param unit test directory does \ not exist, making build dir...; \ mkdir $(TEST_DIR)/param_unit_test; \ fi @if test -d $(TEST_DIR)/param_unit_test/source; then \ echo Param unit test source directory exists...; \ else \ echo Param unit test source directory does \ not exist, making build dir...; \ mkdir $(TEST_DIR)/param_unit_test/source; \ fi @if test -d $(TEST_DIR)/param_unit_test/obj; then \ echo Param unit test object directory exists...; \ else \ echo Param unit test object directory does \ not exist, making object dir...; \ mkdir $(TEST_DIR)/param_unit_test/obj; \ fi @if test -d $(TEST_DIR)/param_unit_test/bin; then \ echo Param unit test executable directory exists...; \ else \ echo Param unit test executable directory does \ not exist, making executable dir...; \ mkdir $(TEST_DIR)/param_unit_test/bin; \ fi Basically, this is necessitated as I don't my makefile to crash and die if the build directory doesn't exist -- I want it to recreate the missing parts of the directory tree. The nesting is due to the fact that I have a build directory, a tests directory inside the build (for module tests vs. full programs) and then within that tests directory individual directories for tests, each of which need a source, obj, and bin directory. So a lot of stuff to create! Here's my question. Is there a way to take advantage of makefile "magic" to feed it some single variable like: PATH=./build/tests/param_test/bin and have it create all the directories I need with like a one or two liner rather than that humongous if statement? Thanks in advance!!
mkdir -p build/tests/param_test/bin mkdir manual: -p, --parents, no error if existing, make parent directories as needed
3,207,094
3,208,441
Fastest factorial implementation with 64-bit result in assembly
This is not homework, just something I though of. So, straight computing factorial is not exactly fast; memoization can help, but if the result is to fit into 32 or 64 bits, then the factorial only can work for inputs 0 through 12 and 20 respectively. So ... we might as well use a lookup table: n n! 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800 11 39916800 12 479001600 13 6227020800 2^32= 4294967296 14 87178291200 15 1.30767E+12 16 2.09228E+13 17 3.55687E+14 18 6.40237E+15 19 1.21645E+17 20 2.4329E+18 2^64= 1.84467E+19 So, suppose I want to have an inline C++ factorial function which uses inline assembly, with a 32 bit or 64 bit unsigned integer expected as a result. If the input is either negative or large enough to cause overflow, the output should be 0. How can this be done in assembly such that it consumes the least amount of cycles? This code will run on a 64-bit Intel/AMD architecture. If feasible, I am interested in improving the worst case scenario, so 20! should not take a lot longer to compute than 0! - hopefully there is a binary search approach. Hopefully there is a clever trick for doing if (n == 0 || n == 1) { return 1; }. Also, if the output needs to be 32 bit, then I think assembly instructions can contain both code and data in them. My assembly knowledge is weak. Please let me know if the question does not make a whole lot of sense. Being able to use the function in C++ would be nice - makes it a more realistic problem. If, for instance, calling a function is expensive, then trying to save 1-2 clock cycles in the body of the assembly will not help much.
I have cleverly built a lookup table in assembly. Just in case you're rusty on your assembly, The routine expects the parameter to be in the ecx register. I verify that it is in range then read the lookup table's values into the eax and edx registers. If the value is out of range, I just xor the eax and edx registers with themselves (this forces them to 0). Unfortunately, since it's an assembly routine the compiler will be unable to inline the code. But, I'm sure the few cycles I saved by writing my awesome assembly routine will more than make up for any gain by inlining. factorial: xorl %eax, %eax xorl %edx, %edx cmpl $20, %ecx ja .TOOBIG movl CSWTCH.1(,%ecx,8), %eax movl CSWTCH.1+4(,%ecx,8), %edx .TOOBIG: LOOKUP_TABLE: .section .rodata .align 32 .type CSWTCH.1, @object .size CSWTCH.1, 168 CSWTCH.1: .long 1 .long 0 .long 1 .long 0 .long 2 .long 0 .long 6 .long 0 .long 24 .long 0 .long 120 .long 0 .long 720 .long 0 .long 5040 .long 0 .long 40320 .long 0 .long 362880 .long 0 .long 3628800 .long 0 .long 39916800 .long 0 .long 479001600 .long 0 .long 1932053504 .long 1 .long 1278945280 .long 20 .long 2004310016 .long 304 .long 2004189184 .long 4871 .long -288522240 .long 82814 .long -898433024 .long 1490668 .long 109641728 .long 28322707 .long -2102132736 .long 566454140 The lookup table is difficult to maintain, so I've included the script I used to build it static constexpr uint64_t const_factorial(uint32_t i) { return (i==0)? 1: (i * const_factorial(i-1)); } uint64_t factorial(uint32_t i) { switch(i) { case 0: return const_factorial(0); case 1: return const_factorial(1); case 2: return const_factorial(2); case 3: return const_factorial(3); case 4: return const_factorial(4); case 5: return const_factorial(5); case 6: return const_factorial(6); case 7: return const_factorial(7); case 8: return const_factorial(8); case 9: return const_factorial(9); case 10: return const_factorial(10); case 11: return const_factorial(11); case 12: return const_factorial(12); case 13: return const_factorial(13); case 14: return const_factorial(14); case 15: return const_factorial(15); case 16: return const_factorial(16); case 17: return const_factorial(17); case 18: return const_factorial(18); case 19: return const_factorial(19); case 20: return const_factorial(20); default: return 0; } } Just in case you missed it in my poor attempt at humor. The C++ compiler is more than capable at correctly optimizing your code. As you can see I didn't need to do anything fancy with lookup tables, binary search trees, or hashes. Just a simple switch statement and the compiler did the rest.
3,207,098
3,212,546
How to write programmatically some unicode text in RTF format?
In order to generate RTF programmatically I have decided to use rtflib v1.0 from codeproject.com. But I can't understand how to generate text in russian unicode. So I need to generate a unicode text. Could someone help me? P.S. Honeslty, I could write in .rtf file some text in, only by opening it with MS Word. But after writing some text in unicode, WordPad showed text is correctly.
Here are steps: Create a file named .rtf Open .rtf Write there the following code in order to generate an RTF file which contains UTF-8 encoded content: {\rtf1\adeflang1025\ansi {\fonttbl {\f26\fbidi \froman\fcharset204\fprq2{\*\panose 010a0502050306030303}Sylfaen;} } {\rtlch\fcs1 \af31507 \ltrch\fcs0 \f26 \u<unicode number>\'3f\u<unicode number>\'3f\u<unicode number>\'3 A lot of other text and symbols like this: + - * _ } } For example: {\rtf1\adeflang1025\ansi {\fonttbl {\f26\fbidi \froman\fcharset204\fprq2{\*\panose 010a0502050306030303}Sylfaen;} } {\rtlch\fcs1 \af31507 \ltrch\fcs0 \f26 \u1329\'3f\u1330\'3f\u1331\'3f\u1332\'3f - these are first 4 latters of Armenian alphabet} } Foe more details see the UTF-8 encoding table here. And RTF spec is here.
3,207,155
3,208,334
Java vs. C++ for building a GUI which has a C++ backend
I currently have a C++ backend that I need to connect with a GUI, and since I've never built a GUI before, I was confused on where to start. I'm comfortable writing code in C++ and Java, so I'd prefer my GUI to be in one of those languages. Also, the GUI has to be reasonably OS independent over Windows and Linux (and hopefully, hence Macs). Now I understand that if I use Java to do it, I'll need some wrappers to do it - but I've also heard (strictly second hand) that writing a GUI in C++ is a pain. I don't want to rewrite too much of my backend code in Java (who does??) and I was hoping for input on: Does either language offer serious advantages/disadvantages compared to the other? How serious is the wrapping issue, and how much rewriting would come in if I used Java. Are there any specific resources I should look at that people think would be relevant? Thanks and Cheers All :)
You say you already know C++ and Java, and that you never did a GUI before. That means: no matter if you go for a Java GUI or a C++ GUI, you will need to learn how to handle the GUI framework if you chose Java, you also need to learn how to interface between the two languages So staying in C++ saves you one thing to learn. Well, it's always a good idea to learn something, but might be a bad idea to learn two new concepts at the same time. Anyway, the learning might be the smaller burden, I guess there is a lot of actual work involed, even when you use tools like SWIG. You might want to know if writing a GUI in Java or doing it in C++ is easier. It depends on the chosen Framework. For Java, you have AWT and Swing which are part of the default Java distribution, and then there is SWT which is used by Eclipse, for example. For C++, there are many toolkits, with Qt, GTK and wxWidgets being the most popular ones, and all three support every major platform. Most of those "C++" GUI toolkits also have a Java binding or even a Java port, so you could use them with Java as well. So far I've used Swing, Qt and a few others which don't help in your situation (The UI thingy that came with Borland C++ Builder and WinForms on .NET). Basically, the concepts are the same for all those frameworks, and I found none of them being harder or easier than the other. The only exception maybe Java, because I never got those LayoutManagers to work, even though the other toolkits have equivalents to LayoutManagers that are easy to master. But maybe thats just me. People also will tell you that Java GUIs are always ugly and don't fit the host system. Well, most Java GUIs really are, but IMHO thats not because of Java, but because of bad programming. It takes two lines of code to let a Swing app adapt to the look and feel of the OS, and most programmers simply don't put enough effort into their Java GUIs to copy and paste those two lines... you can imagine how much they care about the rest of their GUI design. For your current situation, I would recommend a C++ GUI, but if you know how your future plans look like, and if you know you will doing Java GUIs for the rest of your life, then it's probably ok to start that now and take the extra effort of . And if you chose C++ for the GUI, people will tell you all kind of things to pull you in any direction. All of the three big portable frameworks have their pros and their cons, but I don't believe there is any single best or worst one among them. I'd recommend Qt simply because I already used it - but if I'd happten to have used GTK or wxWidgets instead, I'd probably suggest that.
3,207,307
3,207,347
Simple noob I/O question (C++)
sorry for the noob question, but I'm new to C++. I need to read some information, line-by-line, from a file, and perform some calculations, and output into another file. For example, we read a unique ID for each line, a name, and 2 numbers. The last 2 numbers are multiplied, and in the output file, the ID, name and product are printed line by line: input.txt: 2431 John Doe 2000 5 9856 Jane Doe 1800 2 4029 Jack Siu 3000 10 output.txt: ID Name Total 2431 John Doe 10000 9856 Jane Doe 3600 4029 Jack Siu 30000 My code is similar to this, but only the first line appears in the output file. If I press Enter repeatedly, the other lines appear in the output file: #include <fstream> using namespace std; ifstream cin("input.txt"); ofstream cout("output.txt"); int main () { int ID, I, J; string First, Last; char c; cout << "ID\tName\t\Total\n"; while ((c = getchar()) != EOF) { cin >> ID >> First >> Last >> I >> J; cout << ID << " " << First << " " << Last << " " I * J << "\n"; } return 0; } That's my only problem, that the values don't appear in the output file, unless I press Enter repeatedly, then close the program. Can anyone suggest a fix for my code above, to have it do the task without keyboard input? Thanks!
Use while (!cin.eof()) {
3,207,399
3,207,431
What is the most efficient way to convert STL string array to const char* array?
We have: std::string string_array[2]; string_array[0] = "some data"; string_array[1] = "some more data"; char* cstring_array[2]; What is the most efficient way to copy data from string_array to cstring_array? Or pass string_array to the function, needed "const char* cstring_array[]"?
A function that takes a char const * is only written to accept a single string at a time, not an array of strings. To pass an std::string to such a function, just call the function with your_string.c_str() as the parameter. Edit: for a function that takes an array of strings, the obvious choice (at least to me) would be to write a minimal front-end that lets you pass a vector<std::string>: // The pre-existing function we want to call. void func(char const *strings[], size_t num) { for (size_t i=0;i<num; i++) std::cout << strings[i] << "\n"; } // our overload that takes a vector<string>: void func(std::vector<std::string> const &strings) { std::vector<char const *> proxies(strings.size()); for (int i=0; i<proxies.size(); i++) proxies[i] = strings[i].c_str(); func(&proxies[0], proxies.size()); }
3,207,461
3,207,556
Best way to create windows applications
I have been learning windows API from online and PDF books but I hear of people using sdk and visual studio programs. What should i do? API I'd create but extremely complex. Would I benefit from learning the API or should I get a sdk or program that writes to code for me? I have msc++e but I don't think it comes with those benifts
In the case of windows, the SDK and the Win32 API refer to pretty much the same thing. The SDK is all the crap you need to target the API (this is always what an "SDK" is). When you're using a non-VC compiler on windows (or a cross-compiler) you have to download the SDK in order to write win32 programs. There's very few situations in which targeting the Win32 API itself is useful. You usually want to work at a higher level with an API like MFC, WTL, or WX (I include WX because for windows it's actually a wrapper for Win32). There are also libraries that do their own thing and just draw everything themselves (all owner drawn windows) like Qt, GTK, etc. If you're working with a windows specific library you'll still end up touching the Win32 API occasionally but only small parts of it. You'll save a LOT of time just letting those parts turn up instead of actually trying to learn the API itself. Nobody that isn't insane or being tortured into submission writes raw Win32.
3,207,538
3,207,547
Use fprintf to memory stream
I have a vc++ method that uses fprintf to write values to a file in the hard disc. I want to change this method so that instead of writing the values to disc, I want to return a pointer to the data. I know in advance the size I have to allocate. Is there any way to pass a memory stream or unsigned char pointer to fprintf? thanks
You can use sprintf or better yet snprintf [_snprintf/snprintf_s for VC++] (as Michael Burr pointed out and as it's noted in the Remarks section of the sprintf link). And, since it's tagged C++, better yet use std::stringstream.
3,207,662
3,208,562
how do I insert a string datetime into mysql using c++
I have a datetime field in the following format: string date = "Jun 23 19:47:15 +0000 2010"; how do I insert it ito datetime field in mysql table? I am assuming I have to convert the date into unix timestamp before I insert it into the table.
First, you've got an sql-injection attack waiting to happen. Had to be said. Ok, that huge problem swept aside, you can either convert the date to a MySQL format (such as a UTC timestamp then converted again with FROM_UNIXTIME()), or tell MySQL how to convert it using STR_TO_DATE(). Both are documented in the MySQL manual, under the section "Date and Time Functions".
3,207,679
3,207,722
What are the shortcomings of std::reverse_iterator?
The documentation for boost's specialized iterator adaptors states that boost::reverse_iterator "Corrects many of the shortcomings of C++98's std::reverse_iterator." What are these shortcomings? I can't seem to find a description of these shortcomings. FOLLOW-UP QUESTION: How does boost::reverse_iterator correct these shortcomings?
Well, the big problem is that they're not forward iterators, and there's stuff that pretty much expect forward iterators. So, you have to do some funny conversions to get things to work. To name some issues Some versions of erase() and insert() require iterators rather than reverse iterators. That means that if you're using a reverse iterators and you want to insert() or erase(), you're going to have to use the reverse iterator's base() function to get your hands on a forward iterator. There is no automatic conversion. base() returns the forward iterator equivalent to the reverse iterator in terms of insertion. That is, insert inserts in front of the current element. The element that the reverse iterator is pointing at, therefore, would be the wrong element to be pointing at if base() gave you an iterator that pointed at the same element. So, it points one forward, and you can use it for insertion. Because base() returns an iterator pointing at a different element, it's the wrong element to use for erase(). If you called erase() on the iterator from base(), you'd erase one element forward in the container from the element that the reverse iterator points at, so you have to increment the reverse iterator before calling base() in order to get the correct forward iterator to use for erase(). Whether you can even use base() with erase() to correctly erase an element depends entirely on your implementation. It works with gcc, but with Visual Studio they're really just wrapping a forward iterator in a manner that makes it so that it doesn't work to use erase() when dealing with reverse iterators and Visual Studio. I don't recall whether insert() has the same problem, but reverse iterators don't work the same between different implementations of C++ (according to the Visual Studio guys, the standard wasn't clear enough), so it can be kind of hairy to use them for anything other than simply iterating over a container. There are probably other issues as well, but dealing with any type of iterator other than a non-const, forward iterator in C++ when doing anything other than simply iterating over a container can get a bit hairy - if you can even do it all - because so many functions require non-const forward iterators rather than any other kind of iterator. If you really want to know the differences between the various iterator types and the issues associated with them, I recommend reading Scott Meyer's Effective STL. It has a great chapter on iterators. EDIT: As for how Boost's reverse iterator corrects those shortcomings, I'm afraid that I don't have a clue. I'm aware of some of the standard reverse iterator's shortcomings and have been bitten by them in the past, but I've never used Boost much, so I'm not familiar with their reverse iterators at all. Sorry.
3,207,704
3,218,316
How can I cin and cout some unicode text?
I ask a code snippet which cin a unicode text, concatenates another unicode one to the first unicode text and the cout the result. P.S. This code will help me to solve another bigger problem with unicode. But before the key thing is to accomplish what I ask. ADDED: BTW I can't write in the command line any unicode symbol when I run the executable file. How I should do that?
Here is an example that shows four different methods, of which only the third (C conio) and the fourth (native Windows API) work (but only if stdin/stdout aren't redirected). Note that you still need a font that contains the character you want to show (Lucida Console supports at least Greek and Cyrillic). Note that everything here is completely non-portable, there is just no portable way to input/output Unicode strings on the terminal. #ifndef UNICODE #define UNICODE #endif #ifndef _UNICODE #define _UNICODE #endif #define STRICT #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <iostream> #include <string> #include <cstdlib> #include <cstdio> #include <conio.h> #include <windows.h> void testIostream(); void testStdio(); void testConio(); void testWindows(); int wmain() { testIostream(); testStdio(); testConio(); testWindows(); std::system("pause"); } void testIostream() { std::wstring first, second; std::getline(std::wcin, first); if (!std::wcin.good()) return; std::getline(std::wcin, second); if (!std::wcin.good()) return; std::wcout << first << second << std::endl; } void testStdio() { wchar_t buffer[0x1000]; if (!_getws_s(buffer)) return; const std::wstring first = buffer; if (!_getws_s(buffer)) return; const std::wstring second = buffer; const std::wstring result = first + second; _putws(result.c_str()); } void testConio() { wchar_t buffer[0x1000]; std::size_t numRead = 0; if (_cgetws_s(buffer, &numRead)) return; const std::wstring first(buffer, numRead); if (_cgetws_s(buffer, &numRead)) return; const std::wstring second(buffer, numRead); const std::wstring result = first + second + L'\n'; _cputws(result.c_str()); } void testWindows() { const HANDLE stdIn = GetStdHandle(STD_INPUT_HANDLE); WCHAR buffer[0x1000]; DWORD numRead = 0; if (!ReadConsoleW(stdIn, buffer, sizeof buffer, &numRead, NULL)) return; const std::wstring first(buffer, numRead - 2); if (!ReadConsoleW(stdIn, buffer, sizeof buffer, &numRead, NULL)) return; const std::wstring second(buffer, numRead); const std::wstring result = first + second; const HANDLE stdOut = GetStdHandle(STD_OUTPUT_HANDLE); DWORD numWritten = 0; WriteConsoleW(stdOut, result.c_str(), result.size(), &numWritten, NULL); } Edit 1: I've added a method based on conio. Edit 2: I've messed around with _O_U16TEXT a bit as described in Michael Kaplan's blog, but that seemingly only had wgets interpret the (8-bit) data from ReadFile as UTF-16. I'll investigate this a bit further during the weekend.
3,207,712
3,207,773
Including Templated C++ in Objective C
I am trying to include a C++ library with quite a few templates into an objective C application. It seems to perpetually choke on a few inline statements inside a shared library: template <class T> inline T MIN(T a, T b) { return a > b ? b : a; } template <class T> inline T MAX(T a, T b) { return a > b ? a : b; } yielding the output: expected unqualified-id before '{' token expected `)' before '{' token I am compiling with the options. g++ -x objective-c++ -Wall -O3 -I. -c demod_gui.m -o demod_gui All the other templates seem to compile fine, any idea what could be wrong here? Thanks in advance for any help.
There are already macros MIN and MAX defined in Foundation/NSObjCRuntime.h. #if !defined(MIN) #define MIN(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; }) #endif #if !defined(MAX) #define MAX(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; }) #endif So your definition becomes template <class T> inline T ({ __typeof__(T a) __a = (T a); __typeof__(T b) __b = (T b); __a < __b ? __a : __b; }) { return a > b ? b : a; } which is obviously invalid. Why not use std::max and std::min?
3,207,917
3,207,988
Fail to CoCreateInstance an EXE COM server
I have an EXE COM server (used to elevate our application to a higher integrity level) which is downloaded to %temp% and registered by an ActiveX control. This COM server works pretty well on Vista machines. On Window 7 machines I got something wired: the COM server can be downloaded and registered successfully, but I got the error 0x80080005 (Server execution failed ) when trying to initialize the server by CoCreateInstance. If I copy the COM server to %temp% manually instead of downloading it via internet then everything works as expected. I am suspecting that the downloaded EXE files have some special attributes that prevent it been loaded but have no idea how to figure it out. Does anyone have the same experience or have any clue for this issue? Any suggests will be highly appreciated. Joe
Yes they do. Start a command prompt and use DIR /R. You'll see the alternate data stream in the file. The one that says: "don't trust this file, it came from an untrusted source". You can delete them with the filename:streamname syntax. Check if that's okay with your customer first. I don't know many that are thrilled about EXEs getting downloaded and bypassing normal security rulez.
3,208,657
3,208,745
Is unsigned char('0') legal C++
The following compiles in Visual Studio but fails to compile under g++. int main() { int a = unsigned char('0'); return 0; } Is unsigned char() a valid way to cast in C++?
No, it's not legal. A function-style explicit type conversion requires a simple-type-specifier, followed by a parenthesized expression-list. (§5.2.3) unsigned char is not a simple-type-specifier; this is related to a question brought up by James. Obviously, if unsigned char was a simple-type-specifier, it would be legal. A work-around is to use std::identity: template <typename T> struct identity { typedef T type; }; And then: int a = std::identity<unsigned char>::type('0'); std::identity<unsigned char>::type is a simple-type-specifier, and its type is simply the type of the template parameter. Of course, you get a two-for-one with static_cast. This is the preferred casting method anyway.
3,208,927
3,209,893
Large scale Machine Learning
I need to run various machine learning techniques on a big dataset (10-100 billions records) The problems are mostly around text mining/information extraction and include various kernel techniques but are not restricted to them (we use some bayesian methods, bootstrapping, gradient boosting, regression trees -- many different problems and ways to solve them) What would be the best implementation? I'm experienced in ML but do not have much experience how to do it for huge datasets Is there any extendable and customizable Machine Learning libraries utilizing MapReduce infrastructure Strong preference to c++, but Java and python are ok Amazon Azure or own datacenter (we can afford it)?
Unless the classification state space you are attempting to learn is extremely large, I would expect that there is significant redundancy in a text-mining-focused dataset with 10-100 billion records or training samples. As a rough guess, I would doubt that one would need much more than a 1-2% random sample subset to learn reliable classifiers that would hold up well under cross-validation testing. A quick literature search came up with the following relevant papers. The Tsang paper claims O(n) time complexity for n training samples, and there is software related to it available as the LibCVM toolkit. The Wolfe paper describes a distributed EM approach based on MapReduce. Lastly, there was a Large-Scale Machine Learning workshop at the NIPS 2009 conference that looks to have had lots of interesting and relevant presentations. References Ivor W. Tsang, James T. Kwok, Pak-Ming Cheung (2005). "Core Vector Machines: Fast SVM Training on Very Large Data Sets", Journal of Machine Learning Research, vol 6, pp 363–392. J Wolfe, A Haghighi, D Klein (2008). "Fully Distributed EM for Very Large Datasets", Proceedings of the 25th International Conference on Machine Learning, pp 1184-1191. Olivier Camp, Joaquim B. L. Filipe, Slimane Hammoudi and Mario Piattini (2005). "Mining Very Large Datasets with Support Vector Machine Algorithms ", Enterprise Information Systems V, Springer Netherlands, pp 177-184.
3,208,958
3,210,155
How to keep a list of instances of a class?
I'm writing a raytracer in C++ and need to be able to check intersections with every object in a scene (optimizations will come later), and to do this, I need to keep a running list of class instances. A list of pointers, updated when a new instance is created, won't work because as far as I know there is no way to increase the size of the array after it is initialized. I'd really like a built-in (to C++) solution if there is one.
I'm writing a raytracer in C++ and need to be able to check intersections with every object in a scene [...] The standard approach is a spatial graph. Most commonly, octrees are used, since they can express location in 3-dimensional space. Trivially, the spatial tree would look something like this: struct SpatialNode { SpatialNode * children[8]; std::vector<object*> objects; }; Each node has an (implicit or explicit) position and size. When a new object is added to the world scene, the tree is walked through the children (which occupy the octants that are split by the x-y, y-z, and z-x planes: 4 above, 4 below; 4 left, 4 right; 4 behind, 4 in front) and the object is added only to the smallest node that can fully contain it. (Obviously, you'll need to be able to calculate the dimensions of your object and whether they can be fully contained within a given region.) This has the benefit of being fairly fast (only the portions of the tree that are examined are actually relevant), both in populating it and in searching it. There are several articles on it that you can read at Wikipedia, GameDev.net, and elsewhere.
3,209,085
3,209,253
Strange enable_if behaviour using nested classes (MSVC compiler bug or feature?)
After quite some time debugging my code, I tracked down the reason for my problems to some unexpected template specialization results using enable_if: The following code fails the assertion in DoTest() in Visual Studio 2010 (and 2008), while it doesn't in g++ 3.4.5. However, when i remove the template from SomeClass or move my_condition out of the scope of SomeClass it works in MSVC, too. Is there something wrong with this code that would explain this behaviour (at least partially) or is this a bug in the MSVC compiler? (using this example code it's the same for boost and the c++0x stl version) #include <cassert> #include <boost\utility\enable_if.hpp> template <class X> class SomeClass { public: template <class T> struct my_condition { static const bool value = true; }; template <class T, class Enable = void> struct enable_if_tester { bool operator()() { return false; } }; template <class T> struct enable_if_tester<T, typename boost::enable_if< my_condition<T> >::type> { bool operator()() { return true; } }; template <class T> void DoTest() { enable_if_tester<T> test; assert( test() ); } }; int main() { SomeClass<float>().DoTest<int>(); return 0; } When trying to fix it by moving the condition out of the scope, i also noticed that this isn't even enough when using std::enable_if, but at least it works with boost::enable_if: #include <cassert> //#include <boost\utility\enable_if.hpp> #include <type_traits> template <class T, class X> struct my_condition { static const bool value = true; }; template <class X> class SomeClass { public: template <class T, class Enable = void> struct enable_if_tester { bool operator()() { return false; } }; template <class T> //struct enable_if_tester<T, typename boost::enable_if< my_condition<T, X> >::type> { struct enable_if_tester<T, typename std::enable_if< my_condition<T, X>::value >::type> { bool operator()() { return true; } }; template <class T> void DoTest() { enable_if_tester<T> test; assert( test() ); } }; int main() { SomeClass<float>().DoTest<int>(); return 0; } I hope someone has an explanation for this.
Everything is fine with your code, it's just that VC is buggy. It's known to have problems with partial template specialization of template member classes.
3,209,205
3,209,509
Is there a way to speed up C++ compilation times in Solaris Sun Studio 12?
Since I am compiling my C++ code on a very server box (32 or 64 cores in total), is there a way of tweaking compiler options to speed up the compilation times? E.g. to tell compiler to compile independent .cpp files using multiple threads.
Sun Studio includes parallel build support in the included dmake version of make. See the dmake manual for details.
3,209,225
3,210,485
How to pass a method pointer as a template parameter
I am trying to write a code that calls a class method given as template parameter. To simplify, you can suppose the method has a single parameter (of an arbitrary type) and returns void. The goal is to avoid boilerplate in the calling site by not typing the parameter type. Here is a code sample: template <class Method> class WrapMethod { public: template <class Object> Param* getParam() { return &param_; } Run(Object* obj) { (object->*method_)(param_); } private: typedef typename boost::mpl::at_c<boost::function_types::parameter_types<Method>, 1>::type Param; Method method_; Param param_ }; Now, in the calling site, I can use the method without ever writing the type of the parameter. Foo foo; WrapMethod<BOOST_TYPEOF(&Foo::Bar)> foo_bar; foo_bar.GetParam()->FillWithSomething(); foo_bar.Run(foo); So, this code works, and is almost what I want. The only problem is that I want to get rid of the BOOST_TYPEOF macro call in the calling site. I would like to be able to write something like WrapMethod<Foo::Bar> foo_bar instead of WrapMethod<BOOST_TYPEOF(&Foo::Bar)> foo_bar. I suspect this is not possible, since there is no way of referring to a method signature other than using the method signature itself (which is a variable for WrapMethod, and something pretty large to type at the calling site) or getting the method pointer and then doing typeof. Any hints on how to fix these or different approaches on how to avoid typing the parameter type in the calling site are appreciated. Just to clarify my needs: the solution must not have the typename Param in the calling site. Also, it cannot call FillWithSomething from inside WrapMethod (or similar). Because that method name can change from Param type to Param type, it needs to live in the calling site. The solution I gave satisfies both these constraints, but needs the ugly BOOST_TYPEOF in the calling site (using it inside WrapMethod or other indirection would be fine since that is code my api users won't see as long as it is correct). Response: As far as I can say, there is no possible solution. This boil down to the fact that is impossible to write something like WrapMethod<&Foo::Bar>, if the signature of Bar is not known in advance, even though only the cardinality is necessary. More generally, you can't have template parameters that take values (not types) if the type is not fixed. For example, it is impossible to write something like typeof_literal<0>::type which evalutes to int and typeof_literal<&Foo::Bar>::type, which would evaluate to void (Foo*::)(Param) in my example. Notice that neither BOOST_TYPEOF or decltype would help because they need to live in the caling site and can't be buried deeper in the code. The legitimate but invalid syntax below would solve the problem: template <template<class T> T value> struct typeof_literal { typedef decltype(T) type; }; In C++0x, as pointed in the selected response (and in others using BOOST_AUTO), one can use the auto keyword to achieve the same goal in a different way: template <class T> WrapMethod<T> GetWrapMethod(T) { return WrapMethod<T>(); } auto foo_bar = GetWrapMethod(&Foo::Bar);
If your compiler supports decltype, use decltype: WrapMethod<decltype(&Foo::Bar)> foo_bar; EDIT: or, if you really want to save typing and have a C++0x compliant compiler: template <class T> WrapMethod<T> GetWrapMethod(T) { return WrapMethod<T>(); } auto foo_bar= GetWrapMethod(&Foo::Bar); EDIT2: Although, really, if you want it to look pretty you either have to expose users to the intricacies of the C++ language or wrap it yourself in a preprocessor macro: #define WrapMethodBlah(func) WrapMethod<decltype(func)>
3,209,611
3,209,628
Why doesn't Direct3D have it's own vertex structure?
I've always wondered the reasoning behind why we must always define D3DVERTEX. Is it because Microsoft wants to allow the opportunity to put this in a class and overload operators, or is there another reason? Thanks
It's so you can use whatever is convenient for your application. If you need a normal as part of your vertex, you can have that. If you don't need a normal then you save 12 bytes per vertex. If you need colour information, texture coordinates, specular parameters and so on then you choose to define them or not depending on your specific needs. If Microsoft were to provide a "D3DVERTEX" structure you'd either have 500 different versions, with different combinations of fields, or you'd have one enormous one that included every possible value, killing your bandwidth.
3,209,643
3,209,727
Launching external application and block current application till the launched application quit
I am not sure whether there is a way to Launch an external application, and block current application till the launched application had quit. Currently, I am using the following non-blocking method (MFC) to launch std::string str = "Notepad2.exe"; // Non-blocking. Return immediately. WinExec(str.c_str(), SW_SHOW);
ShellExecuteEx with SEE_MASK_NOCLOSEPROCESS will (among other things) give you a handle to the new process. You can do a WaitForSingleObject on that handle, which will be signaled when it terminates. BTW, for a GUI program, this is almost always a bad idea -- making your GUI unresponsive until another program exits is really a poor idea.
3,209,646
3,209,653
Does putting data into std::vector in C++ create a copy of the data?
I am interested if creating a new std::vector (or calling its assign method) creates a copy of the data? For example, void fun(char *input) { std::vector<char> v(input, input+strlen(input)); // is it safe to assume that the data input points to was COPIED into v? }
Yes. Elements are always copied into or out of STL containers. (At least until move semantics are added in C++0x) EDIT: Here's how you can test for copying yourself: #include <vector> #include <iostream> class CopyChecker { public: CopyChecker() { std::cout << "Hey, look! A new copy checker!" << std::endl; } CopyChecker(const CopyChecker& other) { std::cout << "I'm the copy checker! No, I am! Wait, the" " two of us are the same!" << std::endl; } ~CopyChecker() { std::cout << "Erroap=02-0304-231~No Carrier" << std::endl; } }; int main() { std::vector<CopyChecker> doICopy; doICopy.push_back(CopyChecker()); } The output should be: Hey, look! A new copy checker! I'm the copy checker! No, I am! Wait, the two of us are the same! Erroap=02-0304-231~No Carrier Erroap=02-0304-231~No Carrier
3,210,178
3,210,244
In Objective-C, How one can forward method to specific super class
All I knew is this: Objective-c allows us to forward method invocation to its super class by [super method] However I want forward the invocation to super.super; Skipping the immediately super class. In c++ we can easily do these by typecasting ((GrandSuper*)object).method(). Is their any provision to do the same in objective c
It's probably a bad idea to do this, although it is possible. You probably want to think of a better way to achieve whatever you're trying to do. Let's assume that you have three classes: Cat which inherits from Mammal which inherits from Animal. If you are in the method -[Cat makeNoise], you can skip -[Mammal makeNoise] and call -[Animal makeNoise] like so: -(void) makeNoise; { void(*animalMakeNoiseImp)(id,SEL) = [Animal instanceMethodForSelector:@selector(makeNoise)]; animalMakeNoiseImp(self, _cmd); }
3,210,343
3,210,457
How to Add New Members to Struct
These are functions and Struct declarations I have, and I'm not allowed to change them. DerivedA giveDerivedA (); DerivedB giveDerivedB (); struct Base{ QString elementId; QString elementType; }; struct DerivedA : Base { int a; int b; }; struct DerivedB : Base { int c; int d; }; But what I need is something like this: struct DerivedA : Base { int a; int b; void create(); QString doc; }; How can I add these method and member to structs I got? My first idea is: struct myA: DerivedA { void create(); QString doc; }; Do you have any suggestion? Edit: 2nd Alternative(Choosed) struct myA{ void create(); QString doc; private: DerivedA derivedA; };
This is similar to the problem people have extending standard library classes. If your base class doesn't have a virtual destructor, you can't safely inherit from it. In that case, you must either use free-functions (preferred anyway), or composition. Otherwise, what you have there is good.
3,210,661
3,210,754
how to get compile warning
I'm quite surprised when I compile the following code without any warning using g++ 4.1.2 with -Wall -Wextra -Wconversion enabled. I want g++ to show me every warning to avoid potential harm. I have to stick to g++ 4.1.2. #include <stdint.h> #include <string> using namespace std; int main() { uint8_t u1=1; uint64_t u64=1000; string s1=""; u1=u64; // want warning here s1=u64; // want warning here s1=u1; }
I'm afraid GCC before 4.3 doesn't seem to support this. The description of -Wconversion changed between 4.2 and 4.3 to reflect the new warning behavior, and there is no indication that pre-4.3 GCC would check for this.
3,210,759
3,211,007
Linux developers knowing C++?
I got into a discussion a while back. The company I work at develop under Linux and does so in ANSI C. A lot of benefits could come from moving to C++ as far as design goes I think. Our existing code would just have to get rid of all implicit type casts since C++ is a bit stricter about that and it would compile and run as usual. But I was told that we would never start using C++. The reason was that "Linux developers know C", but it would be very hard to find Linux developers who know C++. Personally I find this kinda strange since I started out by learning C++ on Linux. But it made me curious and I wonder if there are any statistics anywhere or if you could help me get a general feel for the validity in this statement. Would be good for future reference since I have always thought that Linux developers with knowledge in C++ wouldn't be that hard to find, but I could be totally wrong.
A lot of benefits could come from moving to C++ as far as design goes I think. Probably (depends on who would decide on the design in C++). Our existing code would just have to get rid of all implicit type casts since C++ is a bit stricter about that and it would compile and run as usual. It's not that simple. If you changed compiler options (or file extensions) to switch to C++ your code will not compile just like that (you will need to go over it and make changes). Furthermore, your existing C codebase will make for a poorly-written C++ codebase. It may also introduce all kinds of subtle bugs that to a seasoned C-thinking developer will be almost impossible to find (sizeof operator behaves differently for arrays in C and C++ for example but a seasoned C/beginner C++ developer would not even consider that the familiar sizeof in his code does something unexpected). The reason was that "Linux developers know C", but it would be very hard to find Linux developers who know C++. That's not a valid reason (if you make a job-posting online with "looking for C++ Linux developers you should get some good CVs - depending on your offer). It may be the belief of whoever can make that decision in your company or it may be just an excuse they gave to get rid of you :-\ Here are some of the reasons (against switching) that may actually apply in your case - and that your manager probably considered: the people who wrote your codebase may be good C developers but not know C++ - or be beginner C++ developers and/or poor C++ developers. Good C developers often make poor C++ developers (best practices in C++ are completely different and many times opposed to best practices in C. This is a problem because the C++ code looks familiar enough to a C developer that he will think his experience applies to it (and good design decisions in C often make for poor design decisions in C++). They may even be good C++ developers, but if that is the case, that should be unknown to your manager (if they were hired as C developers, their C++ skills probably never came up in the job interview). your senior team members may have a good understanding of your application logic. If your application switches to C++ they may have to go (and be replaced by C++ developers). Such a change would lose you team members who are very familiar with your problem domain. Depending on your specific problem domain such a loss could be enormous. Depending on the size and structure of your codebase, moving to C++ may be a very good decision. You don't give enough detail for us to know if that is the case. For example, I've seen a large C codebase that over the years ended up reinventing C++ poorly (pseudo-classes supporting virtual function tables and inheritance - with a structure holding a void* to a base structure, or a base structure having void* to specialized data created dynamically - and other monsters). Would be good for future reference since I have always thought that Linux developers with knowledge in C++ wouldn't be that hard to find, but I could be totally wrong. They shouldn't be hard to find, but that's only a valid point if you're at the beginning of your project. No good manager will consider lightly changing seasoned developers who know the problem domain with new hires just for a few design decisions. If you can provide better reasons for switching they may consider it. Good reasons for switching (for a manager) involve lower maintenance costs, lower development costs, lower risks, less effort, better progress reporting and so on. If you want to keep pushing for this change, you will have to find some good arguments in those areas on top of some good counter-arguments to his "Linux developers know C". Your arguments should be good enough that they overcome the arguments I've given above.
3,210,781
3,212,991
std::vector<float> and double* - How safe is this?
Is it safe to do this? double darray[10]; vector<float> fvector; fvector.insert(fvector.begin(), darray, darray + 10); // double to float conversion // now work with fvector VS2008 gives me a warning about the double to float conversion. How do I get rid of this warning? I don't think it makes sense to cast darray to float* as that would change the step size (stride) of the pointer. Update: I know what the warning indicates. But unlike the "afloat = adouble;" scenario where I can easily apply a cast, I am unable to eliminate the warning in this case. Edit: I've edited the code so that darray is no longer a function argument. Thanks to all those of you who pointed it out.
Use std::transform() this allows you to provide a conversion method. Then you just need a conversion method that does not generate a warning: #include <vector> #include <algorithm> #include <iterator> struct CastToFloat { float operator()(double value) const { return static_cast<float>(value);} }; int main() { double data[] = { 1, 2,3,4,5,6,7,8,9,10}; std::vector<float> fl; std::transform(data, data+10, std::back_inserter(fl), CastToFloat()); }
3,210,927
3,211,042
Usage of namespaces in c++
Can we use namespaces like in below snippet? The code compiles in both gcc and msvc, leaving me confused about namespace usage. In f1.h: namespace My { void foo(); } In f1.cpp ` void My::foo() { } I thought that the function should be defined as: namespace My { void foo() {} } Can anyone kindly explain? Thanks
It's legal to define namespace members outside of their namespace as long as their name is prefixed with the name of their namespace, and the definition actually occurs in a namespace that encloses it. It can't happen in a namespace that's nested inside the member namespace. namespace A { void f(); } void A::f() { } // prefix with "A::" namespace B { } void B::f() { } // invalid! not declared in B! namespace C { void f(); } namespace D { void C::f() { } } // invalid! D doesn't enclose C namespace E { void f(); namespace F { void E::f() { } // invalid! F is nested inside E! } } It's the same stuff as for class members, where you can also define functions outside of their class, as long as you prefix the names with the name of the class. However as for classes, namespace members must be first declared in their respective namespace before they can be defined outside out it.
3,210,958
3,211,096
How is the code memory managed?
When talking about a process' memory, I heard about things like code memory and data memory. And for the data memory, there are 2 major managing mechanisms, stack and heap. I am now wondering how is the code memory managed? And who manages it? Pardon me if my statement is not so clear. Thanks.
I recommend http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory (and the other memory related articles) if you're interested in finding out more about the details of process' memory management. code memory = Text segment Notice how the address space is 4GB. When the kernel creates a process it gives it virtual memory. Below is an example of a 32 bit OS. The kernel manages what addresses get mapped to actual RAM via the processor's MMU. So, the kernel and the MMU manage code memory, just as they manage the entire address space of a process. (source: duartes.org)
3,211,130
3,221,954
lambda expression (MSVC++ vs g++)
I have the following code #include <algorithm> #include <iostream> #include <vector> #include <functional> int main() { typedef std::vector<int> Vector; int sum=0; Vector v; for(int i=1;i<=10;++i) v.push_back(i); std::tr1::function<double()> l=[&]()->double{ std::for_each(v.begin(),v.end(),[&](int n){sum += n; //Error Here in MSVC++}); return sum; }; std::cout<<l(); std::cin.get(); } The above code produces an error on MSVC++ 10 whereas it compiles fine with g++ 4.5. The error produced is 1 IntelliSense: invalid reference to an outer-scope local variable in a lambda body c:\users\super user\documents\visual studio 2010\projects\lambda\lambda.cpp 19 46 lambda So, is there any other way to access the outer-scope variable sum without explicitly creating a new variable inside the local lambda expression(inside std::for_each)? On g++ 4.5 the code compiles fine. Does the standard(n3000 draft) say anything about it?(I don't have a copy of C++-0x(1x ?) standard at present)
Have you actually tried compiling the code in the question? Visual C++ 2010 accepts the code, as is (with the comment removed, obviously), and successfully compiles the code without error. The "error" you are seeing is not a compilation error, but an IntelliSense error. The IntelliSense error checking results in a lot of false positives (I've reported several bugs on Microsoft Connect over the past few months); in this case, IntelliSense is incorrectly saying this is an error when it is not. You have two options: you can ignore the IntelliSense false positives or you can disable the IntelliSense error checking (right-click the Error List window and uncheck "Show IntelliSense Errors"). Either way, these IntelliSense errors in no way prevent compilation from succeeding.
3,211,214
3,212,012
How to convert a unicode string to its unicode escapes?
Say I have a text "Բարև Hello Здравствуй". (I save this code in QString, but if you know other way to store this text in c++ code, you'r welcome.) How can I convert this text to Unicode escapes like this "\u1330\u1377\u1408\u1415 Hello \u1047\u1076\u1088\u1072\u1074\u1089\u1090\u1074\u1091\u1081" (see here)?
I have solved the problem with this code: EDITED TO A BETTER VERSION: (I just do not want to convert Latin symbols to Unicode, because it will consume additional space without and advantage for my problem (want to remind that I want to generate Unicode RTF)). int main(int argc, char *argv[]) { QApplication app(argc, argv); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QString str(QWidget::tr("Բարև (1-2+3/15,69_) Hello {} [2.63] Здравствуй")); QString strNew; QString isAcsii; QString tmp; foreach(QChar cr, str) { if(cr.toAscii() != QChar(0)) { isAcsii = static_cast<QString>(cr.toAscii()); strNew+=isAcsii; } else { tmp.setNum(cr.unicode()); tmp.prepend("\\u"); strNew+=tmp; } } QMessageBox::about(0,"Unicode escapes!",strNew); return app.exec(); } Thanks to @Daniel Earwicker for the algorithm and of course +1. BTW you need to specify UTF-8 for text editor encoding.
3,211,269
3,211,319
shared_from_this throws an exception
I am writing Qt-based app with Blender-like functionality. It consists of a 'framework' which is GUI + plugin system and plugins. Plugins are Qt dlls with objects (e.g. a Sphere, a Box, etc.) that can be basically created and displayed. All those objects, once created, are stored in the framework in some kind of a container structure which holds shared_ptr's to them (so actually the container is pretty much like vector<shared_ptr<INode>>) What I want is to use shared_from_this() function inside one of plugins. E.g. Here's a sample plugin (code changed for clarity): class Q_DECL_IMPORT SphereNode: public INode, public Sphere Where INode is: class INode: public QObject, public boost::enable_shared_from_this<INode> ,a base class for everything stored in the container. So the problem is that this function: void SphereNode::update() { foo(shared_from_this()); } throws a boost::bad_weak_ptr exception. A couple of notes how this SphereNode is created (a Factory class) boost::shared_ptr<INode> NodeFactory::createNode(const QString& type, QString tag) { ... QPluginLoader loader(filesPlugin_[i]); boost::shared_ptr<QObject> plugin(loader.instance()); boost::shared_ptr<INode> iNodePlugin = boost::shared_dynamic_cast<INode>(plugin); return iNodePlugin; } Any ideas?
Perhaps it is this line: boost::shared_ptr<INode> iNodePlugin = boost::shared_dynamic_cast<INode>(plugin); Which should be replaced by: boost::shared_ptr<INode> iNodePlugin = dynamic_cast<INode*>(loader.instance())->shared_from_this(); Maybe it has something to do with: boost::shared_ptr<QObject> plugin(loader.instance()); Here plugin takes ownership of the returned instance. However, the Qt documentation states that the instance will be automatically freed by the QPluginLoader upon destruction. However, this would rather cause a segfault (undefined behavior) than a regular boost::bad_weak_ptr exception. If you want to prevent this, you can specify a null_deleter that will do nothing when the reference counter reachs 0. Are you calling shared_from_this() from either a constructor or a destructor (directly or indirectly) ? If so, there is your problem. When you're in the constructor, the object is not fully created yet, so having a shared_ptr to it is invalid. To avoid this issue, you can get your shared_ptr to the object in a factory method (that you already have anyway), when the object was succesfully constructed.
3,211,463
3,213,860
What is the most efficient way to make this code thread safe?
Some C++ library I'm working on features a simple tracing mechanism which can be activated to generate log files showing which functions were called and what arguments were passed. It basically boils down to a TRACE macro being spilled all over the source of the library, and the macro expands to something like this: typedef void(*TraceProc)( const char *msg ); /* Sets 'callback' to point to the trace procedure which actually prints the given * message to some output channel, or to a null trace procedure which is a no-op when * case the given source file/line position was disabled by the client. * * This function also registers the callback pointer in an internal data structure * and resets it to zero in case the filtering configuration changed since the last * invocation of updateTraceCallback. */ void updateTraceCallback( TraceProc *callback, const char *file, unsinged int lineno ); #define TRACE(msg) \ { \ static TraceProc traceCallback = 0; \ if ( !traceCallback ) \ updateTraceCallback( &traceCallback, __FILE__, __LINE__ ); \ traceCallback( msg ); \ } The idea is that people can just say TRACE("foo hit") in their code and that will either call a debug printing function or it will be a no-op. They can use some other API (which is not shown here) to configure that only TRACE uses in locations (source file/line number) should be printed. This configuration can change at runtime. The issue with this is that this idea should now be used in a multi-threaded code base. Hence, the code which TRACE expands to needs to work correctly in the face of multiple threads of execution running the code simultaneously. There are about 20.000 different trace points in the code base right now and they are hit very often, so they should be rather efficient What is the most efficient way to make this approach thread safe? I need a solution for Windows (XP and newer) and Linux. I'm afraid of doing excessive locking just to check whether the filter configuration changed (99% of the time a trace point is hit, the configuration didn't change). I'm open to larger changes to the macro, too. So instead of discussing mutex vs. critical section performance, it would also be acceptable if the macro just sent an event to an event loop in a different thread (assuming that accessing the event loop is thread safe) and all the processing happens in the same thread, so it's synchronized using the event loop. UPDATE: I can probably simplify this question to: If I have one thread reading a pointer, and another thread which might write to the variable (but 99% of the time it doesn't), how can I avoid that the reading thread needs to lock all the time?
You could implement a configuration file version variable. When your program starts it is set to 0. The macro can hold a static int that is the last config version it saw. Then a simple atomic comparison between the last seen and the current config version will tell you if you need to do a full lock and re-call updateTraceCallback();. That way, 99% of the time you'll only add an extra atomic op, or memory barrier or something simmilar, which is very cheap. 1% of the time, just do the full mutex thing, it shouldn't affect your performance in any noticeable way, if its only 1% of the time. Edit: Some .h file: extern long trace_version; Some .cpp file: long trace_version = 0; The macro: #define TRACE(msg) { static long __lastSeenVersion = -1; static TraceProc traceCallback = 0; if ( !traceCallback || __lastSeenVersion != trace_version ) updateTraceCallback( &traceCallback, &__lastSeenVersion, __FILE__, __LINE__ ); traceCallback( msg ); } The functions for incrementing a version and updates: static long oldVersionRefcount = 0; static long curVersionRefCount = 0; void updateTraceCallback( TraceProc *callback, long &version, const char *file, unsinged int lineno ) { if ( version != trace_version ) { if ( InterlockedDecrement( oldVersionRefcount ) == 0 ) { //....free resources..... //...no mutex needed, since no one is using this,,, } //....aquire mutex and do stuff.... InterlockedIncrement( curVersionRefCount ); *version = trace_version; //...release mutex... } } void setNewTraceCallback( TraceProc *callback ) { //...aquire mutex... trace_version++; // No locks, mutexes or anything, this is atomic by itself. while ( oldVersionRefcount != 0 ) { //..sleep? } InterlockedExchange( &oldVersionRefcount, curVersionRefCount ); curVersionRefCount = 0; //.... and so on... //...release mutex... Of course, this is very simplified, since if you need to upgrade the version and the oldVersionRefCount > 0, then you're in trouble; how to solve this is up to you, since it really depends on your problem. My guess is that in those situations, you could simply wait until the ref count is zero, since the amount of time that the ref count is incremented should be the time it takes to run the macro.
3,211,566
3,211,576
Whats the significance of return by reference?
In C++, function() = 10; works if the function returns a variable by reference. What are the use cases of it?
The commonest case is to implement things like operator[]. struct A { int data[10]; int & operator[]( int i ) { return data[i]; } }; Another is to return a big object from a class via an accesor function: struct b { SomeBigThing big; const SomeBigThing & MyBig() const { return big; } }; in order to avoid the copying overhead.
3,211,614
3,282,687
Using openMP in the cuda host code?
It it possible to use openMP pragmas in the CUDA-Files (not in the kernel code)? I will combine gpu and cpu computation. But nvvc compiler fails with "cannot find Unknown option 'openmp' ", if i am linking the porgram with a openmp option (under linux) A wayaround is to use openMP-statments only in c/c++ files.
I've just found this http://www.cse.buffalo.edu/faculty/miller/Courses/CSE710/heavner.pdf Page 25 says: With gcc: -#include omp.h Add the -fopenmp flag With nvcc, this should be -Xcompiler -fopenmp as this needs to be passed directly to gcc -Xcompiler passes flags directly to host compiler Add -lgomp flag during the linking stage. I haven't tried it yet...
3,211,678
3,211,716
string contains valid characters
I am writing a method whose signature is bool isValidString(std::string value) Inside this method I want to search all the characters in value are belongs to a set of characters which is a constant string const std::string ValidCharacters("abcd") To perform this search I take one character from value and search in ValidCharacters,if this check fails then it is invalid string is there any other alternative method in STL library to do this check.
Use find_first_not_of(): bool isValidString(const std::string& s) { return std::string::npos == s.find_first_not_of("abcd"); }
3,211,691
3,211,747
What portable data backends are there which have fast append and random access?
I'm working on a Qt GUI for visualizing 'live' data which is received via a TCP/IP connection. The issue is that the data is arriving rather quickly (a few dozen MB per second) - it's coming in faster than I'm able to visualize it even though I don't do any fancy visualization - I just show the data in a QTableView object. As if that's not enough, the GUI also allows pressing a 'Freeze' button which will suspend updating the GUI (but it will keep receiving data in the background). As soon as the Freeze option was disabled, the data which has been accumulated in the background should be visualized. What I'm wondering is: since the data is coming in so quickly, I can't possibly hold all of it in the memory. The customer might even keep the GUI running over night, so gigabytes of data will accumulate. What's a good data storage system for writing this data to disk? It should have the following properties: It shouldn't be too much work to use it on a desktop system It should be fast at appending new data at the end. I never need to touch previously written data anymore, so writing into anywhere but the end is not needed. It should be possible to randomly access records in the data. This is because scrolling around in my GUI will make it necessary to quickly display the N to N+20 (or whatever the height of my table is) entries in the data stream. The data which is coming in can be separated into records, but unfortunately the records don't have a fixed size. I'd rather not impose a maximum size on them (at least not if it's possible to get good performance without doing so). Maybe some SQL database, or something like CouchDB? It would be great if somebody could share his experience with such scenarios.
I think that sqlite might do the trick. It seems to be fast. Unfortunately, I have no data flow like yours, but it works well as a backend for a log recorder. I have a GUI where you can view the n, n+k logs. You can also try SOCI as a C++ database access API, it seems to work fine with sqlite (I have not used it for now but plan to). my2c
3,211,761
3,211,795
Situations where "old" C features might be better than newer C++ ones?
Recently i had a discussion with my boss (a long time C developer) who discouraged me in using C++ streams and stick to "good old" printf & friends. Now i can understand why he is saying this and believe me i did not follow his advice. But still this is bugging me - are there things in C that are still better in some cases than newer C++ implementations of the same/similar thing? By better i mean for example performance, stability or even code readability/maintainability. And if so, can someone give me examples? I'm mainly talking about similar differences like printf/streams, not about features like inheritance or OOP for that matter. The reason why i'm asking all this is that i consider myself a C++ developer and as such I always try to code the C++ way.
C printf()-style output is typically faster than C++ ostream output. But of course it can't handle all the types that C++ output can. That's the only advantage I'm aware of - typically, because of aggressive inlining, C++ can be a lot faster than C.
3,211,771
3,211,784
How to convert int to QString?
Is there a QString function which takes an int and outputs it as a QString?
Use QString::number(): int i = 42; QString s = QString::number(i);
3,211,794
3,211,820
Unit tests for std::map
Does anyone know where I can find unit tests that will test std::map? The reason I ask is because I have written a class that acts as a replacment for std::map and has virtually all the same functionality, so unit tests for std::map will be suitable for my class, too. Of course, I can write my own, but if someone has already written extensive tests for this then that would save me a lot of time and would hopefully cover things that I might have missed. Thanks.
While i don't know how much is needed to use them stand-alone, you could take a look at libstdc++' testsuite.
3,212,058
3,212,106
C++ How to create a heterogeneous container
I need to store a series of data-points in the form of (name, value), where the value could take different types. I am trying to use a class template for each data-point. Then for each data-point I see, I want to create a new object and push it back into a vector. For each new type, I need to create a new class from the template first. But I can not store the objects created in any vector, since vectors expect the same type for all entries. The types I need to store can not be fitted in a inheritance hierarchy. They are unrelated. Also there can be more types created in future, and I do not want to change the storage service for each new type. Is there a way to create a heterogeneous container to store these entries? Thank you!
The boost library has probably what you're looking for (boost::any). You can roll your own using a wrapped pointer approach if you cannot use boost...
3,212,144
3,212,318
Qt moving from LGPL to commercial halfway through
I've never understood this bit about licensing on the Qt website. Qt Commercial Developer License The Qt Commercial Developer License is the correct license to use for the development of proprietary and/or commercial software with Qt where you do not want to share any source code. You must purchase a Qt Commercial Developer License from us or from one of our authorized resellers before you start developing commercial software. The Qt Commercial Developer License does not allow the incorporation of code developed with the Qt GNU LGPL v. 2.1 or GNU GPL v. 3.0 license versions into a commercial product. If you are starting to develop an app while you're not sure if you'll ever want to sell it (using LGPL), how would they prevent you from moving to the commercial license at some point? As long as the API is the same you simply recompile / link, no? What am I missing?
I believe that the text only refers to code that has already been distributed under LGPL, and therefore cannot be closed-sourced by switching Qt license. I think you have nothing to worry about: nobody know/cares where the undistributed code you wrote came from (Commercial Qt or LGPL Qt). As long as it hasn't been released under a LGPL license, nothing can happpen.
3,212,392
3,213,161
QTreeView, QFileSystemModel, setRootPath and QSortFilterProxyModel with RegExp for filtering
I need to show a QTreeView of a specific directory and I want to give the user the possibility to filter the files with a RegExp. As I understand the Qt Documentation I can achieve this with the classes mentioned in the title like this: // Create the Models QFileSystemModel *fileSystemModel = new QFileSystemModel(this); QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this); // Set the Root Path QModelIndex rootModelIndex = fileSystemModel->setRootPath("E:\\example"); // Assign the Model to the Proxy and the Proxy to the View proxyModel->setSourceModel(fileSystemModel); ui->fileSystemView->setModel(proxyModel); // Fix the TreeView on the Root Path of the Model ui->fileSystemView->setRootIndex(proxyModel->mapFromSource(rootModelIndex)); // Set the RegExp when the user enters it connect(ui->nameFilterLineEdit, SIGNAL(textChanged(QString)), proxyModel, SLOT(setFilterRegExp(QString))); When starting the program the TreeView is correctly fixed to the specified directory. But as soon as the user changes the RegExp it seems like the TreeView forgets its RootIndex. After removing all text in the RegExp LineEdit (or entering a RegExp like ".") it shows all directories again (on Windows this means all drives and so on) What am I doing wrong? :/
I got a response from the Qt mailing list which explained this issue: What I think is happening, is that as soon as you start filtering, the index you use as your root does no longer exist. The view then resets to an invalid index as the root index. The filtering works on the whole model tree, not just on the part you see if you start to enter your filter! I think you are going to need a modified proxy model to do what you want. It should only apply the filtering on items under your root path, but let the root path itself (and everything else) alone. So after subclassing QSortFilterProxyModel and some parent() checking in the function filterAcceptsRow() this does work as expected now!
3,212,394
3,212,413
Cross-platform compatible directory creation in C++
I need to dynamically create directory based on input filenames in C++ and it must be cross-platform compatible. I am also familiar with the boost library. The input to the directory creation function will be a string with the following prototype: void createDirectory (std::string name) Sample code would be much appreciated.
If Boost is fine, take a look at create_directory() from Boost.Filesystem.
3,212,571
3,212,635
Usefulness of the "inline" feature
There's two things about inlining: The inline keyword will be ignored if the compiler determines that the function cannot be inlined. There is a compiler optimization (on Visual Studio, I don't know about GCC) that tells the compiler to inline all functions where possible. From this I conclude that I never need to bother about inlining. I just have to turn on the compiler optimization for the release build. Or are there any situations where manually inlining would be preferred?
The inline keyword has two functions: it serves as a hint to the compiler to perform the inlining optimization (this is basically useless on modern compilers, which inline aggressively with or without the keyword) it tells the compiler/linker to ignore the One Definition Rule: that the inline'd symbol may be defined in multiple translation units (typically because it is defined in a header, that is included from multiple files). Normally, this would result in a linker error, but it is allowed when you use the inline keyword.
3,212,649
3,279,075
How to fill memory fast with a `int32_t` value?
Is there a function (SSEx intrinsics is OK) which will fill the memory with a specified int32_t value? For instance, when this value is equal to 0xAABBCC00 the result memory should look like: AABBCC00AABBCC00AABBCC00AABBCC00AABBCC00 AABBCC00AABBCC00AABBCC00AABBCC00AABBCC00 AABBCC00AABBCC00AABBCC00AABBCC00AABBCC00 AABBCC00AABBCC00AABBCC00AABBCC00AABBCC00 ... I could use std::fill or simple for-loop, but it is not fast enough. Resizing of a vector performed only once in the beginning of program, this is not an issue. The bottleneck is filling the memory. Simplified code: struct X { typedef std::vector<int32_t> int_vec_t; int_vec_t buffer; X() : buffer( 5000000 ) { /* some more action */ } ~X() { /* some code here */ } // the following function is called 25 times per second const int_vec_t& process( int32_t background, const SOME_DATA& data ); }; const X::int_vec_t& X::process( int32_t background, const SOME_DATA& data ) { // the following one string takes 30% of total time of #process function std::fill( buffer.begin(), buffer.end(), background ); // some processing // ... return buffer; }
Thanks to everyone for your answers. I've checked wj32's solution , but it shows very similar time as std::fill do. My current solution works 4 times faster (in Visual Studio 2008) than std::fill with help of the function memcpy: // fill the first quarter by the usual way std::fill(buffer.begin(), buffer.begin() + buffer.size()/4, background); // copy the first quarter to the second (very fast) memcpy(&buffer[buffer.size()/4], &buffer[0], buffer.size()/4*sizeof(background)); // copy the first half to the second (very fast) memcpy(&buffer[buffer.size()/2], &buffer[0], buffer.size()/2*sizeof(background)); In the production code one needs to add check if buffer.size() is divisible by 4 and add appropriate handling for that.
3,212,704
3,212,735
Will a boost smart pointer help me?
i am using Xerces to do some xml writing. here's a couple of lines extracted from my code: DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer(); serializer->release(); Is there a boost smart pointer that i can use, so i can avoid calling serializer->release(); as it's not exception safe. The problem as i see it is that smart pointers can only call delete on your pointer object, could it be customised to call release? thanks
Yes, smart pointers can call a custom "deleter" function object. #include <iostream> #include <tr1/memory> struct Example { void release() { std::cout << "Example::release() called\n"; } }; struct ExampleDeleter { void operator()(Example* e) { e->release(); } }; int main() { { std::tr1::shared_ptr<Example> p ( new Example, ExampleDeleter() ); } std::cout << " see?\n"; } (same for boost: see the shared_ptr(Y * p, D d); constructor.)
3,212,813
3,213,165
Ambiguous Class Namespace Issue
I... feel really silly asking this, but I'm not sure how to resolve the problem. This is a little snippit of my code (Objective-C++): #include "eq/eq.h" namespace eqOther { class Window : public eq::Window //<-- Error occurs here { public: Window( eq::Pipe* parent ) : eq::Window( parent ) {} void popup(); protected: virtual ~Window() {} virtual bool processEvent( const eq::Event& event ); private: }; } And the error I'm getting is: Use of 'Window' is ambiguous and it says it's declared in X.h as typedef XID Window and in window.h as class eq::Window which is its superclass. The class I'm declaring should be in namespace eqOther yea? eqOther::Window is different than eq::Window!? I feel soooo dumb, but I just don't see what I've done wrong...
Perhaps you have some using namespace eq; somewhere in your headers
3,212,925
3,213,415
win32 DialogBox app: how to show text from callback on the DialogBox?
I'm working on a win32 DialogBox based app. This uses DialogBox() to create the dialog box, and has a dialog box procedure which does all the usual things. The dialog box has some static text controls on it, and generally I'm showing text in these via SendDlgItemMessage() from within the dialog box procedure. However at one point the DialogBox initiates a lengthy operation. This operation has a callback with a series of status messages. I'm having some trouble showing these messages on the dialog box, for two reasons: The callback function doesn't know what the dialog box HWND is, because it gets called from the code which carries out the lengthy operation. I suppose I can define a file scope HWND variable and copy the dialog box HWND into it from the dialog box procedure just before the lengthy operation is started. That way, the callback function could have access to the dialog box HWND. But that seems awfully kludgy: is there a more elegant way? The dialog box procedure is blocked while the lengthy operation happens. This doesn't matter because it's an embedded system. But will Windows even show the text in the dialog box if I issue a SendDlgItemMessage() while the dialog box procedure is blocked? edit I've done some investigations using SendDlgItemMessage() to send a WM_SETTEXT to a static text control on a dialog. The text is displayed immediately even if the dialog box procedure is blocked.
Well, your dialog HWND is a singleton so it isn't the end of the world. But yes, the standard way this is done is by passing an opaque pointer to the code that gets the job done. Compare with the lParam argument of EnumWindows() for example, the callback gets that pointer back. Whether a control repaints itself immediately is an implementation detail. I only know of progress bar doing this. You could call UpdateWindow on the dialog window handle to get any pending paint updates flushed to the screen. The all-around better mouse trap is to perform long running tasks on a worker thread. Avoids Windows displaying the "Not Responding" ghost window, avoids timeouts on broadcast messages and numerous potential deadlock problems. But tends to be tricky to get right, you cannot update the window directly from the worker thread.
3,213,037
3,213,261
Determine if Linux or Windows in C++
I am writing a cross-platform compatible function in C++ that creates directories based on input filenames. I need to know if the machine is Linux or windows and use the appropriate forward or back slash. For the following code below, if the machine is Linux then isLinux = true. How do I determine the OS? bool isLinux; std::string slash; std::string directoryName; if isLinux slash = "/"; else slash = "\\"; end boost::filesystem::create_directory (full_path.native_directory_string() + slash + directoryName);
Use: #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) static const std::string slash="\\"; #else static const std::string slash="/"; #endif BTW, you can still safely use this slash "/" on Windows as windows understands this perfectly. So just sticking with "/" slash would solve problems for all OSes even like OpenVMS where path is foo:[bar.bee]test.ext can be represented as /foo/bar/bee/test.ext.
3,213,040
3,213,148
Compare unsigned char = 0x00 and signed char = '00'
How do i compare the following: unsigned char a = 0x00; char b = '0'; // signed char how do i write a comparison/conversion that matches a and b? thanks!
Like everyone said, they are not the same thing. But if you must compare them equal, you can do that with a lexical cast: #include <iostream> #include <boost/lexical_cast.hpp> bool compare(unsigned char val, char c) // throws if c is not a digit! { return val == boost::lexical_cast<int>(c); } int main() { unsigned char a = 0x00; char b = '0'; std::cout << std::boolalpha << compare(a, b) << '\n'; }
3,213,172
3,213,901
How to do Gtk TextIter arithmetic
I am attempting to use Gtk TextIter objects to lift three-character slices out of a TextBuffer, but am having trouble with the arithmetic. I set up an iterator p to point to the start of the range and want q to point to three characters further on. I have tried... q = p + 3; // Doesn't compile q = p; q += 3; // Doesn't compile q = p; q++; q++; q++; // Happy I'd like to know what the correct way to do this is. The third method works, but looks like a ghastly hack. Any thoughts?
If you read the documentation you'll see that TextIter doesn't have a + or += operator. It's a bidirectional iterator and not a random access iterator so this is as it should be. You can use either: q = p; std::advance(q, 3); or q = p; q.forward_chars(3);
3,213,445
3,213,458
C++ double operator+
Possible Duplicates: Incorrect floating point math? Float compile-time calculation not happening? Strange stuff going on today, I'm about to lose it... #include <iomanip> #include <iostream> using namespace std; int main() { cout << setprecision(14); cout << (1/9+1/9+4/9) << endl; } This code outputs 0 on MSVC 9.0 x64 and x86 and on GCC 4.4 x64 and x86 (default options and strict math...). And as far as I remember, 1/9+1/9+4/9 = 6/9 = 2/3 != 0
1/9 is zero, because 1 and 9 are integers and divided by integer division. The same applies to 4/9. If you want to express floating-point division through arithmetic literals, you have to either use floating-point literals 1.0/9 + 1.0/9 + 4.0/9 (or 1/9. + 1/9. + 4/9. or 1.f/9 + 1.f/9 + 4.f/9) or explicitly cast one operand to the desired floating-point type (double) 1/9 + (double) 1/9 + (double) 4/9. P.S. Finally my chance to answer this question :)
3,213,571
3,214,150
g++ __FUNCTION__ replace time
Can anyone tell when g++ replaces the __FUNCTION__ 'macro' with the string containing the function name? It seems it can replace it not until it has check the syntactical correctness of the source code, i.e. the following will not work #include <whatsneeded> #define DBG_WHEREAMI __FUNCTION__ __FILE__ __LINE__ int main(int argc, char* argv) { printf(DBG_WHEREAMI "\n"); //* } since after preprocessing using g++ -E test.cc the source looks like [...] int main(int argc, char* argv) { printf(__FUNCTION__ "test.cc" "6" "\n"); //* } and now the compiler rightly throws up because the *ed line is incorrect. Is there any way to force that replacement with a string to an earlier step so that the line is correct? Is __FUNCTION__ really replaced with a string after all? Or is it a variable in the compiled code?
Is there any way to force that replacement with a string to an earlier step so that the line is correct? No. __FUNCTION__ (and its standardized counterpart, __func__) are compiler constructs. __FILE__ and __LINE__ on the other hand, are preprocessor constructs. There is no way to make __FUNCTION__ a preprocessor construct because the preprocessor has no knowledge of the C++ language. When a source file is being preprocessed, the preprocessor has absolutely no idea about which function it is looking at because it doesn't even have a concept of functions. On the other hand, the preprocessor does know which file it is working on, and it also knows which line of the file it is looking at, so it is able to handle __FILE__ and __LINE__. This is why __func__ is defined as being equivalent to a static local variable (i.e. a compiler construct); only the compiler can provide this functionality.
3,213,591
3,213,820
Rvalues vs temporaries
Somebody generalized the statement "Temporaries are rvalues". I said "no" and gave him the following example double k=3; double& foo() { return k; } int main() { foo()=3; //foo() creates a temporary which is an lvalue } Is my interpretation correct?
Temporaries and rvalues are different (but related) concepts. Being temporary is a property of an object. Examples of objects that aren't tempory are local objects, global objects and dynamically created objects. Being an rvalue is a property of an expression. The opposite of rvalues are lvalues such as names or dereferenced pointers. The statement "Temporaries are rvalues" is meaningless. Here is the relationsip between rvalues and temporary objects: An rvalue is an expression whose evaluation creates a temporary object which is destroyed at the end of the full-expression that lexically contains the rvalue. Note that lvalues can also denote temporary objects! void blah(const std::string& s); blah(std::string("test")); Inside the function blah, the lvalue s denotes the temporary object created by evaluating the expression std::string("test"). Your comment "references are lvalues" is also meaningless. A reference is not an expression and thus cannot be an lvalue. What you really mean is: The expression function() is an lvalue if the function returns a reference.
3,213,738
3,213,979
QThread blocking main application
I have a simple form UI that has a slot for a button, starting a thread: void MainWindow::LoadImage() { aThread->run(); } And the run() method looks like this: void CameraThread::run() { qDebug("Staring Thread"); while(1) { qDebug("ping"); QThread::sleep(1); } } When I click the button that calls LoadImage(), the UI becomes unresponsive. I periodically see the "ping" message as the debug output but the UI hangs, does not respond to anything. Why is my thread not running separately? CameraThread derived as public QThread I am using gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) with QT libraries and QT Creator from Ubuntu 10.04(x86) repositories.
Short answer: Start your thread by calling aThread->start(); not run(), and make sure you thread's run() method is protected (not public). Explanation Calling start() is the correct way to start the thread, as it provides priority scheduling and actually executes the run() method in its own thread context. It looks like you are going to be loading images in this thread, so I'm going to include some tips before you run into pitfalls many people fall into while using QThread QThread itself is not a thread. It is just a wrapper around a thread, this brings us to.. signals/slots defined in the CameraThread class will not necessarily run in the thread's context, remember only the run() method and methods called from it are running in a separate thread. IMHO, subclassing QThread in the majority of cases is not the way to go. You can do it much simpler with the following code, and it will save you many headaches. class ImageLoader : public QObject { Q_OBJECT public slots: void doWork() { // do work } }; void MainWindow::MainWindow(/*params*/) { ImageLoader loader; QThread thread; loader.moveToThread( &thread ); connect( this, SIGNAL( loadImage() ), &loader ,SLOT( doWork() ) ); thread.start(); // other initialization } void MainWindow::LoadImage() { emit loadImage(); } Also read the Qt blog regarding this topic.
3,213,838
3,213,858
C++ member function masking external function - how to call external function?
In a Qt application, I'm trying to call the networking function connect() (which is from sys/socket.h). The call's being made from a QObject object, which has its own connect() member function. The QObject's connect() method is preventing me from calling the networking connect() function. Any way to use the networking connect()?
C++ member function masking external function - how to call external function? Use ::connect()
3,213,954
3,214,003
How to get length of std::stringstream without copying
How can I get the length in bytes of a stringstream. stringstream.str().length(); would copy the contents into std::string. I don't want to make a copy. Or if anyone can suggest another iostream that works in memory, can be passed off for writing to another ostream, and can get the size of it easily I'll use that.
Assuming you're talking about an ostringstream it looks like tellp might do what you want.
3,214,168
4,701,661
Linking Statically with glibc and libstdc++
I'm writing a cross-platform application which is not GNU GPL compatible. The major problem I'm currently facing is that the application is linked dynamically with glibc and libstdc++, and almost every new major update to the libraries are not backwards compatible. Hence, random crashes are seen in my application. As a workaround, I distribute binaries of my application compiled on several different systems (with different C/C++ runtime versions). But I want to do without this. So my question is, keeping licensing and everything in mind, can I link against glibc and libstdc++ statically? Also, will this cause issues with rtld?
Specifying the option -static-libgcc to the linker would cause it to link against a static version of the C library, if available on the system. Otherwise it is ignored.
3,214,250
3,214,349
Incomplete type as function parameter?
I have that template class that uses a policy for it's output and another template argument to determine the type for it's data members. Furthermore the constructor takes pointers to base classes which are stored in private pointers. Functions of this objects shall take a this pointer to the template class to give them access to the data. In code this looks like this: class ShapeGenerator; template <typename PointData, typename OutputPolicy> class ModelCreator { private: OutputPolicy output; ShapeGenerator* shape std::vector<PointData> data; public: ModelCreator (ShapeGenerator *s) : shape(s) { } void createShape() { shape->generateShape(this); } }; ShapeGenerator is an interface and shall be implemented. It looks like this: class ShapeGenerator { public: void generateShape (ModelCreator* m) = 0; }; If I compile this with g++ 4.3.4 (cygwin) I get an error in the ShapeGenerator::generateShape saying 'ModelCreater' is not a type. I put in a forward declaration of ModelCreator but it changed nothing. I played with some combinations of types and parameters, for example passing only the vector and then I got an error message that said something about incomplete types. I guess this is the problem here. So, is it possible to pass a templated type with without specific arguements? If so, how? edit: I'm not bound to the ModelCreator typename. If I have to write it more template-like this isn't problem. But I would like not to specify the types of ModelCreator in the ShapeCreator object. Is that possible? edit2: Ok, I guess I was a bit to optimistic with this "design". It would have been nice to just throw in some ingrediences and get a soup. But now the salt has to know about the kind of water in the pot. I'll change the templates to plain old composition. Thanks you guys.
If you want to use the ModelCreator with "free" template parameters, then you have to make ShapeGenerator a template too: template <typename PointData, typename OutputPolicy> class ShapeGenerator { public: void generateShape (ModelCreator<PointData,OutputPolicy>* m) = 0; }; or template <template <typename, typename> class ModelCreator> class ShapeGenerator { public: void generateShape (ModelCreator* m) = 0; }; The second version takes another template as a parameter. You would use it like this: ShapeGenerator<ModelCreator<PointDataType,OutPutPolicyType> > shapeGenerator;
3,214,278
3,214,308
Deriving a pointer type to the non-pointer class member
In book named "Using C++" by Rob McGregor there is following example of using pointer-to-member operator class mycls { public: int member; int *ptr; }; void main() { mycls MyClass; // Derive a pointer type to the non-pointer class member int mycls::*member = &mycls::member; MyClass.ptr = new int; mycls* pMyClass = &MyClass; pMyClass->*member = 5; *MyClass.ptr = 10; cout << "pMyClass->*member = " << pMyClass->*member << "\n"; // pMyClass->*member = 5 cout << "MyClass.*member = " << MyClass.*member << "\n"; // MyClass.*member = 5 cout << "*MyClass.ptr = " << *MyClass.ptr << "\n"; // *MyClass.ptr = 10 cout << "*pMyClass->ptr = " << *pMyClass->ptr << "\n"; // *pMyClass->ptr = 10 delete MyClass.ptr; } In this example I don't understand why member variable mycls::member becomes maybe a pointer after (guessing) this line of code: int mycls::*member = &mycls::member; What this does?
Suppose you had a local variable: int member; You could make a pointer to it with: int *ptr = &member; To get the pointer to member syntax, we just append mycls:: in the appropriate places: int mycls::*member = &mycls::member; It might be clearer with an example that shows how the pointer can switch between any members of the class that are of the correct type: class C { public: int a; int b; }; void main() { // make pointer to member, initially pointing to a int C::*ptrToMember = &C::a; C x; C *ptrToObj = &x; // make pointer to object x ptrToObj->*ptrToMember = 2; // store in a; ptrToMember = &C::b; // change pointer to b ptrToObj->*ptrToMember = 3; // store in b; } Note how we create the pointer to the member a before we've created an object of type C. It's only a pointer to a member, not a pointer to the member of a specific object. In the 'store' steps, we have to say which object as well as which member. Update In the comments the OP asked if this is the same: int *ptr = &(ptrToObj->a); No, it's not. That is a pointer to any int, anywhere in memory. The easiest way to understand this is to think of what it means technically. A "pointer" is an absolute location in memory: where to find an object. A "pointer-to-member" is a relative location, sometimes called an offset: where to find an object within the storage of an outer object. Internally they are just numbers. A pointer-to-member has to be added to an ordinary pointer to make another pointer. So if you have a pointer to an object (an int is an object!), you can use it to change what is stored at that absolute location in memory: *ptr = 123; But if you have a pointer-to-member, it is not a memory location. It is an offset, an amount to be added to a memory location. You cannot use it by itself. You must "add" it to an object pointer: ptrToObj->*ptrToMember = 132; This means: go to the location in memory ptrToObj, then move along by the distance ptrToMember.
3,214,297
3,214,332
How can my C/C++ application determine if the root user is executing the command?
I am writing an application that requires root user privileges to execute. If executed by a non root user, it exits and terminates with a perror message such as: pthread_getschedparam: Operation not permitted I would like to make the application more user friendly. As part of its early initialization I would like it to check if it is being executed by root or not. And if not root, it would present a message indicating that it can only be run by root, and then terminate.
getuid or geteuid would be the obvious choices. getuid checks the credentials of the actual user. The added e in geteuid stands for effective. It checks the effective credentials. Just for example, if you use sudo to run a program as root (superuser), your actual credentials are still your own account, but your effective credentials are those of the root account (or a member of the wheel group, etc.) For example, consider code like this: #include <unistd.h> #include <iostream> int main() { auto me = getuid(); auto myprivs = geteuid(); if (me == myprivs) std::cout << "Running as self\n"; else std::cout << "Running as somebody else\n"; } If you run this normally, getuid() and geteuid() will return the same value, so it'll say "running as self". If you do sudo ./a.out instead, getuid() will still return your user ID, but geteuid() will return the credentials for root or wheel, so it'll say "Running as somebody else".
3,214,340
3,214,602
Explain boost::filesystem's portable generic path format in C++
I am trying to understand portable generic path format and everything is not clicking. Can someone please explain this in terms of examples? I also have been told that I can use the forward slash in windows because windows understands both. Also is it considered good/safe style to use forward slash in windows?
I think an example is just a/b/c—the portable path format follows POSIX conventions. If you use boost::basic_path, you don't have to care about the correct slashes, the library knows how to convert the portable format to the native format. However, you should always use boost::wpath instead of boost::path, otherwise (I think) you cannot work with Unicode filenames on Windows.
3,214,569
3,214,590
“no match for 'operator<'” when trying to insert to a std::set
I'm using gcc 4.3.3 to try to compile the following code: struct testStruct { int x; int y; bool operator<(testStruct &other) { return x < other.x; } testStruct(int x_, int y_) { x = x_; y = y_; } }; int main() { multiset<testStruct> setti; setti.insert(testStruct(10,10)); return 0; } I get this error: /usr/include/c++/4.4/bits/stl_function.h|230|error: no match for ‘operator<’ in ‘__x < __y’ I suspect I'm not doing the the operator overloading as it should be done, but I just can't pinpoint the exact problem. What am I doing wrong here?
The operator must be const and take a const reference: bool operator<(const testStruct &other) const { return x < other.x; }
3,214,618
3,214,654
Unresolved external symbol in c++
#include <iostream> #include <cstdlib> using std::cout; using std::endl; using std::rand; int man(){ int t=rand(); cout<<t<<endl; return 0; } here is code for generate random number in c++ and i have mistake 1>c:\users\david\documents\visual studio 2010\Projects\random_function\Debug\random_function.exe : fatal error LNK1120: 1 unresolved externals please help
Me, I think I'd change "man" to "main" and see what happens...
3,214,837
3,214,941
C++: Why is the destructor being called here?
I guess I don't fully understand how destructors work in C++. Here is the sample program I wrote to recreate the issue: #include <iostream> #include <memory> #include <vector> using namespace std; struct Odp { int id; Odp(int id) { this->id = id; } ~Odp() { cout << "Destructing Odp " << id << endl; } }; typedef vector<shared_ptr<Odp>> OdpVec; bool findOdpWithID(int id, shared_ptr<Odp> shpoutOdp, OdpVec& vec) { shpoutOdp.reset(); for (OdpVec::iterator iter = vec.begin(); iter < vec.end(); iter++) { Odp& odp = *(iter->get()); if (odp.id == id) { shpoutOdp.reset(iter->get()); return true; } } return false; } int main() { OdpVec vec; vec.push_back(shared_ptr<Odp>(new Odp(0))); vec.push_back(shared_ptr<Odp>(new Odp(1))); vec.push_back(shared_ptr<Odp>(new Odp(2))); shared_ptr<Odp> shOdp; bool found = findOdpWithID(0, shOdp, vec); found = findOdpWithID(1, shOdp, vec); } Just before main() concludes, the output of this program is: Destructing Odp 0 Destructing Odp 1 Why does this happen? I'm retaining a reference to each of the Odp instances within the vector. Does it have something to do with passing a shared_ptr by reference? UPDATE I thought that shared_ptr::reset decremented the ref count, based on MSDN: The operators all decrement the reference count for the resource currently owned by *this but perhaps I'm misunderstanding it? UPDATE 2: Looks like this version of findOdpWithID() doesn't cause the destructor to be called: bool findOdpWithID(int id, shared_ptr<Odp> shpoutOdp, OdpVec& vec) { for (OdpVec::iterator iter = vec.begin(); iter < vec.end(); iter++) { Odp& odp = *(iter->get()); if (odp.id == id) { shpoutOdp = *iter; return true; } } return false; }
This line right here is probably what is tripping you up. shpoutOdp.reset(iter->get()); What you're doing here is getting (through get()) the naked pointer from the smart pointer, which won't have any reference tracking information on it, then telling shpoutOdp to reset itself to point at the naked pointer. When shpoutOdp gets destructed, it's not aware that there is another shared_ptr that points to the same thing, and shpoutOdp proceeds to destroy the thing it's pointed to. You should just do shpoutOdp = *iter; which will maintain the reference count properly. As an aside, reset() does decrement the reference counter (and only destroys if the count hits 0).
3,214,880
3,214,916
Non-Integer numbers in an String and using atoi
If there are non-number characters in a string and you call atoi [I'm assuming wtoi will do the same]. How will atoi treat the string? Lets say for an example I have the following strings: "20234543" "232B" "B" I'm sure that 1 will return the integer 20234543. What I'm curious is if 2 will return "232." [Thats what I need to solve my problem]. Also 3 should not return a value. Are these beliefs false? Also... if 2 does act as I believe, how does it handle the e character at the end of the string? [Thats typically used in exponential notation]
You can test this sort of thing yourself. I copied the code from the Cplusplus reference site. It looks like your intuition about the first two examples are correct, but the third example returns '0'. 'E' and 'e' are treated just like 'B' is in the second example also. So the rules are On success, the function returns the converted integral number as an int value. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.
3,215,001
3,215,498
How do I turn relational comparison of pointers into an error?
We've been bitten by the following bug many times: #include <iostream> #include <vector> #include <algorithm> using namespace std; void print(int* pn) { cout << *pn << " "; } int main() { int* n1 = new int(1); int* n2 = new int(2); int* n3 = new int(3); vector<int*> v; v.push_back(n1); v.push_back(n2); v.push_back(n3); sort(v.begin(), v.end()); // Here be dragons! for_each(v.begin(), v.end(), print); cout << endl; delete n1; delete n2; delete n3; } The problem is that std::sort is comparing integer pointers not integers, which is not what the programmer intended. Worse, the output may appear correct and deterministic (consider the order of addresses returned by new or allocated on the stack). The root problem is that sort eventually calls operator< for T, which is rarely a good idea when T is a pointer type. Is there any way to prevent this or at least get a compiler warning? For example, is there a way to create a custom version of std::sort that requires a comparison function when T is a pointer?
For pointers in general you could do this: #include <ctime> #include <vector> #include <cstdlib> #include <algorithm> #include <functional> #include <type_traits> namespace util { struct sort_pointers { bool operator() ( int *a, int *b ) { return *a < *b; } }; template <typename T, bool is_pointer = !std::tr1::is_pointer<T>::value> struct sort_helper { typedef std::less<T> wont_compare_pointers; }; template <typename T> struct sort_helper<T,false> { }; template <typename Iterator> void sort( Iterator start, Iterator end ) { std::sort( start, end, sort_helper < typename Iterator::value_type >::wont_compare_pointers() ); } template <typename Iterator, class Func> void sort( Iterator start, Iterator end, Func f ) { std::sort( start, end, f ); } } int main() { std::vector<int> v1; std::vector<int*> v2; srand(time(0)); for( int i = 0; i < 10; ++i ) { v1.push_back(rand()); } util::sort( v1.begin(), v1.end() ); for( int i = 0; i < 10; ++i ) { v2.push_back(&v1[i]); } /* util::sort( v2.begin(), v2.end() ); */ //fails. util::sort( v2.begin(), v2.end(), util::sort_pointers() ); return 0; } std::tr1::is_pointer was just what it was called in Visual Studio 2008, but I think Boost has one too, and newer compiles might provide it as std::is_pointer. I'm sure someone would be able to write a prettier solution, but this appears to work. But I must say, I agree with cogwheel, there is no reason for this, the programmer should be able to see if this is going to be a problem and act accordingly. Addition: You can generalize it a bit more I think, to automatically select a functor that will dereference the pointers and compare the values: namespace util { template <typename T> struct sort_pointers { bool operator() ( T a, T b ) { return *a < *b; } }; template <typename T, bool is_pointer = !std::tr1::is_pointer<T>::value> struct sort_helper { typedef std::less<T> compare; }; template <typename T> struct sort_helper<T,false> { typedef sort_pointers<T> compare; }; template <typename Iterator> void sort( Iterator start, Iterator end ) { std::sort( start, end, sort_helper < typename Iterator::value_type >::compare() ); } } That way you don't have to think about if you're providing it with pointers to compare or not, it will automatically be sorted out.
3,215,015
3,215,121
Is there a way to change the delete action on an existing instance of shared_ptr
I have a function where I want a cleanup action done 90% of the time, but in 10% I want some other action to be done. Is there some way to use some standard scoped control likeshared_ptr<> so that initially it can have one delete action and then later in the function the delete action can be changed? shared_ptr<T> ptr( new T, std::mem_fun_ref(&T::deleteMe) ); ptr.pn.d = std::mem_fun_ref(&T::queueMe);
I don't think you can change the deleter once the shared_ptr was created. But why would you do that ? Usually, when you create an object, you know immediatly how it must be destroyed. This is not likely to change. If you really must do some specific treatments, you still can provide a custom deleter which does special things depending on the required logic.
3,215,109
3,215,151
referencing a vector::front works, but vector::begin doesn't
I have this bit of code: cerr << client->inventory.getMisc().front()->getName() << endl; vector<itemPtr>::iterator it; it = client->inventory.getMisc().begin(); cerr << (*it)->getName() << endl; Let me explain that a bit: client is a tr1::shared_ptr that points to an object that has a member named inventory that has a private vector<itemPtr> member accessible by getMisc(). itemPtr is a typedef for tr1::shared_ptr<Item>, and getName() returns a private std::string member of Item. Essentially, client->inventory.getMisc() boils down to a std::vector, and I'm trying to get an iterator to its first element. The problem is that the fourth line segfaults. Apparently either the iterator or the shared_ptr it points to is invalid. I used the first cerr statement to test if the vector itself was valid, and it prints as it should, so I think it is. Is there anything I'm doing wrong? Alternatively, what would you guys do to debug this?
Exactly what is the signature of getMisc? If you're actually returning a std::vector<itemPtr> then you are returning a copy of the list. In that case, the first access pattern will work (slowly) because the temporary copy doesn't get destroyed until after front finishes executing, by which time the itemPtr itself is copied into a temporary. The second fails because after getting at the iterator with begin, the temporary falls out of scope and is destroyed, leaving the just-created iterator hanging.
3,215,221
3,215,264
xor all data in packet
I need a small program that can calculate the checksum from a user input. Unfortunately, all I know about the checksum is that it's xor all data in packet. I have tried to search the net for an example without any luck. I know if I have a string: 41,4D,02,41,21,04,02,02,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00 This should result in a checksum of 6A. Hopefully someone could help me. If someone has an example writen in Python 3, could also work for me
If I understand "xor all data in packet" correctly, then you should do something like this: #include <iostream> #include <vector> using namespace std; int main() { unsigned int data; vector< unsigned int > alldata; cout << "Enter a byte (in hex format, ie: 3A ) anything else print the checksum of previous input: "; while ( true ) { cin >> hex >> data; if ( cin.fail() || cin.bad() ) break; alldata.push_back( data ); cout << "Enter a byte: "; } unsigned int crc = 0; for ( int i = 0; i < alldata.size(); i++ ) crc ^= alldata[ i ]; cout << endl << "The checksum is: " << hex << uppercase << crc << endl; system( "pause" ); return 0; } The idea is to establish a variable initialized to 0 and then xor all elements of the packet with it while storing the result of the operation in the same variable on each step. EDIT: edited the answer to provide complete working example (far from perfect, but works). Usage: enter bytes as required, once you are finished with input, enter anything invalid, for example q (cannot be a hexadecimal number). You will get the checksum printed.
3,215,310
3,215,366
Buffer too small when copying a string using wcsncpy_s
This C++ code is kind of lame, but I need to maintain it. I cannot seem to figure out a "buffer too small" problem. I am using Visual Studio 2010. I will come up with minimal code required to reproduce based on the values I see in the debugger. Sorry, I will not have tested the actual snippet itself. Also, since my system clipboard is "busy" while I debug, I cannot just copy and paste, so some error might creep in somewhere, but I will double-check stuff. Trust me, you do not want to see the whole function - it is way too long to make any sense :) From tchar.h #define _tcsncpy_s wcsncpy_s From afxstr.h: typedef ATL::CStringT< TCHAR, StrTraitMFC_DLL< TCHAR > > CString; From WinNT.h: typedef WCHAR TCHAR, *PTCHAR; Oh, man, these macros never seem to end. I will stop here. Finally, from myfile.cpp: CString str; // Actually a function parameter with value "07/02/2010" DWORD nIndex = 10; DWORD nLast = 0; LPCTSTR psz = (LPCTSTR) str; // Debugger says that it also gets "07/02/2010". CString s; _tcsncpy_s( s.GetBuffer((int) (nIndex - nLast + 1)), // I added the " + 1" part hoping to fix a bug, but that changed nothing nIndex - nLast, psz + nLast, (size_t) (nIndex - nLast) ); With this I hit an assertion, and the debugger opens tcsncpy_s.inl with the following code at the end: 53 ... 54 if (available == 0) 55 { 56 if (_COUNT == _TRUNCATE) 57 { 58 _DEST[_SIZE - 1] = 0; 59 _RETURN_TRUNCATE; 60 } 61 RESET_STRING(_DEST, _SIZE); =>62 _RETURN_BUFFER_TOO_SMALL(_DEST, _SIZE); 63 } 64 _FILL_STRING(_DEST, _SIZE, _SIZE - available + 1); 65 _RETURN_NO_ERROR; 66 } 67 68 The debugger points at line 62: _RETURN_BUFFER_TOO_SMALL. Unfortunatelly I cannot view the values of things while in the tcsncpy_s.inl. Perhaps an experienced coder could tell me what is going on here? I believe (perhaps incorrectly) that this code is quite old, and not written with Unicode in mind. What is the best way to fix this sticking to the old N crappy guns (No C++0X tricks or other fancy stuff please) - I just want to put a patch on a bullet wound.
The fourth argument to strncpy_s is the number of characters to copy from the source buffer, and it does not account for the terminating null - i.e., in practice, if the source buffer contains a string that has (nIndex - nLast) or more characters, then (nIndex - nLast) will be copied, and then also a null character will be appended. So the destination buffer must be prepared to accept (nIndex - nLast + 1) characters to also account for that null. Now your +1 seemingly does that, but you should also reflect it in the second argument to strncpy_s, which tells it how large the buffer is. Change it to (nIndex - nLast + 1), and it should work.
3,215,332
3,215,346
Main only receiving first letters of arguments
int _tmain(int argc, char** argv) { FILE* file1=fopen(argv[1],"r"); FILE* file2=fopen(argv[2],"w"); } It seems as if only the first letter of the arguments is received... I don't get why! std::cout<<"Opening "<<strlen(argv[1])<<" and writing to "<<strlen(argv[2])<<std::endl; outputs 1 and 1 no matter what. (in MSVC 2010)
It's not char it's wchar_t when you are compiling with UNICODE set. It is compiled as wmain. Linker just does not notice that there is a different signature, because it's "export C" function and it's name does not contain its argument types. So it should be int _tmain(int argc, TCHAR** argv) Converting to char is tricky and not always correct - Win32 provided function will only translate the current ANSI codepage correctly. If you want to use UTF-8 in your application internals then you have to look for the converter elsewhere (such as in Boost)
3,215,362
3,215,387
C++: Difficulty with partial application
I'm trying to use partial application of function arguments so I can use STL's find_if. Here is a sample program: (Class header and implementation is merged for brevity.) #include <functional> #include <iostream> #include <vector> #include <algorithm> #include <iostream> using namespace std; struct Odp { int id; Odp(int id) { this->id = id; } ~Odp() { cout << "Destructing Odp " << id << endl; } }; typedef vector<Odp*> OdpVec; class Foo { public: void loadUp() { vec.push_back(new Odp(0)); vec.push_back(new Odp(1)); vec.push_back(new Odp(2)); } void printWithID(int id) { OdpVec::iterator iter = find_if(vec.begin(), vec.end(), bind1st(&hasID, id)); if (iter != vec.end()) { cout << "Odp at " << *iter << " has id " << id << endl; return; } cout << "No Odp with id " << id << " could be found." << endl; } private: OdpVec vec; bool hasID(int id, Odp* odp) { return odp->id == id; } }; int main() { Foo foo; foo.loadUp(); foo.printWithID(1); } However, this doesn't even compile. The error is: error C2276: '&' : illegal operation on bound member function expression What am I doing wrong here? UPDATE Making hasID() a free floating function results in this error: error C2664: 'std::find_if' : cannot convert parameter 3 from 'std::binder1st<_Fn2>' to 'std::binder1st<_Fn2>' 1> with 1> [ 1> _Fn2=bool (__cdecl *)(int,Odp &) 1> ] 1> Cannot copy construct class 'std::binder1st<_Fn2>' due to ambiguous copy constructors or no available copy constructor 1> with 1> [ 1> _Fn2=bool (__cdecl *)(int,Odp &) 1> ]
bind_1st should be used with functors not member functions. Functor is an object with overloaded operator(). You can use mem_fn to construct an adaptor around your member function. In your case, since hasID makes no use of this you could have done with just using a static method. (Then you don't have to bind this as a first argument)
3,215,618
3,216,005
The Symbol file MyFile.pdb does not match the module
I've searched on this issue, and found many flavors and ideas but no real solutions. So, donning my asbestos suit and hoping for the best, I'm going to dare ask it again. I have managed C# code that calls managed C++ code, which in turn calls unmanaged C++ code. The unmanaged C++ code is throwing an exception, and I'd like to be able to debug through it. However, when I try to (explicitly, via the Call Stack) load the symbols, I get the dreaded "The symbol file MyFile.pdb does not match the module" error. I'm guessing that this is a generic error code being returned, as the files are from the same build. Using the chkmatch tool would seem to confirm that the files do in fact match. Any help much appreciated... wTs
Might be worthwhile checking the path of the loaded dll - are you using the one you thought you where? If you are using incremental builds, you might also need idb files I had an issue where MSVC just didn't want to see any debug symbols at the time, didn't work out why, but instead worked around the issue using CrashFinder or windbg instead. Perhaps a reboot will get it working again. You might like to use symstore during your build to ensure all the pdbs are captured more reliably, that way you can debug across multiple builds of a file too.
3,215,646
3,215,745
Getting coords from Goocanvas::Points
I'm attempting to get the coordinates from an instance of Goocanvas::Points in goocanvasmm. I have this: double x = 0, y = 0; int i; Goocanvas::Points points; Glib::RefPtr<Goocanvas::Item> root = canvaswidget.get_root_item(); Glib::RefPtr<Goocanvas::Polyline> line = Goocanvas::Polyline::create(100, 100, 110, 120); root->add_child(line); points = line->property_points().get_value(); for (i = 0; i < 2; i++){ points.get_coordinate(i, &x, &y); printf("%f03, %f03", x, y); } Which should work. But it outputs this when I try to compile: main.cpp: In function ‘int main(int, char**)’: main.cpp:21: error: no matching function for call to ‘Goocanvas::Points::get_coordinate(int&, double*, double*)’ /usr/include/goocanvasmm-0.1/goocanvasmm/points.h:82: note: candidates are: void Goocanvas::Points::get_coordinate(int, double&, double&) const make: *** [all] Error 1
Have you tried this? points.get_coordinate(i, x, y);
3,215,756
3,216,156
operator= in subclass
I'm quite confused about how to solve the following problem (search both on SO and google didn't help much). Say we have a class defining basic operators and a simple vector as only data and add only additional methods in inherited classes: class Foo { public: // this only copies the data Foo& operator=(const Foo& foo); // do something that computes a new Foo from *this Foo modifiedFoo(); //.. private: std::vector<int> data; } class Bar: public Foo { public: void someNewMethod(); //.. // no new data } Inheritance now ensures that the operator= in the case bar1 = bar2 does the right thing. But from the data point of view, both Bar and Foo are basically the same, so I'd like to be able to write both Foo foo; Bar bar; foo = bar; // this ... bar = foo; // .. and this; and more specifically bar = foo.modifiedFoo(); [ Edit: And btw, this doesn't work either obviously... bar1 = bar2.modifiedFoo(); ] I thought it would be as easy as adding another Bar& operator=(const Foo & foo) in Bar, but somehow this is ignored (and I don't like this anyways, what if I derive more and more classes?) So what is the right way to go about this?? Thanks!! And sorry if this has been asked before.
Martin told you what went wrong, here's what you should do instead: Bar bar; Foo& foo = bar; // this works now Now foo is a reference to a an object, and you can have base class references (and pointers, BTW) refer to objects of derived classes. However, this bar = foo; will never work (at least not implicitly) and it shouldn't. What you're trying to do here is to assign a base class object (or reference) to a derived class. However, while a derived class can always stand in for a base class object, the opposite is not true. (You can't just mindlessly use any vehicle when what you need is a boat, because not all vehicles are boats, the vehicle you're using might be a car and you'd drown.) This is not to say that you cannot make it work. if you know how to create a derived class object from a base class object, you can write a function to do so. It's just that the compiler doesn't know how to make a car from a vehicle. As solipist has shown, such a conversion function can be a constructor. However, I would make conversion constructors explicit: class Bar: public Foo { public: explicit Bar(const Foo&); // } The explicit keyword makes sure that the compiler will never attempt to call this constructor unless you say so. If you remove it, then this code would compile: //void f(Foo); // you meant to call this, but forgot to include its header void f(Bar); // you didn't even know this was included Foo foo; f(foo); // won't compile with the above Bar class and the compiler would silently generate this code: f(Bar(foo)); While this seems handy at first, I think I have sooner or later been bitten by every single implicit conversions I allowed to creep into my code and had to remove them later. So many years ago I swore to never allow them anymore. Note that even with the explicit conversion constructor you can still call f(Bar) with a Foo object - you just have to say so explicitly: f(Bar(foo)); // compiles fine even with the explicit conversion constructor
3,215,817
3,215,892
Ballistic curve problem
Ok i know this is quite off-topic for programmers but still I need this for app, so here it is: Ballistic curve (without wind or any other conditions) is specified by these 2 lines: So, there is a problem that you got 3 unknown values: x,y and time t, but only 2 equations. You can't really compute all 3 with just these values, I got: velocity v angle Alpha origin coordinates Thus, you have to decide which one to specify. Now you have 2D tanks game, or anything like that, you know you have tank and using ballistic you have to shoot opponent down with setting angle and power. I need to know when the bullet hit the ground, it can be on-air as it fly, or precomputed. There comes up my problem. Which way to use? Pre-compute or check for hitting the ground in each step. If I would like to pre-compute, I would need to know height of terrain, which, logically would have to be constant as I don't know in which x coord. If I would know the X, it would mean that just in front of my turret is wall. So only way to get to result, when I hit the ground, would be with checking in intervals of time for hitting the ground. This is also good because the terrain doesn't have top be static yay! But isn't that too great overhead which could be made much simpler? Have you encountered with such problem/solution? Thanks in advance, btw the terrain can be flat, using lines or NURBS so I please for general solution, not specific as in which height you shoot in that will be impact.
You can compute the path of the projectile y(x) by solving one equation for t and substituting into the other. You get Then finding the landing point is a matter of computing the intersections between that function and the function that defines the height of the terrain. One intersection will be the launch point and the other will be the landing point. (If your terrain is very steep and hilly, there could be more than 2 intersections, in which case you take the first one with x greater than the launch point.) You can use any of various root-finding algorithms to actually compute the intersection; check the documentation of whatever mathematical or game-physical libraries you have to see if they provide a method to do this.
3,216,199
3,216,260
C++: Partial template specialization
I'm not getting the partial template specialization. My class looks like this: template<typename tVector, int A> class DaubechiesWavelet : public AbstractWavelet<tVector> { // line 14 public: static inline const tVector waveletCoeff() { tVector result( 2*A ); tVector sc = scalingCoeff(); for(int i = 0; i < 2*A; ++i) { result(i) = pow(-1, i) * sc(2*A - 1 - i); } return result; } static inline const tVector& scalingCoeff(); }; template<typename tVector> inline const tVector& DaubechiesWavelet<tVector, 1>::scalingCoeff() { // line 30 return tVector({ 1, 1 }); } The error gcc outputs is: line 30: error: invalid use of incomplete type ‘class numerics::wavelets::DaubechiesWavelet<tVector, 1>’ line 14: error: declaration of ‘class numerics::wavelets::DaubechiesWavelet<tVector, 1>’ I've tried several solutions, but none worked. Anybody has a hint for me?
template<typename tVector> inline const tVector& DaubechiesWavelet<tVector, 1>::scalingCoeff() { // line 30 return tVector({ 1, 1 }); } That's a definition of a member of a partial specialization that would be defined as follows template<typename tVector> class DaubechiesWavelet<tVector, 1> { /* ... */ const tVector& scalingCoeff(); /* ... */ }; It's not a specialization of the member "scalingCoeff" of the primary template "DaubechiesWavelet". Such a specialization is required to pass the value of all arguments, which your specialization does not do. To do what you want, you can use overloading though template<typename tVector, int A> class DaubechiesWavelet : public AbstractWavelet<tVector> { // line 14 template<typename T, int I> struct Params { }; public: static inline const tVector waveletCoeff() { tVector result( 2*A ); tVector sc = scalingCoeff(); for(int i = 0; i < 2*A; ++i) { result(i) = pow(-1, i) * sc(2*A - 1 - i); } return result; } static inline const tVector& scalingCoeff() { return scalingCoeffImpl(Params<tVector, A>()); } private: template<typename tVector1, int A1> static inline const tVector& scalingCoeffImpl(Params<tVector1, A1>) { /* generic impl ... */ } template<typename tVector1> static inline const tVector& scalingCoeffImpl(Params<tVector1, 1>) { return tVector({ 1, 1 }); } }; Notice that the initialization syntax you use will only work in C++0x.
3,216,298
3,216,324
Iterators and multi-dimensional vectors?
So, I am trying to build a two-dimensional vector that will hold indexes for selecting tiles from a tileset. An iterator in one dimension is simple enough: std::vector<int> vec; std::vector<int>::iterator vec_it; for(int i=5; i>0; --i){ vec.push_back(i); } //prints "5 4 3 2 1 " for(vec_it = vec.begin(); vec_it != vec.end(); ++vec_it){ std::cout<<*vec_it<<' '; } However, I'm running into trouble when adding the second dimension. Here's the code that doesn't work: std::vector<std::vector<int> > vec(5); std::vector<std::vector<int> >::iterator vec_it; std::vector<int>::iterator inner_it; for(int i=0; i<5; ++i){ vec[i].assign(5, 0); } for(vec_it = vec.begin(); vec_it != vec.end(); ++vec_it){ for(inner_it = *vec_it->begin(); inner_it != *vec_it->end(); ++inner_it){ std::cout<<*inner_it<<' '; } std::cout<<std::endl; } //should print: //0 0 0 0 0 //0 0 0 0 0 //0 0 0 0 0 //0 0 0 0 0 //0 0 0 0 0 The compile fails with a nearly-incomprehensible error where I try to do inner_it = *vec_it->begin(), so I suppose my question is, how badly did I screw up?
vec_it->begin() dereferences vec_it, giving you a reference to the vector<int> and then returns the result of calling begin() on that. You shouldn't dereference the result of that using * (doing so dereferences the iterator, yielding the element pointed at by that iterator, which is an int in this case; you want the iterator itself). Your inner for loop should look like: for(inner_it = vec_it->begin(); inner_it != vec_it->end(); ++inner_it)
3,216,309
3,216,396
Using the "curiously recurring template pattern" in a multi-file program
I'm a pretty novice (C++) programmer and have just discovered the CRTP for keeping count of objects belonging to a particular class. I implemented it like this: template <typename T> struct Counter { Counter(); virtual ~Counter(); static int count; }; template <typename T> Counter<T>::Counter() { ++count; } template <typename T> Counter<T>::~Counter() { --count; } template <typename T> int Counter<T>::count(0); which seems to work. However, it doesn't seem to like inheriting from it in a separate header file, where I declared this: class Infector : public Counter<Infector> { public: Infector(); virtual ~Infector(); virtual void infect(Infectee target); virtual void replicate() = 0; virtual void transmit() = 0; protected: private: }; Everything compiles just fine without the inheritance, so I'm fairly sure it can't see the declaration and definition of the template. Anybody have any suggestions as to where I might be going wrong and what I can do about it? Should I be using extern before my Infector definition to let the compiler know about the Counter template or something like that? Cheers, Kyle
I noticed you specifically mentioned declarations and definitions. Do you have them in separate files? If so, templates are header only creatures. You'll need to put your definitions in the header file.
3,216,400
3,217,475
Is any mainstream compiler likely to support C++0x unrestricted unions in the near future?
I keep looking, but it seems like there's zero interest from compiler developers in supporting these. To me, it seems odd - basically, current C++ has restrictions on unions that were always an irritation and never appropriate. You'd think that basically removing a few error checks would be a relatively simple way to tick an extra c++0x support box, but AFAICT no compiler developers have done so yet. Why I'm interested is because it provides a simple solution to a recurring problem in data structure coding - how to reserve memory for an instance of some unknown (template parameter) type, preferably with as much type safety as possible in the circumstances, but without invoking any constructor that happens to be defined on that type. The really important point is that alignment rules must be followed. An unrestricted union is perfect for this - it gives you a type which has no constructors or destructors, but which has the right size and alignment to allow any member. There are of course ways to explicitly construct and destruct when needed, and when you need typesafe access, you just use the appropriate union member to access it. Support for "proper" unions can be useful too, but you get huge benefits even for a single-member union such as... union Memory_For_Item_t { Item_t m_Item; }; Even with the standardized alignment handling features in C++0x, this approach wins for convenience and safety when e.g. you want space for x items in a node, not all of which will be in use (or constructed) at any time. Without C++0x, we are still in the dark ages WRT alignment issues - every compiler does it its own non-standard way. The only problem with unrestricted unions - there's no support for them that I can find.
Near future? I wouldn't count on it. As http://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport lays out well, none of the current compilers support it even though many over C++0x features are being implemented. However as N2544 explains: The current work-around to the union limitations is to create a fake union using template programming or casts. So, the situation you are describing probably already has a solution, although a bit messy.
3,216,462
3,222,668
initializing char arrays in a way similar to initializing string literals
Suppose I've following initialization of a char array: char charArray[]={'h','e','l','l','o',' ','w','o','r','l','d'}; and I also have following initialization of a string literal: char stringLiteral[]="hello world"; The only difference between contents of first array and second string is that second string's got a null character at its end. When it's the matter of initializing a char array, is there a macro or something that allows us to put our initializing text between two double quotation marks but where the array doesn't get an extra null terminating character? It just doesn't make sense to me that when a terminating null character is not needed, we should use syntax of first mentioned initialization and write two single quotation marks for each character in the initializer text, as well as virgule marks to separate characters. I should add that when I want to have a char array, it should also be obvious that I don't want to use it with functions that rely on string literals along with the fact that none of features in which using string literals results, is into my consideration. I'm thankful for your answers.
I might have found a way to do what i want though it isn't directly what I wanted, but it likely has the same effect. First consider two following classes: template <size_t size> class Cont{ public: char charArray[size]; }; template <size_t size> class ArrayToUse{ public: Cont<size> container; inline ArrayToUse(const Cont<size+1> & input):container(reinterpret_cast<const Cont<size> &>(input)){} }; Before proceeding, you might want to go here and take a look at constant expression constructors and initialization types. Now look at following code: const Cont<12> container={"hello world"}; ArrayToUse<11> temp(container); char (&charArray)[11]=temp.container.charArray; Finally initializer text is written between two double quotations.
3,216,494
3,216,755
Fastest way to do many small, blind writes on a huge file (in C++)?
I have some very large (>4 GB) files containing (millions of) fixed-length binary records. I want to (efficiently) join them to records in other files by writing pointers (i.e. 64-bit record numbers) into those records at specific offsets. To elaborate, I have a pair of lists of (key, record number) tuples sorted by key for each join I want to perform on a given pair of files, say, A and B. Iterating through a list pair and matching up the keys yields a list of (key, record number A, record number B) tuples representing the joined records (assuming a 1:1 mapping for simplicity). To complete the join, I conceptually need to seek to each A record in the list and write the corresponding B record number at the appropriate offset, and vice versa. My question is what is the fastest way to actually do this? Since the list of joined records is sorted by key, the associated record numbers are essentially random. Assuming the file is much larger than the OS disk cache, doing a bunch of random seeks and writes seems extremely inefficient. I've tried partially sorting the record numbers by putting the A->B and B->A mappings in a sparse array, and flushing the densest clusters of entries to disk whenever I run out of memory. This has the benefit of greatly increasing the chances that the appropriate records will be cached for a cluster after updating its first pointer. However, even at this point, is it generally better to do a bunch of seeks and blind writes, or to read chunks of the file manually, update the appropriate pointers, and write the chunks back out? While the former method is much simpler and could be optimized by the OS to do the bare minimum of sector reads (since it knows the sector size) and copies (it can avoid copies by reading directly into properly aligned buffers), it seems that it will incur extremely high syscall overhead. While I'd love a portable solution (even if it involves a dependency on a widely used library, such as Boost), modern Windows and Linux are the only must-haves, so I can make use of OS-specific APIs (e.g. CreateFile hints or scatter/gather I/O). However, this can involve a lot of work to even try out, so I'm wondering if anyone can tell me if it's likely worth the effort.
I've tried partially sorting the record numbers by putting the A->B and B->A mappings in a sparse array, and flushing the densest clusters of entries to disk whenever I run out of memory. it seems that it will incur extremely high syscall overhead. You can use memory mapped access to the file to avoid syscall overhead. mmap() on *NIX, and CreateFileMapping() on Windows. Split file logically into blocks, e.g. 32MB. If somethings needs to be changed in the block, mmap() it , modify data, optionally msync() if desired, munmap() and then move to the next block. That would have been something I have tried first. OS would automatically read whatever needs to be read (on first access to the data), and it will queue IO anyway it likes. Important things to keep in mind is that the real IO isn't that fast. Performance-wise limiting factors for random access are (1) the number of IOs per second (IOPS) storage can handle and (2) the number of disk seeks. (Usual IOPS is in hundreds range. Usual seek latency is 3-5ms.) Storage for example can read/write 50MB/s: one continuous block of 50MB in one second. But if you would try to patch byte-wise 50MB file, then seek times would simply kill the performance. Up to some limit, it is OK to read more and write more, even if to update only few bytes. Another limit to observe is the OS' max size of IO operation: it depends on the storage but most OSs would split IO tasks larger than 128K. The limit can be changed and best if it is synchronized with the similar limit in the storage. Also keep in mind the storage. Many people forget that storage is often only one. I'm trying here to say that starting crapload of threads doesn't help IO, unless you have multiple storages. Even single CPU/core is capable of easily saturating RAID10 with its 800 read IOPS and 400 write IOPS limits. (But a dedicated thread per storage at least theoretically makes sense.) Hope that helps. Other people here often mention Boost.Asio which I have no experience with - but it is worth checking. P.S. Frankly, I would love to hear other (more informative) responses to your question. I was in the boat several times already, yet had no chance to really get down to it. Books/links/etc related to IO optimizations (regardless of platform) are welcome ;)
3,216,805
3,226,081
Help me translate Python code which replaces an extension in file name to C++
I apologize if you know nothing about Python, however, the following snippet should be very readable to anyone. The only trick to watch out for - indexing a list with [-1] gives you the last element if there is one, or raises an exception. >>> fileName = 'TheFileName.Something.xMl' >>> fileNameList = fileName.split('.') >>> assert(len(fileNameList) > 1) # Must have at least one period in it >>> assert(fileNameList[-1].lower() == 'xml') >>> fileNameList[-1] = 'bak' >>> fileName = '.'.join(fileNameList) >>> print(fileName) TheFileName.Something.bak I need to convert this logic into C++ (the language I am actually using, but so far suck at) function with the following signature: void PopulateBackupFileNameOrDie(CAtlString& strBackupFileName, CAtlString& strXmlFileName);. Here strXmlFileName is "input", strBackupFileName is "output" (should I reverse the oprder of the two?). The tricky part is that (correct me if I am wrong) I am working with a Unicode string, so looking for these characters: .xmlXML is not as straight-forward. Latest Python does not have these issues because '.' and "." are both Unicode strings (not a "char" type) of length 1, both contain just a dot. Notice that the return type is void - do not worry much about it. I do not want to bore you with details of how we communicate an error back to the user. In my Python example I just used an assert. You can do something like that or just include a comment such as // ERROR: [REASON]. Please ask if something is not clear. Suggestions to use std::string, etc. instead of CAtlString for function parameters are not what I am looking for. You may convert them inside the function if you have to, but I would prefer not mixing different string types in one function. I am compiling this C++ on Windows, using VS2010. This implies that I WILL NOT install BOOST, QTString or other libraries which are not available out of the box. Stealing a boost or other header to enable some magic is also not the right solution. Thanks.
If you're using ATL why not just use CAtlString's methods? CAtlString filename = _T("TheFileName.Something.xMl"); //search for '.' from the end int dotIdx = filename.ReverseFind( _T('.') ); if( dotIdx != -1 ) { //extract the file extension CAtlString ext = filename.Right( filename.GetLength() - dotIdx ); if( ext.CompareNoCase( _T(".xml" ) ) == 0 ) { filename.Delete( dotIdx, ext.GetLength() ); //remove extension filename += _T(".bak"); } }
3,216,935
3,226,644
Can CMake generate build scripts which do *not* use cmake?
Question: Can CMake generate build scripts that do not, in any way, use CMake? If not, how hard is it to gut a CMake generated automake script to not make any checks against CMake? I am a big fan of CMake to the point where I am championing the idea that we transition to it in my current work environment. One thing that could ease this transition from our current build system to CMake would be if I could demonstrate that CMake can generate automake files that do not require cmake themselves. Clearly, I would never want to do this for day to day use, but having the ability to easily create a branch of our code that can be built from source without requiring cmake would go a long way in helping me make my case.
No, CMake cannot do this. It doesn't really make sense, either, since without any CMake-support at build-time, there would be no way to check or update the makefiles/project-files themselves when the CMakeLists.txt files have changed. If you are moving from Visual Studio to CMake, you may want to take a look at vcproj2cmake.
3,216,948
3,216,969
C++ Pass By Const Reference and Return By Const Reference
I'm trying to understand if there is any benefit to returning a const reference. I have a factorial function that normally looks like this: unsigned long factorial(unsigned long n) { return (n == 0) ? 1 : n * factorial(n - 1); } I'm assuming that there will be a performance increase when we pass by const reference and we return a const reference... but const-correctness always confuses me. const unsigned long & factorial(const unsigned long& n) { return (n == 0) ? 1 : n * factorial(n - 1); } Is it valid to return a const reference? Furthermore, could somebody please tell me: is it beneficial?
This is invalid. You can't return reference to a local variable. MSVS C++ compiler even gives the following warning: main.cc : warning C4172: returning address of local variable or temporary Not quite sure about GCC, but probably the result would be the same.
3,217,004
3,242,958
Shared pointers and building in SIP4 (was: Dynamic casting in SWIG/python?)
So I'm playing about with Python, C++0x, and SWIG 2.0. I've got a header that looks like this: #include <string> #include <iostream> #include <memory> using namespace std; struct Base { virtual string name(); int foo; shared_ptr<Base> mine; Base(int); virtual ~Base() {} virtual void doit(shared_ptr<Base> b) { cout << name() << " doing it to " << b->name() << endl; mine = b; } virtual shared_ptr<Base> getit() { return mine; } }; struct Derived : Base { virtual string name(); int bar; Derived(int, int); }; Meanwhile, the interface file looks like this: %module(directors="1") foo %feature("director"); %include <std_string.i> %include <std_shared_ptr.i> %shared_ptr(Base) %shared_ptr(Derived) %{ #define SWIG_FILE_WITH_INIT #include "foo.hpp" %} %include "foo.hpp" My Python session then goes like this: >>> import foo >>> b = foo.Base(42) >>> d = foo.Derived(23,64) >>> b.doit(d) Base doing it to Derived >>> g = b.getit() >>> g <foo.Base; proxy of <Swig Object of type 'std::shared_ptr< Base > *' at 0x7f7bd1391930> > >>> d <foo.Derived; proxy of <Swig Object of type 'std::shared_ptr< Derived > *' at 0x7f7bd137ce10> > >>> d == g False >>> d is g False >>> d.foo == g.foo True >>> d.bar 64 >>> g.bar Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Base' object has no attribute 'bar' I can't seem to figure out how to retrieve the "original" proxy object here. Must I produce a function for each and every base class to perform the dynamic_pointer_cast? And if so, what of Director subclasses implemented in Python? I get the feeling there's a switch or feature I can turn on here to get SWIG to do the necessary table lookups and produce the object I want, but I haven't found it yet. (Note: The behavior is similar if I use raw pointers instead of shared pointers, and I can't figure out how to get SWIG to dynamic_cast those either) Update If this sort of behavior (specifically, retrieving the most-derived proxy from a C++ container class that holds pointers to the base class) isn't possible in SWIG, then how about SIP or some other wrapper generator for Python? Update #2 Since SIP4 looks like it works a bit better as far as retrieving the wrapped object sensibly, I'll change the question once again. Check my self answer below for details on my current issues. I'll still accept a good answer for the original SWIG question since I prefer it overall, but my new questions are, basically: How can I deal sanely with wrappers around shared_ptrs rather than raw pointers? If it helps, all of my classes subclass enable_shared_from_this from their generic base classes and expose an appropriate function to get the shared pointer. How can I, using either of SIP4's build systems (Makefile generator or distutils extension), build my little example project without having to first generate and install a shared library or manually edit the generated Makefile?
To (partially) answer my own question, SIP appears to do the right thing, both for the C++ "Derived" class as well as for a Python-level subclass — at least, when I use raw pointers. Looks like I'll need to figure out how to get it to work with shared_ptrs (looks not quite as easy as %include <std_shared_ptr.i> in SWIG). Also, both of SIPs "build system" options (Makefile generator and distutils extension) seem a little odd. Neither example in their manual "just works" - it looks like they expect it to be obvious that you're supposed to compile and install a shared library and header file in your library/include paths for the little Hello World library you're trying to wrap. Perhaps there's an "I just want to build and run this self-contained thing right here" option that I missed, but even python setup.py build_ext --inplace fails because it can't find the wrapped header that I've placed in the current directory, which is obviously a confusing place for it, I know.
3,217,056
3,217,069
ReadFile() Output to WinAPI edit Dialog
Ok, let's see if this all makes sense. Today, as I began working on a small project, I ran into an error I can't seem to get over. The function of the program I am working on is to read data from a pipe (which is the output of another program) and update an HWND ("edit") control dialog using WinAPI. Now, I've been successful at updating the dialog: sort of. If I send the character buffer from the ::ReadFile() function to the dialog, I get the proper output but with a ton of extra characters I don't want. So how can I simply strip it to the output I'm looking for, or is there a better way to accomplish what I'm attempting? Perhaps take the output and WriteFile(); or something similar to decipherable text? Here is what's happening: some output...'Hola Mondo' means... Hello word!ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ$ Here is what I want to happen: some output...'Hola Mondo' means... Hello word! Thanks so much for your help! Regards, Dennis M.
Check the "Bytes Read" output argument of ReadFile so you know how long the string is, then put a terminating NUL (`'\0') character at that offset.
3,217,202
3,217,293
How to look at the data stored in a QMap?
How to look at the data stored in QMap without iterating through it? I am trying to debug an application using QMap with many keys, do you know a way to look at the data in QMap without iterating through each value?
This will dump the content of a QMap (and other Qt types) to stderr: qDebug() << yourQMap;
3,217,390
3,217,430
clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom)
Why does C++ have public members that anyone can call and friend declarations that expose all private members to given foreign classes or methods but offer no syntax to expose particular members to given callers? I want to express interfaces with some routines to be invoked only by known callers without having to give those callers complete access to all privates, which feels like a reasonable thing to want. The best I could come up with myself (below) and suggestions by others so far revolve around idioms/pattern of varying indirectness, where I really just want a way to have single, simple class definitions that explicitly indicate what callers (more granularly than me, my children, or absolutely anybody) can access which members. What is the best way to express the concept below? // Can I grant Y::usesX(...) selective X::restricted(...) access more cleanly? void Y::usesX(int n, X *x, int m) { X::AttorneyY::restricted(*x, n); } struct X { class AttorneyY; // Proxies restricted state to part or all of Y. private: void restricted(int); // Something preferably selectively available. friend class AttorneyY; // Give trusted member class private access. int personal_; // Truly private state ... }; // Single abstract permission. Can add more friends or forwards. class X::AttorneyY { friend void Y::usesX(int, X *, int); inline static void restricted(X &x, int n) { x.restricted(n); } }; I'm nowhere near being a software organization guru, but it feels like interface simplicity and the principle of least privilege are directly at odds in this aspect of the language. A clearer example for my desire might be a Person class with declared methods like takePill(Medicine *) tellTheTruth() and forfeitDollars(unsigned int) that only Physician, Judge, or TaxMan instances/member methods, respectively, should even consider invoking. Needing one-time proxy or interface classes for each major interface aspect sits ill with me, but please speak up if you know I'm missing something. Answer accepted from Drew Hall: Dr Dobbs - Friendship and the Attorney-Client Idiom The code above originally called the wrapper class 'Proxy' instead of 'Attorney' and used pointers instead of references but was otherwise equivalent to what Drew found, which I then deemed the best generally known solution. (Not to pat myself on the back too hard...) I also changed the signature of 'restricted' to demonstrate parameter forwarding. The overall cost of this idiom is one class and one friend declaration per permission set, one friend declaration per set approved caller, and one forwarding wrapper per exposed method per permission set. Most of the better discussion below revolves around the forwarding call boilerplate that a very similar 'Key' idiom avoids at the expense of less direct protection.
The Attorney-Client idiom may be what you're looking for. The mechanics are not too different from your member proxy class solution, but this way is more idiomatic.