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
5,002,616
5,009,594
partial specialization of function templates
In the below code snippet, template<typename T1> void func(T1& t) { cout << "all" << endl; } template<typename T2> void func(T2 &t) { cout << "float" << endl; } // I do not want this // template<> void func(float &t) int main() { int i; float f; func(i); // should print "all" func(f); // should p...
Write a type traits class for your condition: template<class T> struct IsIntFloatOrString { enum { value = boost::is_same<T, int>::value or boost::is_same<T, float>::value or boost::is_same<T, string>::value }; }; Use boost::enable_if and disable_if: template<typename T1> typename boost::...
5,002,643
5,002,715
Get device interface from SetupDiGetClassDevs
is it possible to somehow get interface string for using with CreateFile from SetupDiGetClassDevs function or related functions? I have to scan for my devices connected to computer.
For each device returned from SetupDiGetClassDevs, you need to enumerate device interfaces using SetupDiEnumDeviceInterfaces, and then retrieve detail data using SetupDiGetDeviceInterfaceDetail. The SP_DEVICE_INTERFACE_DETAIL_DATA structure filled in by SetupDiGetDeviceInterfaceDetail contains the correct CreateFile pa...
5,002,761
5,004,374
boost::asio server - detect failure to listen to server port
I have a boost::asio based server which works fine, except that I'm trying to add a check that nothing else is accepting connections on the same port. If I create two of the servers, one of them consistently accepts the connections, but the other does not report any error ( which of the two accepts all connections appe...
boost::asio::ip::tcp::acceptor constructor you use has a default argument reuse_address = true. this sets SO_REUSEADDR socket option. disabling this option you'll receive error on acceptor.listen(). more info about SO_REUSEADDR here Be aware that this option is treated differently on windows and linux
5,003,042
5,003,083
Is there any alternative way of writing the code instaed of using switch statement in c++
We are building DLL's using C++ .As we are having 400 cases in the size of the DLL is getting bigger in size so is there any alternative way of using instead of switch
Depends on the data type you're switching over. If it's a dense int range, use a lookup table storing function pointers. In other cases use a std::map from switched-over values to function pointers.
5,003,117
5,003,348
remove escape characters from a char
I've been working with this for about 2 days now. I'm stuck, with a rather simple annoyance, but I'm not capable of solving it. My programs basicly recieves a TCP connection from a PHP script. And the message which is send is stored in char buffer[1024];. Okay this buffer variable contains an unique key, which is bein...
If you are using C++ use std::string instead of char []. You cannot compare two char [] in way you try to do this (they are pointers to memory), but it's possible with std::string. If it's somehow mandatory to use char[] in your case, use strcmp.
5,003,354
5,003,439
Memory Mapped files - How to insert a strip of data in other process
My file(sample.txt) has 10 chars. I opened the file in write mode, have done a createfilemapping("mymapping"). Then I Hold the process by getchar. Then opened another process which does the below openfilemapping("mymapping"), char*k = (char*)mapviewoffile Now I can access the value of sample.txt and change it via k...
Shared-memory mappings are fixed in size upon creation. You will need to call CreateFileMapping again with a larger mapping size. This will automatically extend the file, at which point you can MapViewOfFile again, and write in whatever data you want. Note that you will need to change the name of the file mapping, unle...
5,003,396
5,004,984
`pow` not returning (IEEE)denormalized floating-point numbers?
Why does pow (math.h or cmath) not returning denormalized numbers? For example, this: float f = pow (2.f, -126); double d = pow (2.0, -1022); gives a non-zero answer for f and d, but using a smaller exponent, i.e -127 for f and -1023 for d, returns a zero, although even 2 ^ -149 (for singles) and 2 ^ -1074 (for double...
It sounds like VC is flushing denormals. This can be controlled by the following: #include <float.h> #pragma fenv_access (on) int main() { _controlfp(_DN_SAVE, _MCW_DN); float f = pow (2.f, -127); double d = pow (2.0, -1023); }
5,003,519
5,003,546
3D points projection to 2D XY plane
I have a 3 Dimentional point set (x,y,z).I need to project these points into 2 dimentional XY plane using orthogonal projection. so my question is, how to convert these points into 2D? is it correct if I make Z=0 only? If it is not correct please any one help me to slove this problem. Also I want to programming this in...
If the axes of your coordinate system are orthogonal to each other, you get the orthogonal projection to the xy-plane by simply setting the z coordinate to zero -- you are right with this.
5,003,543
5,003,821
C++0x with Qt Creator
I'm trying to use new C++0x features in Qt Creator under Windows (Qt Creator 2.0.1). I read the thread Configuring the GCC compiler switches in Qt, Qt Creator, and QMake and added QMAKE_CXXFLAGS += -std=c++0x to .pro file. After it Qt Creator gives me very strange errors on this simple code: #include <memory> int main...
First off, it could be that the library headers just don't represent their dependencies properly. Try adding an #include <cstdio> and perhaps (unfortunately) a using namespace std; to your file at the top. Failing that, several people seem to have had issues with MinGW and swprintf. This mailing list post suggests ad...
5,004,002
5,004,352
Is fclose needed when fopen has failed?
consider the below code snippet. { .... FILE *fptr = fopen("file_that_does_not_exist","r"); ... } here, if fopen fails, do we still need to call fclose() for some cleanup ??
Its simple friend, i mean just imagine.... Do you have to shutdown a computer even if it fails to boot up.... :D Just the same way you don't need to close a file which you actually never opened. Some extra tip : fclose is used just for the sake of freeing the file so that it could be used by some other applicatio...
5,004,011
5,004,100
C++ namespace not declared but it is?
I'm having a compile time problem. New to C++ so I'm sure it's simple. I am gettign the current error. diarydb.cpp: In function ‘bool editdate(int, mysqlpp::Connection&)’: diarydb.cpp:413: error: ‘format_tests’ has not been declared but diardby.cpp I have declared format_tests here namespace format_tests { bool test...
Looks like the file in which you have format_tests::testdateformat(date) cannot see the namespace format_tests { bool testdateformat(string &date); }; Have you included the header file where the testdateformat is declaired?
5,004,088
5,004,571
Accessing Values in a Class Similar to boost::any
I'm making a simple boost::any-like class for educational purposes, but I can't figure out how to access the stored value. I can set the value perfectly, but when I try to access any member in the "holder" class the compiler just complains that the member wasn't found in the class it was derived from. I can't declare...
It's fine to add virtual functions to templates- just the functions themselves cannot be templates. A templated class or struct can still have virtual functions just fine. You need to use the magic of dynamic_cast. class Element { struct ValueStorageBase { virtual ~ValueStorageBase() {} }; temp...
5,004,162
5,004,391
What does it mean for a data structure to be "intrusive"?
I've seen the term intrusive used to describe data structures like lists and stacks, but what does it mean? Can you give a code example of an intrusive data structure, and how it differs from a non-intrusive one? Also, why make it intrusive (or, non-intrusive)? What are the benefits? What are the disadvantages?
An intrusive data structure is one that requires help from the elements it intends to store in order to store them. Let me reword that. When you put something into that data structure, that "something" becomes aware of the fact that it is in that data structure, in some way. Adding the element to the data structure cha...
5,004,537
5,004,632
Simple Cross Platform Clipboard Library?
I was wondering if one was out there. Really all I need is a way to copy and paste strings, like from game to Notepad and vice versa. Thanks
Each application has to provide support for it. Notepad does. If you want your application to provide it, then you have to implement it. Luckily this is easy if you're using the right tools. Cross-platform programming frameworks, such as Qt, usually have classes that encapsulate clipboard operations across platforms. U...
5,004,543
5,004,566
Converting CString to unsigned long
I am trying to convert a string to unsigned long. Here is the code lCardNum = wcstoul(sCardNo.GetBuffer(sCardNo.GetLength()), NULL,0); My sCardNo(CString) value is 4294967359. Why do I get lCardNum(unsigned long) as 4294967295?
Assuming that your unsigned long integer is 32-bits wide, then you are overflowing it. 0xFFFFFFFF is 4294967295. Your wanted 4294967359 is 0x10000003F, i.e., it needs 33 bits. Go for unsigned long long or __int64 on a Windows box, lookup _wcstoui64.
5,004,699
5,004,918
C++ boost::ptr_map with abstract base class causing insertion issues
Following on from my last question I have an abstract base class Action which acts as an interface for executing various different actions. In order to implement an abstraction layer, I have an ActionHandler class that stores various actions in this: class ActionHandler { public: ActionHandler(); ~ActionHandler...
As you pointed out, the method you're calling is std::pair<iterator,bool> insert( key_type& k, T* x ); but the first argument is not of a type that can be bound to a non-const reference to std::string. You would have to either make the key an lvalue std::string key = "help"; cmdmap.insert(key, new DisplayHelpAction()...
5,004,739
5,004,860
Howto create ATL/C++ ActiveX DLL in Visual Studio 2005
I need to create an ActiveX DLL (not a control). I know that VB6 was able to create this project, but I would like to write this DLL with C++. VS2005 doesn't support any project template to create such a component. I tried to create a COM DLL with ATL, but I'm not sure that it can be considered as an ActiveX DLL. How c...
A COM DLL is the same thing as an ActiveX DLL. An ActiveX control is an ActiveX/COM DLL that implements certain common interfaces for hosting in a container application.
5,004,858
5,004,874
Why is std::min failing when windows.h is included?
#include <algorithm> #include <Windows.h> int main() { int k = std::min(3, 4); return 0; } What is windows doing if I include Windows.h? I can't use std::min in visual studio 2005. The error message is: error C2589: '(' : illegal token on right side of '::' error C2059: syntax error : '::'
The windows.h header file (or more correctly, windef.h that it includes in turn) has macros for min and max which are interfering. You should #define NOMINMAX before including it. In fact, you should probably do that even if there were no conflict, since the naive definition of the macro shows why function-like macros...
5,005,163
5,005,222
basic structure of com object
What is the basic structure of a com object?
A COM object doesn't have any defined structure, beyond the vtable (virtual function pointer table) associated with each of its interfaces. See this which is more or less the same question.
5,005,186
5,005,232
Can someone explain smart pointers in plain English?
Today I was asked about smart pointers in C++, and I can't find anywhere useful information about it.. Please, can someone tell: What is smart pointers? When do you need it? Do you have any example where smart pointers is actually useful? Thank you!
Primarily, smart pointers help you to: Avoid leaks when exceptions are thrown. When an exception is thrown, you don't want any objects that are allocated earlier in the try block to be leaked. By wrapping them in smart pointers, which will be destroyed when the try block is exited, those objects will get properly dest...
5,005,267
5,005,465
com object and interfaces
What is an interface connected to a com object?
Each object implements one or more COM interfaces. A COM interface is a fixed description of what an object can do - in terms of C++ that's a class without member variables and with pure virtual member functions only. A COM class is an implementation of one or more interfaces - in terms of C++ it's a class (usually wit...
5,005,292
5,007,736
copying between interleaved openGL Vertex Buffer Objects
using opengl 3.3, radeon 3870HD, c++.. I got question about interleaved arrays of data. I got in my application structure in vector, which is send as data to buffer object. Something like this: struct data{ int a; int b; int c; }; std::vector<data> datVec; ... glBufferData(GL_ARRAY_BUFFER, sizeof(data)*datVec.si...
I would separate the dynamic part with a static one (your point 2). If you still want to keep them interleaved into a single buffer, and you have some spare video memory, you can do the following: Copy the original interleaved array into a backup one. This requires memory for all components rather than only dynamic on...
5,005,317
5,005,415
Read line of numbers using C++
What's the standard way of reading a "line of numbers" and store those numbers inside a vector. file.in 12 12 9 8 17 101 2 Should I read the file line by line, split the line with multiple numbers, and store the tokens in the array ? What should I use for that ?
#include <vector> #include <fstream> #include <iterator> #include <algorithm> std::vector<int> data; std::ifstream file("numbers.txt"); std::copy(std::istream_iterator<int>(file), std::istream_iterator<int>(), std::back_inserter(data));
5,005,448
5,005,489
Returning a struct without initializing it
I have a very simple color struct like this struct { unsigned char red; unsigned char green; unsigned char blue; unsigned char alpha; } RGBA; Now in some function, I would like to return a structure like this. But I can't figure out how to do that. All I can think of is creating a local structure, fill...
First, in your first snippet, RGBA is an object whose type is an unnamed struct I don't think that's what you intended. You probably meant either: typedef struct { ... } RGBA; /* what a lot of C programmers do */ or struct RGBA { ... }; /* probably what you meant */ Anyway, to answer your question, give it a constru...
5,005,673
5,005,743
C++: follow-up question on reading from an external file using getline(). How to get a subset of the file data?
I need to read in numbers from an external file and store them in a vector of ints. I can do this now thanks to Howard Hinnant and wilhelmtell, who patiently helped figure out why my coding was not working yesterday. I have been trying to figure out how to incorporate an additional feature into the code, but I have ex...
When you reach the start of a block just read to the end of the line into a string, then parse the string. std::getline( theStream, block, '\n' ); std::istringstream blockStream( block ); std::getline( blockStream, line, '\'' ); // etc
5,005,854
5,006,180
C++, Qt 4 Sqlite: can't create table
I'm trying to use sqlite as database for a symbian app but I can't create a table. Here's the code: bool DatabaseManager::createExpenseTable(){ if(QFile::exists(dbName)){ this->showDebugMsg("Database file exist"); }else{ this->showDebugMsg("Database file exist DOES NOT exist"); } // Cr...
Wait, I found the problem. with this code: this->showDebugMsg(query.lastError().text()); I saw that "the table expense already exist" and so, it doesn't create a new one. sorry for bothering you all.
5,005,863
5,006,072
is it possible to convert bitset<8> to an array of characters of integers?
I have bitset<8> v8 and its value is something like "11001101", something in binary, how can we convert it to an array of characters or integers in c++?
To convert to an array of char, you could use the bitset::to_string() function to obtain the string representation and then copy individual characters from that string: #include <iostream> #include <algorithm> #include <string> #include <bitset> int main() { std::bitset<8> v8 = 0xcd; std::string v8_str...
5,005,889
5,006,187
Consuming a web service in a Visual C++ 2008 DLL
I need to call a third party Web Service from within a VC++ 2008 DLL. The DLL is using MFC in a Shared DLL and it is not using ATL. In solution explorer the Add Web Reference item is grayed. any suggestion? thank you in advance stefano
Since calling a WS in C# is trivial, first create a dll in C# wrapping the service call and expose it via COM interop to your C++ code. Even if it seems tricky is the less troubles way to go.
5,005,896
5,005,936
How to get the value of const string& in C++
I have a function that takes const string& value as argument. I am trying to get the value of this string so that I can manipulate it in the function. So I want to store the value into a string returnVal but this does not work: string returnVal = *value
Simply do string returnVal = value; Since value is not a pointer but a reference you do not need the pointer-dereferencing-operator (otherwise it would be const string *value).
5,005,997
5,006,047
Getting square instead of new line in output to a file
I'm trying to get an output into a text file. Always when I add to in endl or "\n" it doesn't start a new line, but puts a square in the file instead. I've done it in Dev-C++ and also with Qt, but always the same result. Do you know where's the problem? Thanks for your answers.
If you want to display a new line in Windows, use "\r\n" instead "\n". (read more at http://en.wikipedia.org/wiki/Newline#Representations)
5,006,092
5,014,160
STD::string as a Member Parameter for Dynamically Allocated Objects
I wish to dynamically allocate set of objects(can be several hundreds). Part of those objects are text fields. Because std::string offers nice string manipulations, I would prefer having the object member parameters of type std:string. However, std::string is dynamically resizable object. To me, this goes against the d...
Your question is a little difficult to parse, and sample code would have made that easier, I think. Am I right in assuming that you have a class that contains a string, like so: class foo { public: std::string str; }; and you wonder how the string is resized? Let me try and explain: The size of objects of class ...
5,006,239
5,006,312
Windows: Read CMD-Output and bring it to a textbox (Edit) in C++
I want to put the output of an cmd-command (e.g. "assoc") into a textbox. I managed this with pipes. BUT New lines (\n) on the console aren't shown in the textbox... So if "assoc" results in .xxx=xxx .yyy=yyy .zzz=zzz there is .xxx=xxx.yyy=yyy.zzz=zzz in the textbox So what can I do?
Convert LF (\n) char to CR/LF (\r\n) in the output.
5,006,378
5,006,736
Passing argument to a function
Is it a bad programming principle to pass arg to a function which isn't "exact match" type wise but has trivial or user defined conversion to this type? For example: void f(bool option); and later in main (this is highly hypothetical so please don't give advise on that code): int a = getSomeValue(); f(a);//here inste...
It all depends on context. In this very specific situation that you site in your question. I prefer the explicit test rather than than the implicit conversion of 0 to false (But that is also because the names of the variables and the function are so meaningless if they were named differently then I may not mind). But t...
5,006,704
5,006,904
Find none duplicated letter in a char array. My program works wrong. Need help
Find none duplicated letter in a char array. My program works wrong. Need help #include <iostream> #include <vector> #include <list> # include <ext/hash_map> /* find none duplicated letter from char array */ using namespace __gnu_cxx; using namespace std; list<char> find_Noneduplicate_idx(const vector<char>& A) { ha...
First of all, change this int myints[] = {'H','A','C','B','C','H','Z'}; to char myints[] = {'H','A','C','B','C','H','Z'}; Otherwise when creating the vector on the following line, you're reading past the end of this array. Try std::cout << fifth.size() to see just how big your vector became! Or, alternatively, change...
5,006,752
5,006,955
Should I use relative include paths for my project, or place the include-directory on the include path?
In my project, I currently use relative paths to include my files, which admittedly doesn't change often. However, it yields pretty weird include patterns, because I usually nest my files in alot of folders. For example, in my current project I have network/server/myfile.hpp. It needs to include common/log.hpp. Current...
Relative includes paths with .. in it look a bit ugly and expect a certain filesystem structure, that is, "../../common/log.hpp" is two folders up. It makes sense to avoid unnecessary dependencies in general and on filesystem structure in particular, so that moving a header file from one directory to another does not f...
5,006,788
5,006,848
What is the most "standard" worthy database library for c++?
In my personal c++ studies, I've focused on projects that 1) Keep me engaged and 2) Help teach a standard principle. I want to do a project with database access. Which libraries do you think best stick with the c++ programming paradigm? I understand that this question is open to interpretation, so please elaborate on...
You might consider using the Database Template Library. It provides a clean, iterator-based interface to access collections of records, so you can use it with all of the Standard Library algorithms. It also does a pretty good job of limiting the boilerplate you need to write to map database entities to user-defined ...
5,006,797
5,007,825
create matrix using character arrays in c++
I have 8 different arrays, and each array has 8 characters in it, std::string str_v1 = v1.to_string(); char arr_v1[9] = {0}; std::copy(str_v1.begin(), str_v1.end(), arr_v1); // from str_v1 to str_v8 std::string str_v8 = v8.to_string(); char arr_v8[9] = {0}; std::copy(s...
for( int y=0;y<8;y++) { for( int z=0;z<8;z++) { switch(y) { case 0: matrix[z][y] = arr_v1[z]; //Be pretty sure, possibly you are better than you believe break; // I've placed y before z as y is the outer ...
5,007,169
5,166,628
Read with boost::program_options and push_back onto std::vector?
I have a configuration file which contains a list of endpoint entries. Each entry is labeled with a heading of [endpt/n] (for the nth endpoint), and consists of a MAC and IP address. I'd like to use boost::program_options to read the addresses as strings, and push_back the results onto two vectors. I've looked throu...
It is straightforward to do exactly as you want. First, use po::value< vector< std::string > > instead of po::value< std::string > as program-options provides special support of vectors. Then, reference your two vectors directly as typedef std::vector< std::string > vec_string; cfig_file_options.add_options() ((he...
5,007,247
5,007,782
Finding or building an inter-process broadcast communication channel
So we have this somewhat unusual need in our product. We have numerous processes running on the local host and need to construct a means of communication between them. The difficulty is that ... There is no 'server' or master process Messages will be broadcast to all listening nodes Nodes are all Windows processes, ...
I don't know of anything that already exists, but you should be able to build something with a combination of: Memory mapped files Events Mutex Semaphore This can be built in such a way that no "master" process is required, since all of those can be created as named objects that are then managed by the OS and not des...
5,007,268
5,007,290
How to call Linux command from C++ program?
I have written the following simple C++ program in order to learn how to call Linux command(s) from C++ program (by using the system command) Please advise why I have the errors from the C++ compiler? What is wrong with my program? more exm2.cc #include <stdio.h> #include <stdlib.h> int main() { system("echo -n '1. C...
You can't use system() without a char* parameter. So these statements are wrong: system(); system(); If you are not going to make anything, just don't put anything in there.
5,007,369
5,007,451
Program crashes when trying to set a character of a char array
I got this weird behavior of my programm, that i cant figure out. My professor showed me a flaw in my programm, where i just copy a char pointer when i construct an object instead of making a new copy of the whole array, so you can fool around with it. He demonstrated this with similar code like this. For the code: ch...
char* sweat ="Sweater"; sweat[0] = '\0' Here sweat points to a CONSTANT data. "Sweater" is const literal data, residing somewhere in read-only memory, and sweat points to this data as such. It doesn't make a copy of it. So when you do sweat[0]='\0', it tries to change first character of the CONSTANT data. Hence the er...
5,007,483
5,007,531
Pointer comparision issue
I'm having a problem with a pointer and can't get around it.. In a HashTable implementation, I have a list of ordered nodes in each bucket.The problem I have It's in the insert function, in the comparision to see if the next node is greater than the current node(in order to inserted in that position if it is) and keep ...
aux->next->hash_value There's no check whether "next" is NULL.
5,007,671
5,007,716
Return value optimization of values unpacked from std::tuple
Are there any compilers capable of performing return value optimization on multiple values returned from a function through std::tuple? To be clear, in the following code, are there any compilers capable of avoiding unnecessary copies? std::vector<int> a; std::list<float> b; std::tie(a,b) = myFunctionThatReturnsAVector...
It's not worth worrying anymore. If the compiler cannot perform RVO, move semantics will kick in.
5,007,941
5,009,360
Next larger number in an array
You are given an unsorted array A of n elements, now construct an array B for which B[i] = A[j] where j is the least number such that A[j] > A[i] and j>i if such a j does not exist B[i] = -1 Eg: A={1,3,5,7,6,4,8} B = {3 5 7 8 8 8 -1} My solution #include<iostream> using namespace std; int main() { int a[7]={9,3,5...
Make an empty array called c[]. Start at the end of a[] and work backwards. Do a binary search in c[] for the first value greater than a[i]. Put that into b[i], or a -1 if you can't find one. Drop everything in c[] that is less than b[i]. Append a[i] to the beginning of c[]. c[] will always be sorted, allowing binary ...
5,007,968
5,008,023
C++ - Using the new operator with a template provided typename
I have a class template which can be passed a Class or Class pointer. /* Template specialization hack to determine if type is a pointer */ struct type_true { }; struct type_false { }; template <class PRT> class is_pointer : public type_false { }; template <class PRT> class is_pointer <PRT * > : public type_true { }...
Is there some way i can strip the * from the T type or another solution? Of course, you can. Use this: (it removes just one degree of pointerness, i.e it makes T* -> T, and T** -> T*, etc) template<typename T> struct remove_pointer { typedef T type; }; template<typename T> struct remove_pointer<T*> { typedef...
5,008,266
5,008,341
Callback function in freeglut from object
I'm using MSVC++ and freeglut in order to use openGL. Now, I have a class called Camera, which is pretty simple, but it also holds the function for the reshaping of my window. My question is: how can I set glutReshapeFunc(void (*callback)(int,int)) to my function in my camera? I have the following code, which won't wor...
There's no clean way to do this. C does not know about objects, so pointers-to-members don't work. C does not do templates, so functors don't work. The API does not even allow you to pass an arbitrary void *userData to your callback, so you can't pass the object around in that way either. So, indeed, you'll have to cre...
5,008,391
5,008,418
How can I create a container iterator with the container holding a policy type?
I have the following code: #include <map> #include <string> class policy1 { public: struct data { }; }; template<typename policy> class policy_user : public policy { typedef std::map<std::string, typename policy::data> mymap; // good typedef std::map<std::string, typename policy:...
You forgot typename in typedefs. Write: typedef typename std::map<std::string, typename policy::data >::iterator myiterator; typedef typename mymap::iterator myseconditerator; Now. It's fine. typename is required because iterator is a dependent name. See also this
5,008,541
5,008,581
How to call a non-const function within a const function (C++)
I have a legacy function that looks like this: int Random() const { return var_ ? 4 : 0; } and I need to call a function within that legacy code so that it now looks like this: int Random() const { return var_ ? newCall(4) : 0; } The problem is that I'm getting this error: In member function 'virtual int Random(...
you should alter your program to use/declare const correctly... one alternative is to use const_cast.
5,008,804
5,009,006
Generating a random integer from a range
I need a function which would generate a random integer in a given range (including boundary values). I don't have unreasonable quality/randomness requirements; I have four requirements: I need it to be fast. My project needs to generate millions (or sometimes even tens of millions) of random numbers and my current ge...
A fast, somewhat better than yours, but still not properly uniform distributed solution is output = min + (rand() % static_cast<int>(max - min + 1)) Except when the size of the range is a power of 2, this method produces biased non-uniform distributed numbers regardless the quality of rand(). For a comprehensive test ...
5,009,071
5,009,104
c++ templated function error while trying to throw exception
I have some code where i am trying to throw a custom exception in a Templated method. When i try to compile it i get the following warning: there are no arguments to ‘Invalid_State_Exception’ that depend on a template parameter, so a declaration of ‘Invalid_State_Exception’ must be available note: (if you use ‘-fper...
Move the declaration of Invalid_State_Exception above Foo.
5,009,467
5,009,529
Running/compiling executable Linux vs Solaris
if i have code compiled under Solaris 8 and 10 and now have a vendor that wants to use my bin/exe under Linux. Could there be compatibility issues? I am pretty sure i would need to compile/link under Linux OS for it to work 100% but i just wanted to know if someone can give me the breakdown as to why it would not work...
You have to recompile your application on Linux. Linux is a completely different run-time compared to Solaris. Even if you have compiled your application statically, there's the interface/system calls to the kernel that is different among these two operating systems. The processor architecture might be different too, e...
5,009,513
5,031,836
Accessing submatrices using LAPACK
Is there a function in LAPACK, which will give me the elements of a particular submatrix? If so how what is the syntax in C++? Or do I need to code it up?
There is no function for accessing a submatrix. However, because of the way matrix data is stored in LAPACK routines, you don't need one. This saves a lot of copying, and the data layout was (partially) chosen for this reason: Recall that a dense (i.e., not banded, triangular, hermitian, etc) matrix in LAPACK is defi...
5,009,524
5,009,690
dependent classes as other class members
I have a class B that requires an instance of class A to be constructed: class B { B(A* a); // there is no default constructor }; Now I want to create a class that contains B as a member, so I also need to add A as a member and provide it to B's constructor: class C { C() : a(), b(&a) {} A a; // 1. initial...
Is there a good way to resolve this without modifying the classes A and B? Turn on compiler warnings; for gcc, this is -Wreorder (which is included in -Wall): cc1plus: warnings being treated as errors t.cpp: In constructor 'A::A()': Line 3: warning: 'A::y' will be initialized after Line 3: warning: 'int A::x' Line...
5,009,639
5,009,931
Accessible, cross platform, relevant UI framework?
I'm an experienced PHP/JS developer with a tiny bit of background (read university projects) in Java/C/C++. I'm looking to branch out my skill set and would like some advice on what language would be the best to pick up, along with a UI framework for that language. I have a tiny bit of experience with Qt's C++ implem...
Well 3 are recommended: Swing (Java) SWT/JFace (Java) Qt (C++) Working with these UI toolkits is almost the same: (generally same approach, good UI designers, good communities ... etc) so the language choice should rely on what external libraries are you using and whether or not you want native look and feel for your...
5,009,737
5,009,821
This code is undefined, why is it running? How do i crash it?
I ran the code below in visual studios and expected to get a runtime or some kind of error. I got nothing, absolutely nothing. I got the output code 9, comment that line out and got 3. I ran it on codepad and it gave me no errors as well. Is there a compiler that will tell me this code is incorrect? If it is correct wh...
Undefined behavior is undefined behavior. You can't expect it to do anything in particular, including crash. There is no compiler I know of that will catch all types of UB and I don't think it's possible. You could crank up the warning level of your compiler but I don't think it would even warn you then. Your use of...
5,009,869
5,009,966
How to implement garbage collection in C++
I saw some post about implement GC in C and some people said it's impossible to do it because C is weakly typed. I want to know how to implement GC in C++. I want some general idea about how to do it. Thank you very much! This is a Bloomberg interview question my friend told me. He did badly at that time. We want to kn...
Garbage collection in C and C++ are both difficult topics for a few reasons: Pointers can be typecast to integers and vice-versa. This means that I could have a block of memory that is reachable only by taking an integer, typecasting it to a pointer, then dereferencing it. A garbage collector has to be careful not t...
5,009,974
7,567,832
opencv fails to open avi with ffdshow codec
I am currently using OpenCV to try and open an AVI file that was made using ffdshow. The program manages to open the video file and play however, the video file is in black and white and is slightly skewed. VLC and windows media player can run it fine. Is there anything that I am able to do to install the ffdshow codec...
OpenCV is managing video files in different manners depending your OpenCV compilation and configuration, like Video for Windows (Vfw), Win32, ffdshow...if your codec is installed only as a filter for DirectShow and OpenCV is trying to open this video with VfW32.dll the codec cannot be seen.
5,010,116
5,010,860
Building boost with MinGW gives "argument error"
I am trying to build boost with MinGW and have downloaded boost 1.45 and bjam Version 3.1.18. OS=NT After cd'ing into the root of boost, I try to compile it with bjam toolset=gcc --build-type=complete stage which doesn't work. This is the start of the error messages that are returned: C:\boost\boost_1_45_0>bjam toolse...
The following link might be helpful, it appears to be the same problem: http://comments.gmane.org/gmane.comp.lib.boost.user/64146 To summarise: you must use the bjam version included with boost 1.45. And: Still, isn't it wrong that the bjam build linked directly above the 1.45 download link can't build 1.45? According...
5,010,216
5,010,446
Constant combining in optimizing compilers
I have a header file containing a lot of small inline functions. Most of them happen to have constant data. Since these functions are performance critical, the way they handle constants becomes important. AFAIK there are two ways to refer to constants: 1) Define them in a separate source file that is later linked with ...
According to the GCC the following option does what you want: -fmerge-constants Attempt to merge identical constants (string constants and floating point constants) across compilation units. This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inh...
5,010,502
5,251,128
From out-of-process, what is the proper way to get an IWebBrowser2 interface from an instance of IE?
I am working on a browser automation framework, which automates Internet Explorer, as well as other browsers. I am running into an intermittent problem when attempting to launch IE. The framework launches IE using the IELaunchURL API if it is present, and uses CreateProcess if not. The code to obtain the IWebBrowser2 i...
The problem was in the use of threading in the application. We were not properly waiting for a thread to terminate before launching a new instance of IE.
5,010,541
5,010,651
C++: Pass array created in the function call line
How can I achieve a result like somebody would expect it according to the following code example: // assuming: void myFunction( int* arr ); myFunction( [ 123, 456, 789 ] ); // as syntactical sugar for... int values[] = { 123, 456, 789 }; myFunction( values ); The syntax I thought would work spit out a compile error...
You can't achieve that syntactic sugar with C++ code, not in C++03. The only place where braces are allowed, referring to elements of an array, is in initializing a named array: int arr[] = { 0, 1, 2 }; Nowhere else. You can however achieve a similar effect with Boost.Assign: void f(const std::vector<int>& v) { } // ...
5,010,612
5,012,110
Increase precision in DirectX with high range positions?
I am creating an little game in c++ with directx 9 with a randomly created world and have an issue when the player goes far from the 3d origins (0,0,0) 3d rendering become very imprecise causing visual issues. I think it's because the values sent to the shader are floats and floats become less precise when increasing. ...
The problem is probably that you are hitting the precision limits of single-precision floating point numbers. There are many ways to avoid these problems, depending on your setup and what particular issues you are experiencing; you can probably find one that will not require a serious performance hit. From your questi...
5,010,620
5,010,757
Where is IFileOperation implemented (and how can I verify this)?
I am trying to find out where IFileOperation is implemented in Windows 7. As far as I understand from the MSDN page it is in shell32.dll. So, I checked all the COM objects in shell32.dll using a DLL export viewer (from NirSoft) and IFileOperation is not one of them. I searched the registry for the CLSID_FileOperation {...
A DLL doesn't need to export anything special to implement that interface. The registry tells the OS what DLL implements the interface. When a program calls CoCreateInstance, the OS can look up the given CLSID in the registry. The OS then loads the associated DLL and calls its DllGetClassObject function to get an IClas...
5,010,807
5,010,923
How can I use std::generate/generate_n with a polymorphic function object?
I'm new to std::generate and have attempted to structure a program which uses it to initialize vectors. However it's behaving differently to my expectations. I have an abstract base class: template <typename G> class RandomAllele { public: RandomAllele() { /* empty */ } virtual ~RandomAllele() { /* empty */ } v...
As others have mentioned above, the generate and generate_n functions take their generator objects by value, precluding you from directly using inheritance in this context. However, one trick you can do is to apply the Fundamental Theorem of Software Engineering: Any problem can be solved by adding another layer of in...
5,010,968
5,011,304
Problem with reading multiple texture units from a Shader in OpenGL
I am trying to read two different textures in my shader, one for regular texturing, and one bumpmap. However both Sampler2D's are reading from the same texture unit. I am setting the uniforms to 0 and 1 however, and I have bound the textures to their respective units as follows: glActiveTexture(GL_TEXTURE0); glEnable(G...
shaderMgr->activeProgram()->setUniform1f("tex", 0); If this is calling glUniform1f, that's wrong, you must use glUniform1i to set texture samplers.
5,010,978
5,011,314
Reducing wiimote pitch/roll variations
I want to use the wiimote to control a cursor WITHOUT the infrared sensor bar. I'm using the pitch and roll values for this. The problem is that when the pitch is close to 0 degrees, the roll is very unstable, and when the pitch is close to 90 degrees, it is itself very unstable, but the roll is fine. Im polling the w...
This is a common problem with pitch and roll. You can reduce this annoying effect but you cannot get rid of it as long as you are using pitch and roll (Euler angles). Look at 38:25 http://www.youtube.com/watch?v=C7JQ7Rpwn2k I use rotation matrices instead of Euler angles in my motion sensing application. For an introdu...
5,011,071
5,011,086
Passing a void* by reference
Why can't I pass a void* by reference? The compiler allows me to declare a function with the following signature: static inline void FreeAndNull(void*& item) But when I try to call it, I get the following error: Error 1 error C2664: 'FreeAndNull' : cannot convert parameter 1 from 'uint8_t *' to 'void *&' Casting ...
If you take a void * by reference, you have to pass an actual void *, not an uint8_t *. Try this instead: template<typename T> inline void FreeAndNull(T * & V) { free(V); V = 0; } EDIT: Modified sample to better reflect the OP's function name, and to address @6502's entirely correct comment.
5,011,262
5,011,445
Is there code folding support for C++ in Monodevelop?
Is there any code folding support for C++ under Monodevelop (in Mac OS X)? It works with C# but I don't see it with C++.
There is code folding support for C++ in Monodevelop, but it uses the ctags parser. If you install ctags, Monodevelop should enable the feature automatically. [Reference]
5,011,285
5,011,430
Is there any opensource cross platform C++ library for creating menus for command line projects?
So what I need on developer side is something like addoption("-use-something", "Use Something instead of Some other thing", localVarName, desiredValue, defauultValue); While on user side I wish to see 3 things first is to set params in if they were passed as application options/arguments (like from start my.exe -use-...
You should use the Boost.Program_options. Example from the tutorial: // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("compression", po::value<int>(), "set compression level") ; po::variables_map vm; po::store(po::parse_comm...
5,011,531
5,011,586
How to get non-dynamic symbols in GCC backtrace?
GCC's backtrace_symbols() only resolves dynamic symbols, since handling all types of symbols is something GCC maintainers do not want to get into. How would I go about extracting non-dynamic symbols obtained from GCC's backtrace() function myself?
Check out what addr2line does using bfd. That is one approach I have used successfully. More specifically, backtracefilt gets you basically all the way there, you just need to adapt it to take the addresses from backtrace instead of parsing a file.
5,011,546
5,025,139
C++ : Using an array in a nested class definition (OOP)
So I am trying to define a class and I am using another array of a different class to define it. //header file for Name.h class Name { string last; string first; }; //header file for Depositor.h class Depositor { Name name; string ssn;}; //header file for Account.h class Accoun...
By declaring the value of the array in the header file and by adding a variable in the .cpp file you can solve all the problems and leave it as an array. //header file class Bank { Account account[100]; int active_accts; public: //mutator void setLastname (string,int); }; //the implementation file void Bank::setL...
5,011,557
5,012,047
How does one bind namespace prefixes when using QXmlQuery (Qt XQuery)?
I'm attempting to use QXmlQuery to execute an XQuery expression against a document with a declared default namespace. For discussion: <?xml version="1.0" encoding="UTF-8"?> <root xmlns="http://namespace.com/ns1"> <node1 attr1="hi"/> </root> Now, I have the following to open and query against the document: QFile te...
I believe if you would change your query to ... QXmlResultItems items; query.setQuery("declare default element namespace \"http://namespace.com/ns1\"; /root"); ... it should return the data. hope this helps, regards
5,011,818
5,011,831
Static Objects in C++ with Visual Studio
I'm working on a project where there's a static object declared in one of the header files (say A.h). I include A.h in another header file, and I can access the object and it's functions and data as if it were the same object. The problem starts when I include A.h into B.cpp and try and use the same object. The object ...
Initialize the static variable in your implementation file for A.h - e.g. A.cpp. Also mark the variable as extern.
5,011,819
5,011,911
Debugging a user's crash from assembly
I've got a software application which some users report reliably crashes in certain situations. I can't reproduce it on any of the machines I've got so I'm feeling pretty stuck as to how to solve it. A user posted me the assembly line where the crash happens, like this: 00505e58 1000 adc [eax],al 00505e5a cc int 3 005...
If you could get a full crash dump of your app when it crashes, then you could bring up the dmp in either windbg or Visual Studio and debug with source code rather easily. There's plenty of info on the web for getting a dump and debugging. For example, if you have a dump and matching pdb and bring thsi up in windbg, y...
5,012,022
5,013,077
Fastest way to traverse arbitary depth tree for deletion?
For my own exercises I'm writing an XML-parser. To fill the tree I use a normal std::stack and push the current node on top after making it a child of the last top-node (should be depth-first?). So I now do the same for deletion of the nodes, and I want to know if there's a faster way. Current code for deletion: struct...
Don't go out of your way to do iteratively what can be easily done recursively, unless you can prove that the recursive version is either insufficient (e.g. stack overflows) or slower (which won't happen unless you start overflowing your stack, forcing the OS to either expand it or crash you). In other words, in genera...
5,012,084
5,037,946
Implicit casting in templates and compiler coercion
I have this very simple wrapper template: template<class T> struct wrapper { inline operator T () { return v; } inline wrapper(T v):v(v) { } T v; }; Trying to use it with any non-primitive type with (for example) comparison operator relying on the template having it defined doesn't look promi...
Apparently this is a GCC 4.5 bug. The code is valid, unlike what Fred Nurk says. http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45383
5,012,122
5,012,339
SOCKS 5 and UDP (C/C++)
I know that SOCKS 5 supports UDP and I have been over the structure of the packets that are sent/received in negotiating with a SOCKS proxy. The one thing I am not clear on is the procedure for setting up to register with a proxy to send/receive UDP packets. Specifically, my biggest question is, "Is the connection to t...
https://www.rfc-editor.org/rfc/rfc1928 "A UDP-based client MUST send its datagrams to the UDP relay server at the UDP port indicated by BND.PORT in the reply to the UDP ASSOCIATE request" but "UDP association terminates when the TCP connection that the UDP ASSOCIATE request arrived on terminates." I actually tried usin...
5,012,242
5,012,311
Convert a C++ time_t to Delphi TDateTime
In a Delphi XE application, I am reading values from a database originally created by a C++ program. There is a date column, stored (it would appear) as time_t, i.e. Unix time, the number of seconds since 00:00, Jan 1, 1970 UTC. I can deal with the time zone, but how can I get TDateTime from (long) time_t?
Try using the unixtodatetime function which is part of the Dateutils unit : http://docwiki.embarcadero.com/VCL/en/DateUtils.UnixToDateTime
5,012,480
5,012,494
8-bit char to Hex representation
I'm trying to convert 8 bit char into hex view which looks like this: 00 03 80 45 E5 93 00 18 02 72 3B 90 88 64 11 00 45 FF 00 36 00 FF 45 00 00 34 7B FE 40 00 40 02 But some characters contain negative values which makes a larger hex value of more than 2 digits. how would i get each one as represented above?
I don't know what you are using for formatting, but make sure that you make your byte holding variable an unsigned char (assuming that char is 8-bits on your platform, which it is on all sane platforms), before formatting. If your platform has a sane BYTE typedef, use that. You can also use the boost::uint8_t type to s...
5,012,524
5,012,661
Mixing unmanaged C++ with F# for doing physics: worth it?
I'm going to start writing a 3D game in unmanaged C++ using the DirectX SDK. It's going to involve a lot of physics and math, though I can't predictably say how complex it's going to be (I don't know if I'll be parallelizing it, for example). I was thinking, due to F#'s incredibly awesome units of measure feature, and ...
Jumping from managed to unmanaged code, or from unmanaged to managed code for individual operations is costly and not worth it for single instance costly operations. That is, the managed to unmanaged, or unmanaged to managed cost in calling a matrix multiplication will be higher than the cost of the multiplication in t...
5,012,609
5,012,624
Adding library code to your project, or use precompiled binaries?
I need some advice on my project. I am going to use various C++ libraries to accomplish different tasks. I am using Visual Studio 2008. To me, it seems to get a little out of hand when I add the actual source code of the library to my project's path. It seems easier to just use the include files of the library, and ju...
If a library is available use it. With C++ and windows you may have to rebuild the library if it was built with a different compiler, there are issues linking C++ libs between gcc/mingw and visual studio. but in general there is no reason to add the source to your code base.
5,012,633
5,012,823
Can Netbeans(MinGW compiler for c/c++) call on arbitrary C/C++ DLLs(compiled in VS'05)?
AS above, i encountered a "undefined reference error imp_ZN12classNameC1Ev" when using JNI to call upon class functions in arbitrary provided DLL. I am wondering if name mangling incompatibilty for the 2 different compilers is the source of error? To be exact, can a code compiled by MinGW(gcc/g++) call another code's c...
Compiling is not exactly the problem. The problem is at linking. If you have C++ interfaces then name mangling will definitively make you trouble. Each compiler has its own name mangling scheme. Too bad, they should have standardized maybe this too in the C++ standard... One way to workaround the problem is to create a...
5,012,700
5,012,923
How can I make the camera fly through objects in OpenGL using Glut?
First off, all of my code can be found here, it's in 3 files. flythrough.cpp, support.cpp, support.h Okay... so if you run that, it seems to work, but a few things are really bugging me! The camera is starting off in a strange location, I try to change all kinds of variables, but it doesn't seem to have an effect. The...
Its an orthographic camera, therefore you cannot move along the Z axis. You need to change your camera type to do what your trying to do. Ref: Line 33, flythrough.cpp glOrtho(-2.0 * 64 / 48.0, 2.0 * 64 / 48.0, -2.0, 2.0, 100, 100.0); Typically, just uncomment this line, then write the following: gluPerspective(60.0, 6...
5,012,739
5,012,992
Get text from Textbox in GTK+
I'm trying to get the input text from a text box in a callback function when the user changes something it it (on "changed"). The code goes as follow: #include <stdio.h> #include <gtk/gtk.h> void enter_callback( GtkWidget *widget, GtkEditable *buffer) { printf("%s",gtk_editable_get_chars(buffer, 0, -1)); } int main(i...
According to the GTK documentation, GtkText is deprecated, buggy, and should not be used. You should instead be using the GtkTextView widget via gtk_text_view_new.
5,012,803
5,013,284
Test if char* string contains multibyte characters
I receive a byte stream buffer from a TCP server which could contain multibyte characters forming unicode characters. I was wondering if there's always a way to check for BOM to detect those characters or else how would you like to do it?
If you know that the data is UTF-8, then you just have to check the high bit: 0xxxxxxx = single-byte ASCII character 1xxxxxxx = part of multi-byte character Or, if you need to distinguish lead/trail bytes: 10xxxxxx = 2nd, 3rd, or 4th byte of multi-byte character 110xxxxx = 1st byte of 2-byte character 1110xxxx = 1st...
5,013,007
5,013,420
representing matrix by linkedlist
The problem is: An alternative linked representation for sparse matrices uses nodes that have the fields down, right, roe, col, and value. Each nonzero entry of the sparse matrix is represented by a node. The zero terms are not explicitly stored. The nodes are linked together to form two circular lis...
For transpose, you could traverse one list, swapping all the links and row/col pointers. In pseudocode: set node to header do { swap node.row and node.col swap node.right and node.down node = node.right } while node != header; Here's addNode, one (inefficient) solution is to add individual nodes by traver...
5,013,254
5,013,504
What is a network tickle? And how to I go about sending one?
What is a network tickle? And how to I go about sending one?
http://android-developers.blogspot.com/2010/05/android-cloud-to-device-messaging.html
5,013,463
5,013,491
C++ Private Nested Abstract Class
So maybe this is a dumb question and I'm over thinking this, but I have the following situation. I am making a "class Shell" which can run abstract "class Action" objects. It is the only class that should create or use these objects. Action objects need access to the Shell to perform specific actions on it, but I'm ...
If the only code that needs to be able to see Action is Shell, one option would be to forward-declare Action in the header file but only define the class in the .cpp file. This would then let you declare as many Action subclasses as you'd like in the implementation file without letting anyone else subclass off of Acti...
5,013,717
14,759,603
Are inner classes in C++ automatically friends?
If I define an inner class in C++, is it automatically a friend of the class that contains it? For example, is this legal: class Outer { public: class Inner { public: void mutateOuter(Outer& o); }; private: int value; }; void Outer::Inner::mutateOuter(Outer& o) { o.value ++; // Legal? Or...
After having asked more or less the same question here myself, I wanted to share the (apparently) updated answer for C++11: Quoted from https://stackoverflow.com/a/14759027/1984137: standard $11.7.1 "A nested class is a member and as such has the same access rights as any other member. The members of an enclosing c...
5,013,827
5,061,891
C++-based make system
Are there any build systems that don't use a DSL but actually use C++ as the build language?
I've written a build system that I use in my projects in Python called pybake. It's designed to be a bit smarter than make, with less magic. The build is also defined in Python, thereby reusing an existing language, rather than generating a new DSL for that purpose. Here's an example of it in use.
5,014,056
5,014,180
Call by reference vs Pointer argument
Possible Duplicate: FAQ: How to pass objects to functions in C++? Pointer vs. Reference Hi all, in c/c++, we can pass a object as call by reference or passing pointer of the object. for example: i want to create a function which will take string vector as input and output a map that contains some value for each stri...
This is a matter of style. At Google (see Google C++ style guidelines), the following would be preferred: bool CalculateSomeValue( const vector<string>& input, map<string, double>* result); This is because using a pointer requires the explicit use of an ampersand at the call site: CalculateSomeValue(input, &resul...
5,014,061
5,015,089
What's the use of _ATL_PACKING constant when computing distance from the start of object?
ATL features a set of macros for so-called COM maps. COM map is a table that associates an interface GUID with an offset that is to be added to this pointer to get to the corresponding subobject - the whole stuff works as replacement to explicit static_cast for the upcast inside IUnknown::QueryInterface(). The map entr...
The non-zero constant is there because the macro does not work with null pointers. We know that the value of a null pointer is a null pointer constant which evaluates to 0: C++ Standard 4.10/1 Pointer conversions [conv.ptr]: A null pointer constant is an integral constant expression (5.19) rvalue of integer type t...
5,014,288
5,014,331
Beginning of class definition
Formally (quote from std would be ideal), from which point a definition of this class starts: template<typename T> class X { };
from which point a definition of this class starts From the point compiler starts parsing things related to the class. In your example, the letter "t" of the word template is the start, hence the point of definition! By the way, there're two related things. Read this: Point of definition vs Point of instantiation Th...
5,014,373
5,014,567
Undefine already included header
I want to check a header in my source file and if its already defined, I want to undefine it. Is it possible?
You can't do what you seem to want to do. If you don't want the header included your choices are don't include it in the first place conditionally include it or not via the prepocessor e.g. #ifdef INC_MY_HEADER #include "myheader.h" #endif or assuming the header has header guards just define the header guard before t...
5,014,616
5,014,774
Variable number of arguments to constructor with variable types creating variable private member in C++
I have really heavy task to achieve and I haven't found any solution good enough. So, here is the description: - task is to evaluate multiple single dimension arrays which number can vary - good news is that it is possible to specify types of arrays And desirable way of doing it: - creating a class with constructor tha...
constructor that accepts variable number of arrays: vector< vector<T> > ? the inner vectors can be of different sizes but must be of the same type. constructor member function with variable number of parameters You can use a function with variable number of parameters that creates a class, look at how boost::bind ...
5,014,712
5,014,846
Remote debugging C++ on the Windows Server 2008 platform with VS2010; MSVCP100D.dll missing
I've written a quick C++ console app using VS2010. I'd like to run it via the remote debugger on the Windows Server 2008 platform, in order to determine why I can't enumerate the CLSID_AudioInputDeviceCategory on that OS. The console app works on the XP and W7 platforms. The remote debugger gives the following error w...
Thanks to Errata, I had a look at Project Properties -> Configuration Properties -> C++ -> Code Generation I changed Runtime Library from Multi-threaded Debug DLL to Multi-threaded Debug (/MTd). This allows remote debugging without having to rely on the correct debug DLLs residing on the remote machine. I hope this he...
5,014,821
5,361,492
Packaging up libcURL for easy distribution
So I want to package up a really simple and easy-to-use Twitter API that just accesses some of the basic public API calls (such as the public timeline). To this end, I plan to wrap an API around libcURL to do this. A couple of caveats. First, I am designing this for students in a class I am TAing. They are just learn...
I would rather recommend that you install/require a libcurl installed from fink/macports that already do a good job at packaging libcurl. Then you can instead focus your work to get your layer on top of that done really nice.
5,015,133
5,016,867
Generating random floating-point values based on random bit stream
Given a random source (a generator of random bit stream), how do I generate a uniformly distributed random floating-point value in a given range? Assume that my random source looks something like: unsigned int GetRandomBits(char* pBuf, int nLen); And I want to implement double GetRandomVal(double fMin, double fMax); ...
I don't think I'll ever be convinced that you actually need this, but it was fun to write. #include <stdint.h> #include <cmath> #include <cstdio> FILE* devurandom; bool geometric(int x) { // returns true with probability min(2^-x, 1) if (x <= 0) return true; while (1) { uint8_t r; fread(&r, sizeof r, 1...
5,015,285
5,015,377
WNetUseConnection SystemErrorCode 1113 No Mapping Exist
I am trying to convert a string into a wchar_t string to use it in a WNetUseConnection function. Basicly its an unc name looking like this "\\remoteserver". I get a return code 1113, which is described as: No mapping for the Unicode character exists in the target multi-byte code page. My code looks like this: s...
MultiByteToWideChar will not 0-terminate the converted string with your current code, and therefore you get garbage characters following the converted "\uncDrive" Use this: std::string serverName = "\\uncDrive"; int CharsNeeded = MultiByteToWideChar(CP_ACP, 0, serverName.c_str(), serverName.size() + 1, 0, 0); wchar_t *...
5,015,444
5,015,523
How do I use a Win32 Class Library in a Win32 Application in Visual Studio 2010 Express?
As stated, I'm trying to use the class library in the application. Specifically, I've got a (very small) test Console class with one Write(std::string) function. I want to access the class library, access the Console class and successfully send a std::string to the Write function. I don't, specifically, need to know ho...
First of all you need to decide how you wish to link your 'library' code. Do you want it to be static or dynamic? Static linking means the library you wrote gets 'merged' with your exe. So your exe file will be: size-of-exe-code + size-of-lib (roughly, just remember that the exe size increases with the lib) With the ...