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,472,801 | 5,499,274 | Inline throw() method in C++ | I am trying to define a really simple exception class. Because it is so simple I want to keep it in the .h file only, but the compiler doesn't like throw(). The code:
#include <exception>
#include <string>
class PricingException : public virtual std::exception
{
private:
std::string msg;
public:
PricingExc... | Found it finally! @Mike Seymour was right in his comment - it turns out that in a file nr3.h (part of Numerical Recepies code) there is a macro throw(message) defined.
What I don't understand is why it impacts compilation of files that don't include this .h file...
Anyway, I think Visual Studio had a different compila... |
5,472,816 | 5,476,387 | Need a way to display image and draw on the image in Visual C++ | The current way that I found was to make a bitmap and paint it into a picturebox,
but there it is very slow when trying to scroll the panel (the picturebox is inside a scrollable panel).
Is there a better way to achieve this functionality?
| Load the bitmap only when your picture box is created, then leave it in memory until the picture box is destroyed. Loading the bitmap every time OnPaint is called will destroy performance.
Also make sure you aren't re-painting your bitmap if you receive a WM_PAINT message and nothing has changed.
|
5,472,919 | 5,473,028 | Overloaded function template never called | I love templates, at least I would if I would understand them ;-). I implemented an overloaded operator using templates. I am now trying to specialise the function calls.
Here is what I do:
class Terminallog {
public:
Terminallog();
Terminallog(int);
virtual ~Terminallog();
template <class T>
Ter... | The type of test3 in your code is std::vector<int> *, but there is no Terminallog::operator<< that takes an argument of that type. There is one that takes const std::vector<int> * and it would be called if you did
clog << const_cast<const vector<int>*>(test3);
Incidentally, new'ing a vector is almost never a good idea... |
5,473,262 | 5,473,286 | Deallocate wchar_t* of a vector | I have a vector of wchar_t* like this:
std::vector<wchar_t*> myvector;
and a function that take a string and insert it into the vector
void myfunction(wchar_t* mystring)
{
myvector.push_back(mystring);
}
myfunction(L"this is my string");
when I close the program I need to delete the allocated memory of the vecto... | With this myfunction(L"this is my string"); you don't create a new string. It's a constant string that's stored somewhere in your exe. And since you don't explicitly new it, you don't need to delete it either.
Only use new and delete and new[] and delete[] in pairs!
|
5,473,378 | 5,473,433 | Parsing a C++ string in C++ | I have a requirement like this: I have a string like "-myArg:ArgVal".
std::string strArg = "-myArg:ArgVal";
Now, I have to check in above string first character is always '-' and if first character is '-' i should remove it and i should store "myArg" and "ArgVal" in two different string objects.
How can I do this effi... | Try this
if (strArg[0] == '-') {
strVar1 = strArg.substr(1, strArg.find(':') - 1);
strVar2 = strArg.substr(strArg.find(':') + 1);
}
Of course I'm assuming that if the string starts with '-' then there will be a ':' in it with chars before and after. You should probably check this because if there isn't it can ... |
5,473,495 | 5,473,527 | Are these pointer constructions equivalent? | Are these constructions equivalent?
int *(*p[10])() //array of ten pointers onto int functions
and
int *(*p())[10]
| No.
Here's what the ever-wonderful cdecl says:
int *(*p[10])(): declare p as array 10 of pointer to function returning pointer to int
int *(*p())[10]: declare p as function returning pointer to array 10 of pointer to int.
Intuitively, they "shouldn't" be the same since the declaration syntax of C++ is rarely that amb... |
5,473,556 | 5,475,756 | What is the NDEBUG preprocessor macro used for (on different platforms)? | I'm interested in what purpose various platforms / compilers ("implementations") / frameworks assign to the the C and C++ preprocessor macro NDEBUG.
The C as well as the C++ standard only mention this definition once, namely to control the behavior of the assert() macro.
I would ask to include only specific answers, wh... | That is a decision up to the maintainer(s) of the framework in question. Since such decisions are subject to change, it's nothing you should rely on. I use NDEBUG as a toggle for everything debug-related (e.g. trace outputs), but I might change my mind in the next release. No answer anyone could give here is a replacem... |
5,473,727 | 5,473,937 | c++ socket udp and tcp on unix and windows | can you recommend me a good c++ library(or implementation) for udp socket (multicast) and tcp
working on unix / windows system?
tnx
| Boost.Asio
Description
Portable networking and other low-level I/O, including sockets, timers, hostname resolution, socket iostreams, serial ports, file descriptors and Windows HANDLEs.
|
5,474,049 | 5,474,077 | Does Visual Studio frees memory if I interrupt debugging? | Does Visual Studio (I'm using the 2010 edition) frees the memory when I interrupt debugging and some of the free(memory_pointer) instructions are not yet called?
I think it does but I prefer having a confirmation first
| When you interrupt debugging, it won't free any memory because you might want to continue later ...
If you abort debugging, Visual Studio detaches the debugger and aborts the process. In this case, the OS will take care of releasing all resources (i.e. memory, file handles) allocated to the process.
|
5,474,083 | 5,474,152 | Starting C++ in VS - Build succeded but no output | Coming from web development I have been trying to get familiar with compiled programming, specifically C++. I usually run into issues like this and end up getting frustrated and putting it off for another month. Hopefully this is something simple.
I used a basic Hello World script:
#include <iostream>
using namespace s... | Place cin.get(); before the return 0 statement. That should let you see the output.
Or navigate to the directory of the executable from Command Prompt and run the Exe.
Or click on the green button where it says Debug, that should do the job as well.
'Hello World.exe': Loaded 'C:\Windows\System32\ntdll.dll', Cannot find... |
5,474,314 | 5,474,744 | make: implicit rule to link c++ project | I am working my way through a make tutorial. Very simple test projects I am trying to build has only 3 files: ./src/main.cpp ./src/implementation.cpp and ./include/header.hpp This is the make file.
VPATH = src include
CPPFLAGS = -I include
main: main.o implementation.o
main.o: header.hpp
implementation.o: header.hpp
... | According to the make manual, you can use the implicit linking rule with multiple objects if one of these matches the executable name, eg:
VPATH = src include
CPPFLAGS = -I include
main: implementation.o
main.o: header.hpp
implementation.o: header.hpp
This will build an executable named main from both main.o and impl... |
5,474,349 | 5,474,523 | Initialization of Objects with Static Storage Duration in C vs C++ |
Possible Duplicate:
What does main return?
For example, the following code compiles without any warning:
#include <stdio.h>
int i = i + 1;
int main(int argc, char *argv[])
{
fprintf (stderr, "%d\n", i);
return 0;
}
I think this is illegal in syntax, because i is used before it's declared, is it right?
A... | (notice: I'm referring to the current C++ standard)
I'm not really sure about this, but, if my interpretation of the standard is correct, the code should be fine and not UB.
The first initialization of that variable is the zero-initialization of objects with static storage duration that happens before any other
initial... |
5,474,457 | 5,489,962 | Bluetooth connection using socket rfcomm | I have two Bluetooth devices and I'm trying to make two rfcomm connections, one connection per device.
I'm using bluez rfcomm socket
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( dest, &addr.rc_bdaddr );
// connect to server
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// set disconn... | you cannot do this, the bluez bluetooth stack will work on only one dongle i.e local bluetooth device at any time.
To be able to have a singe instance of the bluetooth stack control 2 bluetooth local dongles will be a big change to the bluez stack.
|
5,474,473 | 5,474,568 | Multiple threads queuing for global lock should all return true once first lock acquired | A similar problem is this one: Are threads waiting on a lock FIFO? However, in this problem, once the lock is acquired only one thread executes the protected code, and in the end all threads will have executed the code.
What I would like to do is to execute the protected code once, but for all threads queuing for the m... | You seem to be looking for try_lock().
Given some Boost.Thread Lockable, a call to Lockable::try_lock() will return true if it can acquire the lock at that moment, otherwise false if it cannot acquire the lock.
When your thread reaches a checkpoint, have it try to acquire this lock. If it fails, another thread is alrea... |
5,474,475 | 5,488,329 | Can't link against Boost.Thread 1.46.1 with MinGW 4.5.2 | I've built boost using:
bjam --toolset=gcc --with-thread stage
Whenever I'm trying to actually use Boost.Thread I'm getting undefined references although I link against it. It doesn't happen with other Boost libraries like Regex or System.
>g++ main.cpp -I. -L. -lboost_thread-mgw45-mt-1_46_1
C:\Users\jhasse\AppData\Lo... | Try adding the compiler option '-DBOOST_THREAD_USE_LIB'
|
5,474,699 | 5,474,730 | Binary search problem with my code....please look into my following problem? | #include<iostream>
#include<string>
using namespace std;
int main()
{
int list[25],vote[25];
bool found;
int count,first,mid,last;
char condition;
double high = 0,total=0;
string searchitem,name[25],winner;
cout <<"How many names?" <<endl;
cin>>count;
cout <<" Enter the "<<count<< " candidates last name and the numbe... | while ((first<=count)&&!found)
should be
while ((first<=last)&&!found)
|
5,474,801 | 5,485,612 | How to access SQL DB in C++? | I am looking for a free cross-platform (Windows, Linux) C++ library for an access to an MS SQL server DB.
For example, I want to convert the following C# flow to unmanaged C or C++ (from here) :
static void Main()
{
string connectionString =
ConsoleApplication746.Properties.Settings.Default.ConnectionString... | Accessing MS SQL server from windows should not be a problem in general. For accessing it from Linux, this web page may help you to find a way
http://www.sommarskog.se/mssqlperl/unix.html
Finding a solution that works on both Windows and Linux is a task that may not be solved easily, depends on the exact requirements ... |
5,474,816 | 5,474,914 | Can I change the name of a dll to load at runtime? | Say I have a dll named middle.dll that is importing functions from runme.dll
I now have a replacement runmeDBG.dll that has all the same functions exported as runme.dll
Is there a way to use middle.dll but have it link to the functions exported from runmeDBG.dll instead of runme.dll?
I can change the code for middle.dl... | I'm assuming middle.dll is not yours, and it links statically to runme.dll. No, there's no way to change dll name in case of static linkage; you can, however, rename the runmeDBG.dll to runme.dll and place it somewhere where dll loader will find it. Or use a manifest to point the executable straight to the specific pat... |
5,475,039 | 5,475,208 | Embedding compressed files into a c++ program | I want to create a cross-platform installer, in c++. It can be any compression type, eg zip or gzip, embedded inside the program itself like an average installer. I don't want to create many changes on different platforms, linux and windows. How do I embed and extract files to a c++ program, cross-platform?
| C++ is a poor choice for a cross-platform installer, because there's no such thing as cross-platform machine code.
C++ code can be extremely portable, but it needs to be compiled for each platform, and then you get a distinct output executable for each platform.
If you want to build installers for many platforms from a... |
5,475,040 | 5,481,404 | c++ initializer lists and variadic templates | I wanted to create an array:
template < typename T, typename ... A > struct a {
T x [1 + sizeof... (A)];
a () = default;
a (T && t, A && ... y) : x { t, y... } {}
};
int main () {
a < int, int > p { 1, 1 }; // ok
a < a < int, int >, a < int, int > > q { { 1, 1 }, { 3, 3 } }; // error: bad array initializer
}... | I'm pretty sure that's a bug. {} can be used in place of () for supplying the constructor with arguments. Therefore your code should be ok:
int main ()
{
// this is fine, calls constructor with {1, 1}, {3, 3}
a<a<int, int>, a<int, int>> q({ 1, 1 }, { 3, 3 });
// which in turn needs to construct a T from {1... |
5,475,046 | 5,475,461 | Any metaprogramming way to generate overloads for various numbers of template parameters? | I'm trying to create a set of function templates that can take different types and numbers of parameters, like this:
template <T0>
void call(T0 arg0);
template <T0, T1>
void call(T0 arg0, T1 arg1);
template <T0, T1, T2>
void call(T0 arg0, T1 arg1, T2 arg2);
template <T0, T1, T2, T3>
void call(T0 arg0, T1 arg1, T2 ar... | You can try and do the same thing as Boost does, for example in Boost.Function (link to the template header). They use Boost.Preprocessor to enumerate various things on the given number of arguments. For example consider you want to overload a function for 0-2 arguments. The conventional way would be the following:
voi... |
5,475,378 | 5,475,423 | I need help writing a C++ program that takes two arguments for two functions? | My C++ program needs to take in two arguments text or calc, those are the two functions,
How do I set this up to read in 2 input files using a map?
| You need to pass command line arguments. You can find plenty or resources online. Here are a couple of examples: http://www.cplusplus.com/forum/articles/13355/ and http://msdn.microsoft.com/en-us/library/17w5ykft.aspx.
|
5,475,693 | 5,481,228 | Using '--' as end-of-options marker with boost::program_options | The traditional way of indicating the end of options for command line programs is with the option --. How can I get boost::program_options to recognize this as an option and accept the rest of the command line as positional arguments? The following doesn't work:
namespace po = boost::program_options;
po::positional_op... | I had this same question, but gave up on it.
I believe the way to do this is to call program_options::command_line_parser::extra_style_parser(), passing it a function that takes a vector of string by reference and returns a vector of options (see the style_parser typedef in cmdline.hpp).
Your function will need to dete... |
5,475,982 | 5,476,015 | How to check if a C++ header file is correct with gcc tools? | How can I check if the syntax of a header file is correct with gcc tools?
| You could try compiling it with g++, as in g++ -c myheader.h. This will catch any syntax errors.
|
5,476,152 | 5,476,490 | CUDA - what if I choose too many blocks? | I'm still getting mad on these unknown-size matrices which may vary from 10-20.000 for each dimension.
I'm looking at the CUDA sdk and wondering: what if I choose a number of blocks too high?
Something like a grid of 9999 x 9999 blocks in the X and Y dimensions, if my hardware has SMs which can't hold all these blocks,... | The thread blocks do not have a one to one mapping with the cores. Blocks are scheduled to cores as they become available, meaning you can request as many as you want (up to a limit probably). Requesting a huge number of blocks would just slow the system down as it loads and unloads do-nothing thread blocks to the core... |
5,476,454 | 5,476,469 | why doesn't catch block share the scope of the try block? | Surprisingly, I can't find an answer to that by googling and searching SO (there are lots of similar questions on SO but related to other languages).
I suspect that the answer is no. If so, there is an obvious inconvenience, e.g.
try
{
std::string fname = constructFileName(); // can throw MyException
ofstream f;
... |
Does catch block share the scope of the try block?
No.
How do you deal with this? By moving the std::string fname; out of try, I guess?
Yes.
I understand that a scope is defined by a {} block, but this seems as a reasonable case for, hmm, exception. Is the reason for that that objects can be not fully constructed... |
5,476,589 | 5,476,653 | STL <list> Search List to Find an item property | I don't really have a very good understanding to how STL works.
I was able to create a list and add items to it.
But now I can't seem to search through the list to find an element with a desired property.
Forgive my ignorance on this. I am very new to STL and I still struggle with some elements of C++.
Here is the cod... | You are confusing elements and iterators. Iterators are placeholders for positions in the list, they are not the elements themselves. To get to the element, you need to dereference an iterator:
if ((*ListItem).X == x) // or, easier: if(ListItem->X == x)
{
Monster = *ListItem;
return Monster;
}
}
Furthe... |
5,476,616 | 5,476,857 | stringstream string to int | The C++ code below does int to string and a string to int conversions. Then, it repeats these steps again. The stringstream to int line stream1 >> i3; is breaking the code. What am I missing here?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int i1 = 101;
int i2 = 202;... | I tested your code and could reproduce the problem. I solved it inserting a .clear() before .str("")
Have a look here: How to reuse an ostringstream?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int i1 = 101;
int i2 = 202;
int i3 = 0;
string s1 = "";
string s2 = "";
... |
5,477,272 | 5,480,149 | Desktop App w/ Database - How to handle data retrieval? | Imagine to have a Desktop application - could be best described as record keeping where the user inserts/views the records - that relies on a DB back-end which will contain large objects' hierarchies and properties. How should data retrieval be handled?
Should all the data be loaded at start-up and stored in correspon... | Use Lazy Load and Data Mapper (pg.165) patterns.
|
5,477,563 | 5,477,591 | Template ToString function that works with different character encoding | I've written an INI class that loads/saves/creates an INI data format, however right now it only works with ascii characters, and I would like to expand it to work with any type of character encoding, so besides char, wchar_t. To do this, I have to setup various string functions for doing the parsing; I have some setu... | When I originally posted this question I was close to the answer, but made a careless mistake, and thus have solved my own question while I was still typing it. So for those of you who want a generic toString function that works for a variety of string encodings, here you go:
template<typename CharType, typename T>
st... |
5,477,573 | 5,477,822 | Why doesn't creating/writing to file with fstream work on windows start up? | So here I got this little program which everyone obviously understands.
include <iostream>
include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
This program works just fine, ... | It tries to create the file in the current working directory for the process, since you specified a relative path.
Because there is no way to specify the working directory in the Windows\CurrentVersion\Run registry setting, the working directory is inherited from the parent process. The parent process is the shell, ex... |
5,477,686 | 5,477,806 | use DELETE to save memory, can someone proof | I am learning C++ and for the following code I don't know how much memory would be waisted if I don't delete *p.
#include <iostream>
using namespace std;
int *getPtrToFive()
{
int *x = new int;
*x = 5;
return x;
}
int main()
{
int *p = getPtrToFive();
cout << *p << endl;
delete p; // ????????... | Considering the below example built on Visual C++ 2010 in debug mode, it is going to be 4 bytes leak. CRT is capable of dumping the leaks if found any. ( i.e., not deallocating the acquired resources from free store )
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
int main()
{
int *rawPtr = new int(100) ;
// ... |
5,477,786 | 5,478,983 | Testing Process of a C++ & Qt Application | I'm a part of a big (sort of...) C++ application written mainly in Qt.
I was wondering if this is the right / common approach:
whenever I make a change to a certain / several source files, I compile it (QtCreator) in debug mode, and then launch and test it.
the problem is, each compilation takes a couple of minutes (us... | Try to use unit test with QTest as much as possible, then you can verify the parts first and then top it of with some test on the complete application. This saves a lot of time and can also help to produce more robust code if done right.
This do need some kind of modular approach, so the code needs to be grouped in som... |
5,477,961 | 5,478,435 | How to intercept the "Show Desktop" event? | I'm looking for a way to intercept the ShowDesktop event and set my window at front.
Is there a way doing it without using API hooks?
Thanks,
Omer.
| If you're writing a Windows taskbar style dock then simply make sure your window has WS_EX_TOPMOST set and 'Show Desktop' will leave it alone. Alternatively use SetWindowPos to make it the top-most window after it has been created, e.g.:
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE);
Update: Yo... |
5,478,147 | 5,490,459 | fseek not reading all the data? | I am making a c++ installer and I have appended both the file to extract and an 8 byte filesize of the file to extract within the program, to the executable. My program exits on a file read error, whats going wrong? To note I don't have any knowledge about c file managing, apart from what I've learned today. I am writi... | You don't need the while loop at all. After all, you already allocated the memory that would contain all your data. Move file pointer to the start of data fseek(exeFile, ofset, SEEK_SET), then use fread to read it as whole, and then use fwrite to write it into outFile.
You should open your exeFile and outFile with "rb"... |
5,478,310 | 5,478,367 | Storing a stack in a recursive function | I am trying to search through a binary search tree and store each node in a stack as I traverse through the tree in order to remember my path so that I can perform rotations.
Here is my code:
template <typename T>
bool BST<T>::contains(const T& v, BSTNode *&t)
{
stack<BSTNode*> s;
BSTNode * g;
BSTNode * p;
... | Pass a (non-const) reference to the stack along with the other arguments.
You might need a "setup" function to create the stack initially.
|
5,478,397 | 5,478,523 | How to get GUID (Assembly attribute) of a C# assembly in c++ | I am trying to read GUID attribute of a C#.net assembly from c++ (VC++ 10).
I should mention that, I don't want to use .net or .net reflection. looking for a pure c++ way.
what is the solution ?
Thanks in advance.
| You need to use the Unamanaged Metadata API
and especially the IMetaDataImport::EnumCustomAttributes Method
That's going to be quite a work... Here is a link that gives a good starting point on this (it's C#, but the ideas are exactly the same, and is in fact easier to program in C++): Reading types from assembly
|
5,478,519 | 5,478,586 | Photo Mosaic Algorithm. How to create a mosaic photo given the basic image and a list of tiles? | Hy.What I have to do is to create a program (using C or C++), that takes as input a 24bits/pixel bitmap and a gathering of images and I have to create a mosaic image , similar to the input image using the library of images given(To create a mosaic Photo similar to the input).
So far I can access the input's image p... | I've done this in Scala. The Dr Dobbs article was extremely useful to me.
Sample image:
Here's my basic algorithm:
def createMosaic(targetImage:BufferedImage,
index:PhotoIndexer.PhotoIndex,
opacity:Float,
targetWidth:Int,
targetHeight:Int,
numRows:Int,
numColumns:Int, callback:PhotoMosaicCallback): ImageG... |
5,478,546 | 5,479,015 | Token parser semantic action | I have written a working token parser based on the code shown at spirit lex example 4
One of my rules looks like this
set_name
= ( tok.set_ >> tok.name_ >> tok.identifier )
[
std::cout << val("set name statement to: ") << _3 << "\n"
]
;
This works well. ... | The placeholder in
std::cout << val("set name statement to: ") << _3 << "\n"
refers to boost::spirit::_3, which is a boost.phoenix v2 placeholder. The placeholder in
boost::bind(&writer::print, &w, ::_3)
is a boost.bind placeholder (naturally).
These placeholders do not share the same behavior, or even refer to the s... |
5,478,669 | 5,480,348 | Good techniques for keeping COM classes that implement multiple interfaces manageable | COM objects that implement many interfaces can end up suffering from the god object anti-pattern or end up full of tedious forwarding code:
class MyCOMClass
, public CUnknown
, public IFoo
, public IBar
, public IPersistStream
, public IYetAnotherInterface,
, public IAndAnotherInterfaceToo
// et... | Assuming that you don't need the handler objects to be separate C++ instances from the overall object, then the following may work...
If I Remember my COM Correctly... - why not just leave FooHandler as a partially abstract base class - leave the IUnknown portion unimplemented. Have MyCOMClass derive from all the neces... |
5,478,772 | 5,478,876 | Upgrading from Qt 4.2.1 to Qt 4.6.1 changed the fonts | Just switched from Qt 4.2.1 to 4.6.1 and the fonts are different. Different font type and size (bigger).
I did not regenerate any files just tried compiling with a different Qt version.
All the settings for the fonts, etc. are in the .cpp files.
Any ideas on how to change the fonts back?
I inherited the code and I'm n... | I suspect that this might just be the danger of coding styles like fonts in source code rather than using style sheets. When things change you'll need to add more source code but with style sheets any new stuff should get automatically covered by them provided they are applied on a wide enough scope. Only a guess thoug... |
5,478,913 | 5,526,118 | How does C/C++ select work with gpio under Linux? | How does select work with gpio under Linux?
Is it possible to use select to create a kind of interrupt driven program,
maybe with the help of some threads?
And what shall I think about when I use the select call?
Thanks
Note:
I have read the man page on select, but I think I need some more help on this topic.
man 3p... | Apparently you can use select() on a GPIO exposed through sysfs, but only if it can be configured to generate an interrupt. Your platform may have this or not.
What you want to read though is Documentation/gpio.txt in your kernel source, which mentions how to enable an interrupt for a pin if the kernel driver allows it... |
5,479,319 | 5,479,625 | CUDA - no blocks, just threads for undefined dimensions | I have some matrices with unknown sizes varying from 10-20.000 in both directions.
I designed a CUDA kernel with (x;y) blocks and (x;y) threads.
Since matrices width/height aren't multiple of my dimensions, it was a terrible pain to get things work and the code is becoming more and more complicated to get coalescence ... | You can't really just make a "grid of threads", since you have to organize threads into blocks and you can have a maximum of 512 threads per block. However, you could effectively do this by using 1 thread per block, which will result in a X by Y grid of 1x1 blocks. However, this will result in pretty terrible performan... |
5,479,362 | 5,479,599 | Why is fastcall slower than stdcall? | I found following question: Is fastcall really faster?
No clear answers for x86 were given so I decided to create benchmark.
Here is the code:
#include <time.h>
int __fastcall func(int i)
{
return i + 5;
}
int _stdcall func2(int i)
{
return i + 5;
}
int _tmain(int argc, _TCHAR* argv[])
{
int iter =... | __fastcall was introduced a long time ago. At the time, Watcom C++ was beating Microsoft for optimization, and a number of reviewers picked out its register-based calling convention as one (possible) reason why.
Microsoft responded by adding __fastcall, and they've retained it ever since -- but I don't think they ever ... |
5,479,620 | 5,479,666 | Why is a copy constructor required here? | Consider the following code:
struct S
{
S() {}
void f();
private:
S(const S&);
};
int main()
{
bool some_condition;
S my_other_S;
(some_condition ? S() : my_other_S).f();
return 0;
}
gcc fails to compile this, saying:
test.cpp: In function 'int main()':
test.cpp:6:5: error: 'S::S(const S&)... | The result of ?: is an rvalue, a new object, if one of the arguments is an rvalue. To create this rvalue, the compiler must copy whatever the result is.
if (some_condition)
S().f(); // Compiler knows that it's rvalue
else
my_other_S.f(); // Compiler knows that it's lvalue
This is for the same reason that you c... |
5,479,691 | 10,692,876 | Is there any standard way of embedding resources into Linux executable image? | It is quite easy to embed binary resources into PE images (EXE, DLL) via Windows API (refer to http://msdn.microsoft.com/en-us/library/ms648008(v=VS.85).aspx).
Is there any similar standard API in Linux?
or maybe some kind of de-facto approach to resource embedding?
The goal is to embed some static binary and/or textu... | Make yourself an assembler file, blob.S:
.global blob
.global blob_size
.section .rodata
blob:
.incbin "blob.bin"
1:
blob_size:
.int 1b - blob
Compile with gcc -c blob.S -o blob.o
The blob can now be accessed from within your C program with:
extern uint8_t blob[];
extern int blob_size;
Using a bin... |
5,480,004 | 5,480,044 | how do I convert an integer which is defined in an int array to hex? | I have an int array that represents a very large number such as:
// ...
unsigned int n1[200];
// ...
n1 = {1,3,4,6,1,...} ==> means my number is 13461...
How can I convert that large number to its hex value?
| So here is my take on the problem:
You have an array of digits.
You want to build an unsigned int from this array of digits.
The array of digits could be either HEX digits, or DECIMAL digits.
To build this unsigned long long, assuming an array of DECIMAL digits:
unsigned long long myNum = 0;
unsigned int n1[200];
... |
5,480,189 | 5,480,222 | MVC pattern in Qt4 - how to organize code besides using Interview | i was recently suggested to use MVC pattern to organize my Qt4 application.
I'm a little puzzled :).
How do I implement:
1. model
2. view
3. controller
In HTTP based apps its quite straigtforward. But here I'm not sure what is a view and what is a controller ?
Lets asume that I'm not using Interview right now.
Thanks ... | you can look at this like this:
Controller is the window/form that You created. Member functions in this class should handle all user input and call apropriate member functions in your model.
Model is your class that handles data and implements other logic.
Views are qt widgets used to design your forms/windows
(You ... |
5,480,220 | 5,480,747 | arrays of void pointers | again this question is also origined from "Thinking in C++" Chapter7, Q#7. I believe the Stack header file should be changed to Stack.h
#ifndef STACK_H
#define STACK_H
class Stack {
struct Link {
void* data;
Link* next;
Link(void* dat, Link* nxt);
... | Your Stack constructor asks for an array of pointers on stuffs, and you give it an array of objects. As a bonus, I give you proper main function and freeing memory ^^
#include <cstdlib>
// --- Includes your stuffs ---
using namespace std;
int main(int argc, char* argv[]) {
string* tst_arr[] = new string[3];
tst_a... |
5,480,221 | 5,480,261 | In what situations does new return the same address twice? | Why does the following not compile? It says "error: expected primary-expression before ‘>’ token".
template<typename K, typename V>
struct cmpf {
const K& r;
V& visitor;
cmpf(const K& _r, V& _visitor) : r(_r), visitor(_visitor) {}
template<typename T>
void operator()(T& l) {
if (r.type == a_type(T)) {
r... | Try
return l == r.template get<T>();
Read this FAQ for more information: What is the ->template, .template and ::template syntax about?
|
5,480,633 | 5,481,161 | Mysterious global variables - COM/STA Apartment Object | Here's the scenario:
-COM DLL, loaded into the address space of the process that uses the DLL.
-Inside the DLL couple global variables exist (lets say var a, var b) and a global function.
-Process starts up, calls the global function and initializes globals a, b and calls CoInitialize(NULL) - The thread is an STA.
-The... | It's possible that two instances of your DLL are being loaded -- one explicitly by the application that hosts your DLL, and the second through the COM subsystem via CoCreateInstance. The former will look in the DLL search path for the application's process, while the latter will look in the registry for the location o... |
5,480,668 | 5,480,679 | Attempting to create a pointer to previous object inside object | I'm attempting to create a vector of pointers to Nodes, where each node stores a pointer to the previous Node in the list.
I made a small test program to see if I could access a variable gscore in the previous object to the one I call.
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
Node(... | You never initialize tempnode2. You initialize tempnode twice.
int main()
{
std::vector<Node*> nodeVec;
Node *tempnode;
tempnode = new Node(10);
Node *tempnode2;
tempnode2 = new Node(11); // <<---- HERE
nodeVec.push_back(tempnode);
nodeVec.push_back(tempnode2);
nodeVec[1]->previous =... |
5,480,753 | 5,480,875 | Towers of Hanoi with 3 parameters in C++, Tower(Disk, from, to) | I have been trying to figure out how to implement a recursive function with just 3 parameters: Tower(Disk, from, to). I did a lot of research on google. All the results came up with the 4 parameters recursive function, (disk, a, b, c). Any help will be greatly appreciated.
EDIT:
typedef void (*towersActionFn)(unsigne... | //Pegs are counted 0 to 2
void Tower(int Disk, int Startpeg, int Endpeg)
{
if(Disc <= 0) //Sanity check
return;
if(Disc == 1)
cout << "Move disk from "<<Startpeg<<" to "<<Endpeg<<endl;
else
{
int Other = 3 - Startpeg - Endpeg;
Tower(Disc-1, Startpeg, Other);
T... |
5,480,932 | 5,480,979 | Why do the overloads of vector::insert return void? | template <class InputIterator>
void insert ( iterator position, InputIterator first, InputIterator last );
I need to insert twice into my vector, but the data is large and my vector needs to reallocate. How am I supposed to know where to insert the second time (at the same position) if the call to insert invalidat... | Er... But you are the only person that knows where you want to insert your data. How is vector supposed to know where you are planning to make the second insertion?
If you plan to make two consecutive insertions at the same location (just guessing), then you can convert your iterator to "reallocation-independent" form ... |
5,481,200 | 5,481,217 | How to set more strict compiling rules in VC when compile C++ template code | guys,
I want VC has the same strict compile rules as GCC when it compiles the c++ template code. But I don't know how to set this in my VC9.0 (Visual Studio 2008).
For example,
the following code is not allowed in GCC.
AutoPtr<RefCounted<Shape>> shape;
since ">>" is not allowed here, and gcc requests to add at least ... | You don't. :( MSVC++ simply handles templates incorrectly, and you have to be careful.
Note that your particular example isn't actually an error in C++0x, so MSVC2010 would actually be right to accept it. (It's still wrong on lots of other things, though, but it's gotten a bit better.)
You might even "cheat" and enabl... |
5,481,218 | 5,481,234 | Concatenate string points into another string pointer C++ | Hi everyone I have the following line:
string* playerInfo = "Name: " + firstName + " " + lastName + "\n" +
"Number: " + playerNumber + "\n" +
"Points: " + pointTotal + "\n";
where firstName, lastName, playernumber, pointTotal are all string pointers.
How can I put them a... | Use less pointers. That would have worked if all your variables were just strings. But since you say you have pointers:
string playerInfo = "Name: " + *firstName + " " + *lastName + "\n" +
"Number: " + *playerNumber + "\n" +
"Points: " + *pointTotal + "\n";
One of the first ha... |
5,481,356 | 5,481,491 | Overriding Qualified Virtual Methods | I have C++ class with multiple parents; each parent defines a function with a common name but a different purpose:
class BaseA
{
virtual void myFunc(); // does some task
};
class BaseB
{
virtual void myFunc(); // does some other task
};
class Derived : public BaseA, public BaseB;
If that was it, I would have... | Microsoft allows that syntax (it's available beginning in Visual C++ 2005). They also introduced a new, more powerful syntax for managed code only.
Neither one was included in C++0x.
See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2108.html
I think this is a workaround:
class BaseA
{
protected:
virtu... |
5,481,378 | 5,481,393 | Cannot convert parameter from 'const char[20]' to 'LPCWSTR' | When compiling this code:
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInsance,HINSTANCE hPrevInstance,PSTR cmdLine,int showCmd){
MessageBox(0,"First Win32 Program","Window Tittle",MB_OK);
}
I get the compiler error:
Error C2664: 'MessageBoxW': cannot convert parameter 2 from 'const char [20]' to 'LPCW... | You have UNICODE defined, so MessageBox is expecting a wide string.
|
5,481,383 | 5,486,685 | How to link a library file under C++? | I am trying to use a open source library under C++.
The README file states that
You need to link your program with `svm.cpp'.
I am wondering how to link my program with svm.cpp? Do I need to modify the make file to make this happen?
| Compile svm.cpp with not linking, will result svn.o object file, use it object file with your program linking.
|
5,481,503 | 5,481,552 | How to delete char * in c++? | In my application, I create a char* like this:
class sample
{
public:
char *thread;
};
sample::sample()
{
thread = new char[10];
}
sample::~sample()
{
delete []thread;
}
Am I doing the right thing in the code?
| List of points to be noted:
1) You need to allocate room for n characters, where n is the number of characters in the string, plus the room for the trailing null byte.
2) You then changed the thread to point to a different string. So you have to use delete[] function for the variable you are created using new[].
But wh... |
5,481,536 | 5,484,600 | Istream fails. What is the safe way to use it! | So I am wondering what happens if I have the following code
int i;
cin>> i;
But I actually entered "abc" instead of an integer. It fails? What are the ways to make sure reading from commmand line does not fail?
| Almost by definition, you can't ensure that reading from the command
line doesn't fail. To do that, you'd have to control what was being
typed in on the keyboard (or was in the file or whatever the input was
redirected from). You have to be prepared for errors in that input. If
you need an int, and the user types in... |
5,481,587 | 5,481,790 | Error compiling C++ program | I get this error while compiling:
error: aggregate 'X x' has incomplete type and cannot be defined
I have three classes in 6 different files(header file + 3 implementation files). when I try to compile all these classes with a main, It gives me the above error. I am not including any header file in other header files,... | Somehow, that class isn't being defined when it needs to be.
Firstly, make sure the header has actually been included. Further, make sure you have include guards, and that you don't have circular includes and recursive definitions. Aside from that, without the code we cannot give specifics.
|
5,481,593 | 5,481,645 | how to get words inside a string | well i am working with xml but it is not important now, the problem is the next
it returns me something so
<xml>blalbalblal asfjñs
fasdf
iduser=dmengelblack; name=angel; lastname=uc;
blablal
iduser=cccarlos; name=carlos; lastname=uc;
how do i get (dmengelblack, angel, uc, carlos, uc)
i want to save every row...
remem... | Simple way in java is to read the file as a stream, iterate through that and get the substring between
iduser= and ;
and
name= and ;
and
lastname= and ;
EDIT: With this code you will get the list of all the filed you want as
OUTPUT:
[iduser=dmengelblack, iduser=cccarlos]
[name=angel, name=carlos]
[lastname=uc, last... |
5,481,658 | 5,483,008 | cannot create a unary tuple with an empty tuple in it (c++0x) | I was experimenting with tuples and encountered a problem with creating tuples.
The code example is as follows.
//a.cpp
#include <tuple>
using namespace std;
int main() {
auto te = make_tuple(); //this line is ok
auto tte = make_tuple(te); //this line gives an error.
return 0;
}
I compiled it with both g++ 4... | This looks like the compiler has matched your std::tuple<> against the following constructor of std::tuple<std::tuple<>> (See 20.4.2p15-17 in N3242):
template <class... UTypes> tuple(const tuple<UTypes...>& u);
Requires:
sizeof...(Types) == sizeof...(UTypes).
is_constructible<Ti , const Ui &>::value is true for al... |
5,481,681 | 5,485,475 | Switching from Visual Studio to GNU build system. Need general advice | I need to convert several large Visual Studio projects to use GNU build tools. GUI IDE is no option. Right now I am trying to learn make & autotools. There are some good tutorials online, including the official documentation. But the amount of material is quite overwhelming. I would really appropriate any newbie advice... | Like both Naszta and Fabio recommended: Try out CMake, because it can generate visual studio projects on windows and unix-makefiles.
In addition, I would suggest you look at MinGW: MinGW provides a GCC toolchain on Windows. You can start by porting your code to MinGW, while keeping all the windows-specific stuff. In a... |
5,481,877 | 5,483,375 | c++ dom parser problem | I want to change an XML file. I'm using DOM Parser. My XML file is the following:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!-- Put site-specific property overrides in this file. -->
<configuration>
<property>
<name>fs.default.name</name>
<value> name</value>
</property>... | After m_ConfigFileParser->parse( configFile.c_str() ); do the following (considering "configuration" is the root element):
DOMDocument* doc = m_ConfigFileParser.getDocument();
DOMElement* root = dynamic_cast<DOMElement*>( doc->getFirstChild() );
if ( root ) {
DOMElement* property = dynamic_cast<DOMElement*>( root->ge... |
5,481,922 | 5,481,954 | Recursive boolean function | Say I have the following:
bool signal(QtreeNode * & orig, QtreeNode * & n, int tolerance) {
bool signal1= false, signal2= false, signal3= false, signal4= false;
if(n->isLeaf()){
if(totalDiff>tolerance) //suppose these were defined
return true;
else return false;
}
signal1=si... | You'll hit every leaf in your quadtree this way. Instead you want to break as soon as you've found it. To do that you need to change
signal1=signal(orig, n->neChild, tolerance);
signal2=signal(orig, n->nwChild, tolerance);
signal3=signal(orig, n->swChild, tolerance);
signal4=signal(orig, n->seChild, tolerance);
if(s... |
5,481,941 | 5,482,025 | C++ pure virtual function have body | Pure virtual functions (when we set = 0) can also have a function body.
What is the use to provide a function body for pure virtual functions, if they are not going to be called at all?
| Your assumption that pure virtual function cannot be called is absolutely incorrect. When a function is declared pure virtual, it simply means that this function cannot get called dynamically, through a virtual dispatch mechanism. Yet, this very same function can easily be called statically, non-virtually, directly (wi... |
5,482,203 | 5,484,730 | Boost Client getting stuck | http://www.boost.org/doc/libs/1_46_0/doc/html/boost_asio/example/chat/chat_client.cpp
I am working on client application based on he example above.
I wanted to do the client connection in separte thread so that UI doesnot get stuck.Here UI is getiing stuck.
1. Can you tell me how to acheive this?
2. what is th... |
Can you tell me how to acheive this?
You could launch the boost thread in your main i.e. somewhere before you enter the UI event loop (the blocking call) but don't do a join.
Have a look at the HTTP server examples: In one of them it's shown how you can start your io_service in the main and stop it via CTRL-c. In y... |
5,482,398 | 5,482,489 | What are the limitations of SpicIE in developing an IE add-on? | Are there limitations to using SpicIE (with C#) to develop an IE extension? If an IE extension is developed in SpicIE, and then later needs to be developed as a BHO (C++?), will it have to be rebuilt from scratch?
| I don't think you will be limited if you use this, as it's mostly a thin layer between IE and the extension that uses it. Even if something's missing, the CLR has powerful interop mechanisms, and last, you have SpicIE source.
If you ever need to port it over to a C++ project, yes, you will have to rewrite it, but the l... |
5,482,406 | 5,483,398 | Can I get away with not mocking all methods in an interface in C++ when using googlemock | I am using Google Mock 1.6 RC and am trying to Mock a COM Interface. There are close to 50 methods in the COM Interface some of which are inherited from base interfaces. When I create a mock struct that inherits from this interface and mock only the methods I am using, I get the cannot instantiate abstract class error.... | It is not possible to do. You have to overload all pure virtual methods from all interfaces (except for the constructor and destructor).
|
5,482,447 | 5,482,647 | C++: how to check whether an external program is running? | I run an external program with C++:
_wsystem(exec);
I want to kill the process if it runs for more than n seconds. I can do it in Python like this:
p = subprocess.Popen(self.temp_exec, shell=True)
cur_time = 0.0
while cur_time < self.time_limit:
if p.poll() != None:
# Kill the process
... | There is a MS knowledge base entry describing how to cleanly terminate applications. Essentially if you just want to kill the process and don't care about potential side effects then you can just use TerminateProcess.
The Windows API way to check if a process is still running is GetExitCodeProcess.
|
5,482,593 | 5,482,606 | How to convert CString to CTime in c++? | I want to use system's date/time which is in mm/dd/yy format in code. But the problem is that the time that I am getting is not in ate/time format. So I want to change it to CTime format so that I can use it. How is this going to be possible? How can I convert the CString into CTIme format?
Regards,
Mohan
| The sample for your issue is as follows:
COleDateTime myDtTime;
CTime sysTime;
if(myDtTime.ParseDateTime(strTimestampOther))
{
SYSTEMTIME st;
if(myDtTime.GetAsSystemTime(st))
{
sysTime = st;
}
}
else
ASSERT(FALSE);
|
5,482,595 | 5,482,605 | Is it possible using c++ library function in c prog? | In c program, I want run c++ library function(s), but I don't know how can I do that. Like ever c++ programmer, I know how to use c program under c++ prog. therefore, I wonder it is possible using c++ library function, namely cout, vector etc., in c ?
| Generally, you cannot use C++ facilities in C.
However, a C++ library may choose to export some of its functionality to C programs, by declaring them extern "C". If your C++ library doesn't do this, you will have to write some wrappers (in C++) that do this.
Note that such exported functionality have to conform to C's ... |
5,483,009 | 5,495,371 | QTableView: When selecting cells, how do I make the first cell selected the current index? | I have a simple class which inherits QTableView and I want the following behavior: when the user selects a few cells, I want the first cell selected to be set as the current index.
So for example if I select from (0, 0) towards (2, 2), when I start typing the text would show up in (0, 0), not (2, 2) which seems to be... | I figured out the problem and how to fix it, but it's not pretty. The problem is in the mouse moved event for a QAbstractItemView. After much debugging and searching through the source code I found this in qabstractitemview.cpp:
void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
...
if (index.isValid()
... |
5,483,043 | 5,483,379 | Adding an include path to the parent directory in GCC | I'm wanting to include files from the parent directory in a project I am working on. All of the header files are in the parent directory, is there any way of using -I on the commandline to search for includes in the parent directory without using an absolute path?
I know I can solve these issues using a makefile and I ... | Hmm...
g++ -Wall -I.. simple.cpp
and
// Somewhere in simple.cpp
#include <include_file.hpp>
should work.
|
5,483,068 | 5,484,027 | JNI - connecting STDOUT to a JTextArea? | I am wondering if it is possible to connect STDOUT of a C/C++ dll to a JTextArea? The thing is, I am using 3rd party DLL's so I can't manually alter them.
Basically I have my Java applet, and then my own DLL which Loads and manages the 3rd party DLL's, and it is the 3rd part DLL's which do stuff like printf(). It show... | What is STDOUT? If it's the Posix file handle, there's not much you can
do. You'd have to close it, then open a temporary file, write to that,
and then read it in the Java part. If you're actually using std::cout
for the output, it's possible to (temporarily) change the streambuf of
it to use a stringbuf, then pass ... |
5,483,490 | 5,487,448 | Special routing for application via WinSocks or any another API? | I want to route packets sended from my application to another gateway but i don't know what options i must change via setsockopt.
I can't just add entries to routing table for specific hosts because second application also must connect to these hosts but via default gateway. Gateways have different public IPs.
I found... | Short answer : this is really hard, are you sure you want to do it ? It is not possible directly via set sock opt. Most probably there are easier choices by adding routes manually with the command line utility "route". That will the best choice if your final destination is a known IP or network and that normal traffic ... |
5,483,601 | 5,483,694 | getting an error during overloading the operations | SOLVED
I'm writing a code for making Set by linked lists in C++ with visual C++ 2010.
when I want to overload the operations I get this Error
1>test.obj : error LNK2019: unresolved external symbol "public: __thiscall MySet::MySet(class MySet const &)" (??0MySet@@QAE@ABV0@@Z) referenced in function "public: class MySet... | Have you declared and defined the following constructor method?
MySet::MySet(const MySet &other)
{
....
}
|
5,483,930 | 5,483,978 | 'powf' is not a member of 'std' | I have an error while compiling a library using XCode:
'powf' is not a member of 'std'
The <cmath> is included.
Can someone explain to me what is going wrong?
| Up until C++11, powf was just a Microsoft-ism. It did not appear in the ISO standard at all so is unlikely to be in XCode unless they were to adapt Microsoft's bizarre practices, something I would think unlikely.
pow, on the other hand, has been part of the C++ library for longer by virtue of the fact that it's in earl... |
5,483,963 | 5,484,008 | Problem compiling stl map insert | I'm having trouble compiling the following code:
typedef std::map<mUUID, block_ptr_t> BlockMap;
BlockMap _store;
std::pair< BlockMap::iterator, bool > it;
it = _store.insert(hint, std::make_pair(entry.block_uid, block));
The error is:
error: no match for ‘operator=’ in ‘it = BlockStore::_store.std::map<_Key, _Tp, _Co... | The version of insert that takes a hint returns only an iterator, not a pair.
|
5,483,975 | 5,484,504 | Boost Fusion/MPL: convert type from sequence to sequence of equivalent any_range's | I want to use Boost's any_range to handle multiple heterogeneous data ranges. The type of my data ranges is known as a Fusion vector, for example:
typedef vector<double, int, char> TypeSequence
Given such a type, I want to write a template to derive a further type like this:
vector<AnyRange<double>::value, AnyRange<i... | You can do this easily using boost::mpl::transform, which you can use with Fusion sequences (as long as you include the appropriate headers to make Fusion sequences behave as confirming MPL sequences):
#include <boost/range/any_range.hpp>
#include <boost/fusion/include/mpl.hpp> // Required to adapt Fusion to MPL
#incl... |
5,484,146 | 5,486,141 | Qt progressBar getting Unhandled exception how detect when parent widget is done loading | im using Qt QProgressBar and place it in the statusBar on my main window
Like this in the constructor :
pb = new QProgressBar(statusBar());
pb->setTextVisible(false);
pb->hide();
statusBar()->addPermanentWidget(pb);
then im running procsses (web page loadding in this case )
and trying to show the progress with :
con... | In your createWebViewActions() function you connect the signals to their respective slots. (One small remark, the connect for the titleChanged(QString) signal and adjustTitle() slot fails because they have different signatures)
Among others you are connecting the signal loadProgress(int) to slot setProgress(int). In th... |
5,484,187 | 5,484,252 | What design pattern is this? | Several years ago, I used to create interfaces like this :
class Base
{
public:
virtual ~Base
{
}
void foo()
{
doFoo();
}
private:
virtual void doFoo() = 0;
};
then a derived would be :
class Derived : public Base
{
public:
virtual ~Derived()
{
}
private:
vi... | Your foo method shouldn't be virtual. And in this case the design pattern is called NVI - non-virtual interface
|
5,484,335 | 5,484,479 | TDD and housekeeping overhead with C++ | I do test driven development of c++ code and one thing I find awkward is the fact that I need to create many files for each class, for example:
iread.h
read.h
read.cpp
mockread.h
mockread.cpp
testread.h
testread.cpp
And add these to different folders (filters) within my project.
As a result, I've abondand cpp files t... | Unfortunately with C++ the 'header and module' thing is not going away soon.
My tips for the source/mocks/test file problems are:
Move mocks into the test files - the tests are the only clients of the mocks afterall.
Use module only test files
I've written my own test framework that allows .cpp only files for tests.
... |
5,484,407 | 5,484,463 | .NET WebClient.DownloadData(url) alternative in C++/WinAPI? | How can I get contents of a file online with C++?
| There are a number of ways you can do this.
WinInet
First off Windows has a built-in API allowing you to make HTTP requests, which is reasonably simple to use. I use this simple wrapper class to download files using it:
/**
* Simple wrapper around the WinInet library.
*/
class Inet
{
public:
explicit Inet() : m_... |
5,484,735 | 5,484,943 | Computation Cost of float Sizes | Is there any difference between the computation of small floats - that are close to 0 - and big floats - that are far from 0?
| It depends what kind of computation you are talking about. Adding two numbers together is likely to take the same length of time regardless of the magnitude of the number. In the case of division, the size of the operand can make a difference - for instance, see Intel reference manual page C.34:
If you try compiling t... |
5,484,881 | 5,484,913 | Matrix(row, col) = value | double Matrix::operator()(unsigned int a, unsigned int b)
{
return m[a*rows+b];
}
I have the above currently for accessing the value stored in the matrix, however I'd like to be able to set the value at that position. Is that possible?
| How about returning a reference:
double& Matrix::operator()(unsigned int a, unsigned int b)
{
return m[a*rows+b];
}
Then you can set the value of the corresponding element.
|
5,484,906 | 5,485,377 | Can a mock class inherit from another mock class in googlemock? | Can a mock class inherit from another mock class in googlemock? If yes, then please help me in understanding why isn't this working.
class IA
{
public:
virtual int test1(int a) = 0;
};
class IB : public IA
{
public:
virtual float test2(float b) = 0;
};
class MockA : public IA
{
public:
MOCK_METHOD1(test1, in... | If you plan on using multiple inheritance, you should be using virtual inheritance.
Next example compiles and link fine :
class IA
{
public:
virtual int test1(int a) = 0;
};
class IB : virtual public IA
{
public:
virtual float test2(float b) = 0;
};
class MockA :virtual public IA
{
public:... |
5,484,930 | 5,487,053 | split variadic template arguments | How do I split variadic template arguments in two halves? Something like:
template <int d> struct a {
std::array <int, d> p, q;
template <typename ... T> a (T ... t) : p ({half of t...}), q ({other half of t...}) {}
};
| We still lack a lot of helpers to manipulate variadic parameter packs (or I am not aware of them). Until a nice Boost library brings them to us, we can still write our own.
For example, if you are willing to postpone your array's initialization to the constructor body, you can create and use a function that copies part... |
5,484,938 | 5,649,070 | Character encoding problem with QextSerialPort (Qt/C++) | I am developing a Qt/C++ programme in QtCreator that reads and writes from/to the serial port using QextSerialPort. My programme sends commands to a Rhino Mark IV controller and must read the response of those commands (just in case they produce any response). My development and deployment platform is Windows XP Profes... | Finally, I have realized that I was not configuring the serial port correctly, as suggested by Judge Maygarden. I did not find that information in the device's manual, but in the manual of a software product developed for that device.
The correct way to set up the serial port for connecting to the Mark IV controller is... |
5,485,346 | 5,485,666 | reading buffered text data to string | Hi I want read from a hung text file data directly to a string
I know that i can use the following:
ifstream infile("myfile");
string str(istreambuf_iterator<char>(infile), istreambuf_iterator<char>());
but this way read whole file in one step.
I want read it in several step beacuse this is very larg file about 50GB.... | I'd do something like this (bufSize can be modified to fit your needs):
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void ReadPartially(const char *file)
{
const unsigned bufSize = 10;
ifstream is(file);
string str(bufSize, '\0');
unsigned count=0;
while(!is.eof())... |
5,485,534 | 5,485,591 | compiler misinterprets my code and adds an extra "const" to argument | I'm stuck on a compiler error and I can't seem to find a solution online (mainly because google can't handle the syntax). This is the one and only error I'm getting (MVS 2005).
error C2664: 'LinkedList<T>::CreateLinkedList' : cannot convert parameter 2
from 'const MemberInfo *' to 'MemberInfo *const *' memberdata.cp... | Your LinkedList<MemberInfo*> should be LinkedList<MemberInfo>.
Notice that the error message mentions MemberInfo *const * - a pointer to a pointer.
As the type you use to instantiate the template is a MemberInfo *, T will be MemberInfo * and the CreateLinkedList functions expects a T const * aka a MemberInfo * const *.... |
5,485,579 | 5,485,629 | How do I write a copy constructor for my class which has a std::stringstream member? | If I have a class like this, how should I write the copy constructor?
#include <stringstream>
class MyClass {
std::stringstream strm;
public:
MyClass(const MyClass& other){
//...
}
std::string toString() const { return strm.str(); }
};
std::stringstream has no copy constructor itself, so I can't use an in... | You can try this:
MyClass(const MyClass& other): strm(other.strm.str()) {}
|
5,485,585 | 5,485,607 | c++ isalnum endless loop | Greetings!
Lets cut the excessive intro this time and get straight to the point.
I have a problem in C++ using the isalnum method.
the code:
int playAgainst = 0;
do
{
cout << "Who do you want to play against?(1/2)\n";
cout << "1: Human player\n";
cout << "2: Computer player\n";
cin >> playAgainst
} whil... | Make playAgainst a char and compare against '0', not 0. Right now, the user has to enter the ASCII (or whatever your character set is) code for the character '1' or '2'.
isalnum won't work on ints outside the valid range of char, except for EOF. (The fact that it takes an int argument is a leftover from C, which has di... |
5,485,774 | 5,536,563 | How to show my own context menu in Internet Explorer | I'm writing add-on for Internet Explorer 9 and I have to change default context menu to my own. I'm writing a BHO in C++ and I'm using ATL. I managed to handle event of showing context menu (HTMLDocumentEvents2::oncontextmenu), but I can't display my own one. Here is the code fired when you click right mouse button:
VA... | I fgured it out. Igor Tandetnik helped me on IE addon forum. HWND was from different proccess and TrackPopupMenuEx expects HWND belonging to the calling thread. Here's the code that works:
VARIANT_BOOL STDMETHODCALLTYPE CSpellCheckerBHO::OnContextMenu( IHTMLEventObj *pEvtObj)
{
HMENU contextMenu = CreatePopupMenu()... |
5,485,802 | 5,485,841 | Build a linux library for windows with MinGW | There is a lib sources for linux with make scripts.
http://svn.gna.org/svn/pokersource/branches/poker-eval-java/.
I need to build it for windows. It should be two dll. The main dll and the second dll is jni-wrapper to call the native functions from java.
I have built it under the linux with such commands:
autoreconf --... | you need to add:
#include <stdint.h>
in the enumerate.c file. This will get you past this error, but it's most likely you'll have to add this line to more than one file.
|
5,485,998 | 5,486,050 | Allow my C++ library to work with C (reduced function sets) | I've been wanting to build a shared library of which will utilize classes to keep its functioning clean (it may require many inputs or processing), although I still wish to target for C platforms.
If I apply extern "C" {} over all my prototypes, and provide in example a set of exposed functions that mimick the class fu... | If you create a dll in the fasion you described, that is, all interfaces are extern "C" and all types in interfaces are POD's then yes, you'll practically have no problem using it in C or .NET
Example:
class MyClass
{
public:
MyClass(float x) {...}
void method(int x) {...}
~MyClass() {...}
};
#define MYAP... |
5,486,045 | 5,487,044 | GCC Optimization results in "Undefined symbol" at runtime | I right now have a problem that is rather confusing to me:
I have piece of software written in C++ and that links against a library in C. I include the header classes using the usual
extern "C" {
#include <libheader.h>
}
Everything works fine as long as I do not use gcc's optimization. Once I turn on even -O1, thu... | Is it possible that the header that defines the calling inline function includes the library's header without the extern "C" wrapper, and everywhere else the wrapper lines are used?
Did you try other levels like -O2?
Did you try uninlining your function?
|
5,486,100 | 5,486,293 | How to pass data to objects created with Factory Method | I'm creating a series of objects through a Factory Method pattern. More or less like so:
class CMyFactory
{
public:
virtual CMyObject* MakeObject(ObjectType type);
}
CMyObject* CMyFactory::MakeObject(ObjectType type)
{
CMyObject* newObject = NULL;
switch (type)
{
case type1:
newObject = ... | One thing you could do is pass it to the constructor, like so:
class CMyFactory
{
public:
virtual CMyObject* MakeObject(ObjectType type, ParamType param);
}
CMyObject* CMyFactory::MakeObject(ObjectType type, ParamType param)
{
CMyObject* newObject = NULL;
switch (type)
{
case type1:
newO... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.