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 |
|---|---|---|---|---|
2,916,492 | 2,916,657 | Can boost::program_options Use A Delimiter Other Than "-"? | I am using boost::program_options like this:
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,?", "Show Options")
("capture-file,I", po::value<string>(), "Capture File")
("capture-format,F", po::value<string>()->default_value("pcap"), "Capture File Forma... | To use / and -, use command_line_parser's style() method with the appropriate combination of style_t flags. For example:
po::store(po::command_line_parser(ac, av)
.options(desc)
.style(po::command_line_style::default_style
| po::command_line_style::case_insensitive
| po::command_line_style::all... |
2,916,549 | 2,916,779 | ~1s latency control app: is this suitable for Java? | At my work we recently finished the system architecture for a control application which has a maximum latency of roughly one to two seconds. It is distributed on small ARM on-chip boxes communicating via an IP LAN.
We initially foresee that we would use C or C++, since it is a classical control system language. After ... | The GC is only used for reclaiming memory from discarded objects. Discard very little resources and you will get very little, shorter GCs.
You might use lots of sockets, file handles, handles from external libs, but how fast do you discard them?
A full GC is designed to remove fragmentation. It does this by copying a... |
2,916,592 | 2,916,866 | Qt Won't Compile (10.5 Intel Mac) | I am trying to compile the latest version of Qt for the mac (from Gitorius). When I try to compile this (by doing ./configure and then make), I get the following error while running make:
../../include/QtCore/../../src/corelib/kernel/qvariant.h: In function ‘T qvariant_cast(const QVariant&) [with T = QVariant]’:
../../... | Did you downloaded a stable version? Because you might accidentaly downloaded a beta/unstable version from Gitorious, which might not compile
Also, just download an appropiate stable version tarball from ftp.trolltech.com and compile it.
|
2,916,675 | 4,251,093 | Programmatically obtain DNS servers of host | Using C++, I would like to obtain the DNS servers being used by a host for three operating systems: OS X, FreeBSD, and Windows. I'd like confirmation that the approaches below are indeed best practice, and if not, a superior alternative.
OS X: already answered; updated link at developer.apple.com
Windows: GetNetworkP... | On many unix systems (linux, bsd) you can use the resolver functions to obtain the list of DNS servers: man 3 resolver.
After calling res_init() the resolver structure is initialized. The resolver structure stores all the information you need. The list of DNS servers are stored in the struct entry nsaddr_list.
The exac... |
2,916,691 | 2,916,842 | Visual C++: Compiler Error C4430 | The code of Game.h:
#ifndef GAME_H
#define GAME_H
class Game
{
public:
const static string QUIT_GAME; // line 8
virtual void playGame() = 0;
};
#endif
The error:
game.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
game.h(8): error C2146: syntax err... | Here is what you need to fix your issues:
1. Include the string header file:
#include <string>
2. Prefix string with its namespace:
const static std::string QUIT_GAME;
or insert a using statement:
#include <string>
using std::string;
3. Allocate space for the variable
Since you declared it as static within the class,... |
2,916,759 | 2,916,893 | undefined reference to static member variable | I have this class that has a static member. it is also a base class for several other classes in my program. Here's its header file:
#ifndef YARL_OBJECT_HPP
#define YARL_OBJECT_HPP
namespace yarlObject
{
class YarlObject
{
// Member Variables
private:
static int nextID; // keeps track... | Make sure you are linking against the generated .o file. Double-check the makefile.
|
2,917,168 | 2,917,221 | functional, bind1st and mem_fun | Why won't this compile?
#include <functional>
#include <boost/function.hpp>
class A {
A() {
typedef boost::function<void ()> FunctionCall;
FunctionCall f = std::bind1st(std::mem_fun(&A::process), this);
}
void process() {}
};
Errors:
In file included from /opt/local/include/gcc44/c... | Because bind1st requires a binary function object. However you pass an unary function object. The function object binders of C++03 aren't as sophisticated as the one found in boost or tr1. In fact, they suffer from basic problems like not being able to handle functions with reference parameters.
Since you already use ... |
2,917,436 | 2,917,470 | Why are enums considered compound types? | Arrays, functions, pointers, references, classes, unions, enumerations and pointers to members are compound types.
My understanding of a compound type is that is based on other type(s). For example, T[n], T* and T& are all based on T. Then what other type(s) is an enumeration based on?
Or if my understanding of compoun... | In C++ enum types are scalar types, yet at the same time they are compound types since they are built on top of some fundamental integral type. In case of an array or pointer you specify "base" type explicitly, but in case of an enum the specific underlying integral type is chosen implicitly and automatically by the im... |
2,917,828 | 2,917,870 | Noise with multi-threaded raytracer | This is my first multi-threaded implementation, so it's probably a beginners mistake. The threads handle the rendering of every second row of pixels (so all rendering is handled within each thread). The problem persists if the threads render the upper and lower parts of the screen respectively.
Both threads read from t... |
Both threads read from the same variables, can this cause any problems? From what I've understood only writing can cause concurrency problems...
This should be ok. Obviously, as long the data is initialized before the two threads start reading and destroyed after both threads have finished.
Can calling the same fun... |
2,917,897 | 2,918,160 | How should I pass an object wrapping an API to a class using that API? | This is a revised/better written version of the question I asked earlier today -- that question is deleted now.
I have a project where I'm getting started with Google Mock. I have created a class, and that class calls functions whithin the Windows API. I've also created a wrapper class with virtual functions wrapping t... | There's always the option of using shared_ptr; that would certainly solve the ownership problem.
|
2,917,904 | 2,917,914 | Show descrition text (WINAPI) | I was wondering how I can show description text. By this I mean, for example if you hover over the Start button a small description will appear saying "Start". How are these invoked?
Thanks
| You are looking for Tooltip Controls
|
2,918,008 | 2,918,140 | Getting values of an object after a call to rotatef c++ | I need to access the X,Y values of a vertex object after Ive rotated it (with glRotate3f). How is it possible? I need em to solve an object collision problem where collisions will be sending objects in an angle related direction based upon objects rotation degrees.
edit::
Ok, Ive come close to find a way. Lets assume X... | You are misunderstanding things a bit.
You didn't rotate anything by calling glRotatef. When you call glRotate, you modify transformation matrix, the object data remains unchanged. When you render object, the vertex data goes through vertex processing pipeline, gets multiplied by transformation matrix (every time you r... |
2,918,202 | 2,918,235 | Where is shared_ptr? | I am so frustrated right now after several hours trying to find where shared_ptr is located. None of the examples I see show complete code to include the headers for shared_ptr (and working). Simply stating std, tr1 and <memory> is not helping at all! I have downloaded boosts and all but still it doesn't show up! Can ... | There are at least three places where you may find shared_ptr:
If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.
If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Micros... |
2,918,225 | 2,921,065 | CImg compile problems in Codegear 2009 | I wish to use the CImg library for image processing in my current project. I am using Codegear C++ Builder 2009. I include CImg.h in the source file and put in the following code:
int rows =5;
int cols = 5;
CImg<double> img(rows,cols);
I get the following error:
[BCC32 Error] CImg.h(39159): E2285 Could not find a mat... | A 40,000 line library that's contained in a single header file? That seems like a bad idea...
Anyway, unfortunately, C++Builder 2009 isn't a very good C++ compiler, so it will often fail to handle otherwise legal C++ constructs. (It's not unusual for C++ compilers to fail to properly handle one aspect or another of t... |
2,918,351 | 2,918,359 | How can I pass Arguments to a C++ program started by the Registry? | I'm creating a Win32 program that will be executed every time the computer turns on. I manage to do this by adding the .exe path into the registry. The problem is; I want to make the program appear minimized in the system tray when the computer is turned on but if I double click it [after the computer turns on and the ... | Even if it's not possible to launch your program with command line arguments from the registry, you can use a batch script to do so. Just create a batch script that launches your program with the appropriate arguments, and use the registry to run that batch script instead.
|
2,918,353 | 2,918,470 | Obtaining command line arguments in a Qt application | The following snippet is from a little app I wrote using the Qt framework. The idea is that the app can be run in batch mode (i.e. called by a script) or can be run interactively.
It is important therefore, that I am able to parse command line arguments in order to know which mode in which to run etc.
[Edit]
I am debu... | If your argc and argv are good, I'm surprised this would be possible as QApplication::arguments() is extremely simple. Note the source code. Filtering the #ifdefs for Linux, it's just:
QStringList QCoreApplication::arguments()
{
QStringList list;
if (!self) {
qWarning("QCoreApplication::arguments: Ple... |
2,918,380 | 2,918,627 | Can my thread help the OS decide when to context switch it out? | I am working on a threaded application on Linux in C++ which attempts to be real time, doing an action on a heartbeat, or as close to it as possible.
In practice, I find the OS is swapping out my thread and causing delays of up to a tenth of a second while it is switched out, causing the heartbeat to be irregular.
Is t... | It is hard to say what the main problem is in your case, but it is most certainly not something that can be corrected with a call to sched_yield() or pthread_yield(). The only well-defined use for yielding, in Linux, is to allow a different ready thread to preempt the currently CPU-bound running thread at the same prio... |
2,918,414 | 2,918,545 | C++ Templates: Convincing self against code bloat | I have heard about code bloats in context of C++ templates. I know that is not the case with modern C++ compilers. But, I want to construct an example and convince myself.
Lets say we have a class
template< typename T, size_t N >
class Array {
public:
T * data();
private:
T elems_[ N ];
};
template< typena... | You're asking the wrong question - any "bloat" in your example has nothing to do with templates. (the answer to your question, btw, is to take the address of the member function in both modules and you'll see they're the same)
What you really want to ask is, for each template instantiation, does the resulting executabl... |
2,918,579 | 2,918,594 | Read all files inside a folder including files in subfolders using C++ | I want to read all files inside a given folder(path to folder) using FindFirstFile method provide in windows API. Currently I'm only succeeded in reading files inside the given folder. I could not read files inside sub folders. Can anyone help me to do this??
| When you call FindFirstFile/FindNextFile, some of the "files" it returns will actually be directories.
You can check if something is a directory or not by looking at the dwFileAttributes field of the WIN32_FIND_DATA structure that gets returned to you.
If you find one that is a directory, then you can simply call your ... |
2,919,120 | 2,919,187 | How can I call Objective-C code (specifically code from Mac system libraries) from C++/Qt? | Also, what is the difference between a .m and a .mm file? Or is that just some convention that Nokia uses for Qt?
| .m refers to an Objective-C file, whereas .mm is an Objective-C++. I'm not sure whose convention that is.
As for calling Objective-C from C++, this might help:
http://sseyod.blogspot.com/2009/02/objective-c.html
|
2,919,161 | 2,919,189 | what is the Different categories of pointers? | Can any body explains about the different categories of pointer(like wild pointers)?
|
Valid pointer: one pointing to a real object in memory
Invalid pointer: one pointing to memory that is not what it is supposed to be.
NULL pointer: A pointer whose value is 0 and thus points at nothing.
Dangling pointer (also sometimes wild pointer): one pointing to memory that has been deleted/freed.
Smart pointer: N... |
2,919,254 | 2,919,336 | Any tips for how to build a LED system thet will light up to music? | So basically I would like somehow that given an audio file as input (most likely mp3 or I can use some audio engine that will handle other types too) from my computer to control some LED lights so they will be something like an oscilloscope, like the one in winamp.
What would I need to be able to do this? I'm intereste... | Here is a possible approach (high level description):
You could have a simple micro controller (MCU) in a basic circuit with a number of LEDs connected. LED connection circuitry should be easy to find. Most MCU manufacturers will also give a sample test/LED flash circuit in the product datasheet, along with a sample pr... |
2,919,378 | 2,919,398 | How to enable core dump in my Linux C++ program | My program is written in C++. compiled with gcc, using -g3 -O0 -ggdb flags. When it crashes, I want to open its core dump. Does it create core dump file, or I need to do something to enable core dump creation, in the program itself, or on computer where it is executed? Where this file is created, and what is its name?
| You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid... |
2,919,446 | 2,919,474 | What is it in MVVM that makes it particularly appealing for managed WPF and Silverlight but not native C++? |
What is it in WPF and Silverlight that makes MVVM suit them so well?
What is it in C++, or what does C++ lack, that makes MVVM and C++ never be mentioned together?
| MVVM (Model - View - ViewModel) is an adaptation of the MVP (Model -View - Presenter) or MVC (Model - View - Controller) patterns, both of which are very popular design patterns for C++ applications. The main changes to the design pattern are to better support WPF and Silverlight so it isn't so much that WPF suits MVVM... |
2,919,525 | 2,926,820 | CComModule::Unlock(); | I've been trying to determine what this function does, however I cannot seem to find it anywhere under the MSDN documentation of the CComModule class.
Could anyone tell me what it is used for?
| This function is for DllCanUnloadNow() to work properly.
You know that when you call CoCreateInstance() for an in-proc server COM automagically calls LoadLibraryEx() to load the COM server DLL if necessary. But how long is the DLL kept loaded? In fact COM calls DllCanUnloadNow() for every loaded COM server DLL periodic... |
2,919,584 | 2,920,576 | Override number of parameters of pure virtual functions | I have implemented the following interface:
template <typename T>
class Variable
{
public:
Variable (T v) : m_value (v) {}
virtual void Callback () = 0;
private:
T m_value;
};
A proper derived class would be defined like this:
class Derived : public Variable<int>
{
public:
Derived (int v) : Variable<int> (v) {... | This is a problem I ran in a number of times.
This is impossible, and for good reasons, but there are ways to achieve essentially the same thing. Personally, I now use:
struct Base
{
virtual void execute() = 0;
virtual ~Base {}
};
class Derived: public Base
{
public:
Derived(int a, int b): mA(a), mB(b), mR(0) {}... |
2,919,629 | 2,920,327 | Mac OS X linker error in Qt; CoreGraphics & CGWindowListCreate | Here is my .mm file
#include "windowmanagerutils.h"
#ifdef Q_OS_MAC
#import </System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/Headers/CGWindow.h>
QRect WindowManagerUtils::getWindowRect(WId windowId)
{
CFArrayRef windows = CGWindowListCreate(kCGWindowListOptionOnScreenOnl... | The CGWindowListCreate function is part of the Quartz Window Services. The corresponding framework is ApplicationServices which is located under /System/Library/Frameworks/.
So, you can just include <ApplicationServices/ApplicationServices.h> at the top of the file and link with the -framework ApplicationServicesoption... |
2,919,715 | 2,919,910 | Is there such a thing as a C# style extension method in C++? | I'm currently learning C++ and i run into the simple problem of converting an int to a string. I've worked around it using:
string IntToString(int Number)
{
stringstream Stream;
Stream << Number;
return Stream.str();
}
but though it would be more elegant to use something like:
int x = 5;
string y = x.toStr... | I would not derive any class from basic_string/string. This is not recommended and no method in string is virtual, it does not have a virtual destructor (hence deriving could reault in memory leaks)
Make it pretty for yourself:
You could create a static class (class containing only static methods) in order keep it all ... |
2,919,797 | 3,018,771 | Good simple C/C++ FTP and SFTP client library recommendation for embedded Linux | Could anyone recommend FTP / SFTP client C/C++ library for Linux-based embedded system? I know about Curl library but I need something as simple as possible just to download files from FTP / SFTP servers. Is there any recommendation to look for? Yes, SFTP support is critical. Actually I can even sacrifice multi-threadi... | libssh2 is a great lib for SFTP - and it also happens to be the lib that (lib)curl uses for SFTP.
|
2,919,847 | 2,954,691 | Insert MANY key value pairs fast into berkeley db with hash access | i'm trying to build a hash with berkeley db, which shall contain many tuples (approx 18GB of key value pairs), but in all my tests the performance of the insert operations degrades drastically over time. I've written this script to test the performance:
#include<iostream>
#include<db_cxx.h>
#include<ctime>
#define MIL... | You may want to look at the information provided by the db_stat utility and the HASH-specific tuning functions that are available. Please see BDB Reference Guide section on configuring a HASH database.
I would expect you to get 10s of thousands of inserts per second on commodity hardware. What are you experiencing and ... |
2,920,164 | 2,920,254 | c++ container allowing you to sort items by when they where last accessed? | Does such a thing exist? or could anyone please recommend how I could implement such a container?
basically I have a std::map which uses a 64bit integer as its key and a custom datatype as the containing item.
I need to be able to periodically remove items that havent been accessed in a while in the most optimal way. d... | One idea: maintain a std::deque which gets an iterator into your map element pushed to the front whenever accessing the map. You can then easily look at the deque to tell which elements have been used most recently.
Some C++ sketch (void of error checking, the point is to demonstrate that the deque is updated when acce... |
2,920,315 | 2,920,347 | Permutation of array | For example I have this array:
int a[] = new int[]{3,4,6,2,1};
I need list of all permutations such that if one is like this, {3,2,1,4,6}, others must not be the same. I know that if the length of the array is n then there are n! possible combinations. How can this algorithm be written?
Update: thanks, but I need a p... | If you're using C++, you can use std::next_permutation from the <algorithm> header file:
int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
// print a's elements
} while(std::next_permutation(a, a+size));
|
2,920,371 | 2,920,926 | Why my linux signal handler run only once | #include <iostream>
#include <signal.h>
#include <fenv.h>
#include <string.h>
void signal_handler(int sig, siginfo_t *siginfo, void* context)
{
std::cout << " signal_handler " << fetestexcept(FE_ALL_EXCEPT) << std::endl;
throw "exception";
}
void divide() {
float a = 1000., b = 0., c, f = 1e-300;
c = a / ... | I don't think throwing an exception inside a signal handler is good practice. The operating system expects the signal handler to return, because the signal is blocked while the handler for it is called. By throwing an exception you prevent the system from unblocking the signal.
|
2,920,497 | 2,921,709 | Thread-safety of boost RNG | I have a loop which should be nicely parallelized by insering one openmp pragma:
boost::normal_distribution<double> ddist(0, pow(retention, i - 1));
boost::variate_generator<gen &, BOOST_TYPEOF(ddist)> dgen(rng, ddist);
// Diamond
const std::uint_f... | Browsing through the Boost mailing list archives gives:
Boost.Random does not maintain global
state that would need protection from
multi-threading.
Boost.Random is thread-safe as long as
you don't access any given object from
two threads simultaneously. (Accessing
two different objects is ok, as long
as t... |
2,920,592 | 2,920,769 | rect in c or c++ language | Is there a type called rect in C or class Rect in C++ language.
| Write
template<class T>
struct podrect
{
T left;
T top;
T right;
T bottom;
};
template<class T>
struct rect
{
rect() : left(), top(), right(), bottom() {}
rect(T left, T top, T right, T bottom) :
left(left), top(top), right(right), bottom(bottom) {}
template<class Point>
rect(... |
2,920,600 | 2,920,629 | Strange Template error : error C2783: could not deduce template argument | I have created a simple function with 2 diffrernt template arguments t1, t2 and return type t3.
So far no compilation error. But when Itry to call the function from main, I encounter error C2783.
I needed to know If the following code is legally ok? If not how is it fixed?
please help!
template <typename t1, typename ... | There is no way for the compiler to deduce t3 from the function arguments. You need to pass this argument explicitly. Change the order of the parameters to make this possible
template <typename t3, typename t1, typename t2>
t3 adder1 (t1 a , t2 b)
{
return t3(a + b); // use t3 instead of fixed "int" here!... |
2,920,773 | 2,920,799 | What exactly is a variable in C++? | The standard says
A variable is introduced by the declaration of an object. The variable's name denotes the object.
But what does this definition actually mean?
Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects? Or is a variable the name itself?
Or is... | Variables are named objects. The following create objects that are not variables
new int // create one int object
std::string() // create one string object
The following creates one array variable with name "foo" and 5 unnamed (sub-) objects of type "int"
int foo[5];
The following is not a variable in C++03, but has ... |
2,921,002 | 2,921,077 | How do I create a create and execute an SQL command using OleDB directly? | I want to use the OleDB interfaces directly to open a connection to a DB, create a command and executing it (for example using the ICommandText interface).
The main thing I can't find is how to create the connection and the command object and how to connect the object that implements the ICommandText to the connection.... | MSDN has a lot on this. http://msdn.microsoft.com/en-us/library/502e07a7.aspx is a sort of index into it, including several pages of concepts and others of samples. Should get you started.
http://msdn.microsoft.com/en-us/library/8kaf36d4.aspx specifically starts a File, New, Project and gets you connected to the db and... |
2,921,068 | 2,921,150 | Cannot press QPushButton in a simple program | Basically, I want a simple pushButton with a colorful text which when pressed exits the application.
Why cant I press PushButton in this simple program. I am using QT 4.6 on Arch x86_64.
#include <QtGui/QApplication>
#include <QLabel>
#include <QPushButton>
#include<QtGui>
int main(int argc, char *argv[])
{
QAppl... | Beside the use of a button class that will allow you to display rich text, you also need to make sure your connections are correct.
In your example, you're connecting the clicked signal of the button to the clear() slot of the label, which is non-sense.
To exit your app when the button is clicked, you need to close the... |
2,921,349 | 2,922,104 | priority_queue with dynamic priorities | I have a server application which accepts incomming queries and executes them. If there are too many queries they should be queued and if some of the other queries got executed the queued queries should be executed as well. Since I want to pass queries with different priorities I think using a priority_queue would be t... | How many discrete priority values do you want to implement? If their number is small (say, 256 levels), then instead of a single priority queue it makes more sense to have 256 simple queues (this is how priority process schedulers are implemented in some OSes). Initially your events sent with priority 1 are placed on q... |
2,921,775 | 2,921,930 | need a library to get performance counters data under Win CE, c++ code | Under WindowsCE, C++ project, I'd like to get CPU utilization and memory allocation data real time - for logging and troubleshooting. Is there a library or activeX available that i could include in my code and use [without bringing my process to a halt, preferably], anyone knows?
thanks much for any insight!
O.
| If you are running on an arm based system (don't know enough about x86 systems) then you need to calculate cpu load on your own by spawning an idle thread and check how much time it consumes.
You can use the ToolHelpApi (a nice blog post that demonstrates this) to extract more information about processes.
|
2,921,861 | 2,921,884 | Why would MessageBox fail silently? | Does anyone know how MessageBox(...) could fail silently?
MessageBox(g_hMainhWnd, buffer, "Oops!", MB_OK | MB_ICONERROR);
ShellExecute(0, "open", "http://intranet/crash_handler.php", NULL, "", SW_SHOWNORMAL);
For a little context, this code is called inside our own exception handler, which was registered with SetUnha... | Just an idea but maybe g_hMainhWnd is invalid? See if it works when you put NULL for the first parameter.
I would suggest to call GetLastError after the call and write the output to a file. That way you can see what Windows thinks the error is. The MSDN MessageBox documentation mentions that it sets GetLastError for... |
2,921,864 | 2,921,908 | Are 'const' variables precomputed by default in C++? | Suppose I have variables for positions like
const float latitude = 51.+11./60.+33.0461/3600.;
const float longitude = 12.+50./60.+31.9369/3600.;
and use them frequently in the program. Does the compiler precompute that?
(This example should not produce much overhead, but you get the point.)
Bonus point for pointing ou... | I don't believe it is required for the compiler to compute the result of arithmetic constant expressions in general.
The compiler is, however, required to compute the result of an integral constant expression (basically, a constant expression composed only of integers and other values converted to integers) in cases wh... |
2,921,915 | 2,921,949 | Should the name of my classes begin with 'Q' in Qt? | When I first started working with Qt, it was extremely annoying that every class has a name beginning with 'Q', but now I've got used to it.
I'm using Qt Creator, and it highlights code quite well.
However, it only highlights class names beginning with 'Q'. And it highlights everything beginning with 'Q' even if there ... | Personnally, I wouldn't prefix my own classes. As Qt has its own implementation of lots of thing (string, list...) it helps to know what you're using.
The correct way would be to use namespaces. I think that Qt didn't use them because it's quite old. C++ changed a lot lately.
And generally, adapting your naming convent... |
2,922,175 | 2,922,348 | File IO, Handling CRLF | I am writing a program that takes a file and splits it up into multiple small files of a user specified size, then join the multiple small files back again.
the code must work for C and C++
I am compiling with multiple compilers.
I am reading and writing to the files by using the functions fread() and fwrite()
fread()... | #include <stdio.h>
int main() {
FILE * f = fopen( "file.txt", "rb" );
char c;
while( fread( &c, 1, 1, f ) ) {
if ( c == '\r' ) {
printf( "CR\n" );
}
else if ( c == '\n' ) {
printf( "LF\n" );
}
else {
printf( "%c\n" , c );
}... |
2,922,328 | 2,922,563 | Accept templated parameter of stl_container_type<string>::iterator | I have a function where I have a container which holds strings (eg vector<string>, set<string>, list<string>) and, given a start iterator and an end iterator, go through the iterator range processing the strings.
Currently the function is declared like this:
template< typename ContainerIter>
void ProcessStrings(Contai... | You can get close to this with a template template parameter:
template<template<class> class CONTAINER>
void ProcessStrings(CONTAINER<string>&);
This will process a whole container, and give a compile error if it doesn't contain strings.
ProcessStrings(str_vec); // OK
ProcessStrings(so_set); // Error
If you want to w... |
2,922,439 | 2,922,454 | How to interpret binary data as an integer? | The codebase at work contains some code that looks roughly like this:
#define DATA_LENGTH 64
u_int32 SmartKey::SerialNumber()
{
unsigned char data[DATA_LENGTH];
// ... initialized data buffer
return *(u_int32*)data;
}
This code works correctly, but GCC gives the following warning:
warning: dereferencing p... | The warning is because you are violating the strict aliasing rule.
One way to do it correctly would be to copy the bytes from the data buffer into a u_int32 object and return that object:
unsigned char data[DATA_LENGTH];
// ... initialized data buffer
u_int32 i;
assert(sizeof (i) <= DATA_LENGTH);
std::copy(&data[0], &... |
2,922,590 | 2,922,676 | Application settings methods? c++ | I am thinking about adding configurable settings to an application, and I think the easiest ways are an external file or win registry (its a win only app).
Which way would be better?
I was wondering, an user with not enough permissions may not be able to create/write the config file. And in the case of the registry, wo... | As far as I know:
an user with not enough permissions may not be able to create/write the config file
You should be able to make files inside user's "home directory" or "application data" directory, regardless of permissions. Normally those directories should be writeable.
would todays antivirus allow me to add/edit... |
2,922,942 | 2,922,955 | Is it possible to have a function pointer to a template function in c++? | I want to know if it's possible to create a template function and then create a function pointer that points to that template function. Is this possible?
I'm using VS2008.
The following code gets this compile time error:
"cannot convert from 'overloaded-function' to 'int (__cdecl *)(int &,int &)' None of the functions... | Your arguments are wrong. tfunc takes is arguments by const references so your function pointer must do the same;
int (*tfunc_ptr)(const int &, const int &) = &tfunc<int>;
|
2,923,018 | 2,923,060 | Stack STL with 2 params | Im implementing a B-tree in C++,I have a stack which saves pairs . my problem is, how i put in this stack because push only accept 1 argument. thanks
| #include <utility>
// ...
stack<pair<string,string> > s;
s.push(make_pair("roses", "red"));
|
2,923,147 | 2,923,164 | Shared objects (.so) static linking and opening other shared object, is the static library code shared between them? | I have one shared object (a.so) which has statically linked (s.so). b.so also has a static link of s.so.
a.so does a dlopen on b.so , will "s.so" code be shared between the two?
The .so are built on gcc 4.1 on RedHat linux.
The s.so is compiled against a.so and b.so with -Bstatic and --no-whole-archive option.
| Static library code (s.a) is never shared between binaries.
|
2,923,272 | 2,923,290 | How to convert vector to array | How do I convert a std::vector<double> to a double array[]?
| There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
std::vector<double> v;
double* a = &v[0];
|
2,923,287 | 2,923,355 | What is the process of creating an interpreted language? | I want to create a very simple experimental programming language. What are some resources can i check out to get an overview of the process of creating an interpreted language. I will be using c++ to build and compile the interpreter.
| You need to implement both a parser and an interpreter.
There is a great free text book called "Programming Languages: Application and Interpretation" that uses scheme to build increasingly more complex interpreters. It also serves as a great introduction to programming language features.
Check it out here: http://www... |
2,923,303 | 2,923,501 | OpenGL Shader Compile Error | I'm having a bit of a problem with my code for compiling shaders, namely they both register as failed compiles and no log is received.
This is the shader compiling code:
/* Make the shader */
Uint size;
GLchar* file;
loadFileRaw(filePath, file, &size);
const char * pFile = file;
const GLint pSize = size;
newCashe... | In loadFileRaw, you pass char *data by value. Then you assign to it:
data = (char*)malloc(sizeof(char) * (*size + 1));
so your call
loadFileRaw(filePath, file, &size);
does not change the value of file! To change file, pass it in by pointer:
loadFileRaw(filePath, &file, &size);
and then change your function to
bool ... |
2,923,461 | 8,012,205 | How to Determine the Size of MSADO Command Parameters | I am new to MS ADO and trying to understand how to set the size on command parameters as created by the
command.CreateParameter (Name, Type, Direction, Size, Value)
The documentation says the following:
Size Optional. A Long value that
specifies the maximum length for the
parameter value in characters or
bytes.... | 1) size is optional for fixed length parameters, so you can pass vtMissing (comutil.h). BTW, my size (connecting to SQL Server) for adInteger is 4 and type is VT_I4, VT_I2 is size 2 and adSmallInt.
2) That should work, I guess. Remind to take the max width of the parameter as defined in the database, not any table colu... |
2,923,843 | 2,923,900 | Can I use boost library for crossplatform application executing? | Is there any WinAPI WinExec analog in boost (c++) libraries? I need to run executable from my program, and pass parameters to it. Should I use any other cross-platform libraries for this, or handle myself what OS my program is compiled for?
| You might want to take a look at this question regarding popen() on win32: popen
|
2,923,882 | 2,929,797 | Floor function returning EXC_BAD_ACCESS | The cod that I am using contains these snippets of code. I am calling ThetaG_JD with the argument 2455343.50000 which is just a sample Julian date. Every time I run the program, I receive a EXC_BAD_ACCESS on the indicated line. When using gdb and printing out the intermediary values and passing them through the floor f... | The EXC_BAD_ACCESS is somewhat puzzling to me, but this sounds suspiciously like a floating point exception. It's been a while, but as I recall on x87 hardware, you could generate overflow/underflow/NaN and the processor wouldn't let you know with an exception until the next FP operation which could be in a totally dif... |
2,924,037 | 2,924,106 | Separate "include" and "src" folders for application-level code? | This questions concerns mostly Unix/Linux style C++ development. I see that many C++ libraries store their header files in a "include" folder and source files in an "src" folder. For the sake of conformance I adopted this in my own code. But it is not clear to me whether this should be done for application code as well... | I also separate them, but not strictly on the extension, but on the access of the file.
Suppose you have a module that manages customer information and uses 2 classes to do this: Customer, CustomerValidityChecker.
Also suppose that other parts in your application only need to know about the Customer class, and that the... |
2,924,058 | 2,924,154 | Confused about std::runtime_error vs. std::logic_error | I recently saw that the boost program_options library throws a logic_error if the command-line input was un-parsable. That challenged my assumptions about logic_error vs. runtime_error.
I assumed that logic errors (logic_error and its derived classes) were problems that resulted from internal failures to adhere to p... | In this case, I think (at least for the most part) you're right and it's wrong. The standard describes logic_error as:
The class logic_error defines the type of objects thrown as exceptions to report errors presumably detectable before the program executes, such as violations of logical preconditions or class invarian... |
2,924,134 | 2,924,159 | Copy constructor bug | I'm writing a simple nD-vector class, but am encountering a strange bug. I've stripped out the class to the bare minimum that still reproduces the bug:
#include <iostream>
using namespace std;
template<unsigned int size> class nvector
{
public:
nvector() {data_ = new double[size];}
~nvector() {delete[] data_;}
... | Templated implementation of conversion-constructor is never considered as a candidate function for a copy-constructor. Your templated copy-constructor is never called. Instead, the compiler uses an implicitly generated "default" copy-constructor implementation, which performs shallow copying with obvious consequences.
... |
2,924,238 | 2,924,289 | how to open a file in user's home folder | i'd like to put a kind of lock file in the user's home directory on linux(from c++) but fopen'ing ~/.fluudit doesn't seem to work.
fopen("~/.fluudit","w"); //fails
| You can use the environment variable HOME and if that's not present, you can use the password database:
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
|
2,924,240 | 2,924,274 | C++ - How could I do some operation on bmp file? | I am interesting to do some transformation, like change one color to another, count all used colors, and resize image. I DO NOT want to use any exist library, I would like write myslelf all code.
Summing up: How could I open BMP file and change it?
| I would start with reading some documentation. Maybe go to Wikipedia for an overview.
|
2,924,409 | 2,924,832 | Manually bring up tooltip? (WinAPI) | I've been reading about how tooltips work and it seems like I need to register each tool to the window. My issue is, I have a custom color wheel and I want it to show the tooltip for the RGB, HSV etc of that color which means I won't be registering multiple tools. From the looks of it, the tooltip works with a string r... | No, a string resource is not needed, you can also set TOOLINFO.lpszText to a pointer to a regular string. Consider your usage, you probably want to use TTM_TRACKACTIVATE and TTM_TRACKPOSITION.
Beware that this isn't really appropriate use of tool tips. You'll fight the timeout. Once it trips, you can't get the tip b... |
2,924,419 | 2,924,887 | Wierdness debugging Visual Studio C++ 2008 | I have a legacy C++ app, that in its most incarnation we've been building with makefiles and VS2003's command-line tool. I'm trying to get it to build using VS2008 and MsBuild. The build is working OK, but I'm getting errors where I'd never seen errors, before, and stepping through in VS2008's debugger only confuses ... | This is a common mishap when you mix and match code that was built with different versions of the CRT header files. Lots of changes between 2003 and 2008. STL iterator debugging for example. The RTC feature (Run-Time Error Checks) would be another, that's the source of the 0xcccccccc value you see. It means "uninit... |
2,924,673 | 2,924,705 | Template function in define | I have some template function and I want to call it using define in C++:
#define CONFIG(key, type, def) getValue<type>(key, def);
Of course, it won't work. Could I make something like this?
| It works fine:
template<typename T>
T getValue( int, int ) { return T(); }
#define CONFIG(key, type, def) getValue<type>(key, def);
int main()
{
CONFIG(1, int, 2);
return 0;
}
|
2,924,901 | 2,924,976 | How do i use 'auto' in C++ (C++0x)? | What do i have to do to this code to make it compile, it's braking around this line:
auto val = what.getObject();
#include<iostream>
using namespace std;
class CUP{
public:
void whatsHappening(){}
};
class MUG{
public:
void whatsHappening(){}
};
class CupThrower{
public:
CUP cp;
... | Auto isn't supported in VS2008. Use VS2010 and later versions, or another compiler supporting this feature.
|
2,925,106 | 2,925,199 | How does c++ (c++0x) handle implicitly typed variables? | I am trying to learn how to use implicitly typed variables in c++.
Should i be using 'auto' from C++0x? If so how?
Can some one provide me with a simple example or a good tutorial on this?
Thank you.
| auto x = f();
The type of x will be whatever f() returns.
|
2,925,129 | 2,925,252 | Initialized Variables lose Values after Function Call | Question says it all, really. I'm not sure what the problem is. I'm fairly new to classes; my practical experience with them being close to nill, but I have read a fair amount about them.
I have created a class ECard with the following constructor
ECard::ECard( int bankNum, int PIN )
{
m_BankNum = new int;
... | Don't dynamically allocate variables unless necessary
In the Java language, instances of variables are defined using the new operator. This is not necessary in C++.
Change your class declaration to:
struct ECard
{
ECard(unsigned int bankNum,
unsigned int newPIN)
: m_bankNum(bankNum),
m_pin(ne... |
2,925,132 | 2,925,197 | Why is execution-time method resolution faster than compile-time resolution? | At school, we about virtual functions in C++, and how they are resolved (or found, or matched, I don't know what the terminology is -- we're not studying in English) at execution time instead of compile time. The teacher also told us that compile-time resolution is much faster than execution-time (and it would make sen... | Profiling unoptimised code is pretty much meaningless. Use -O2 to produce a meaningful result. Using -O3 may result in even faster code, but it may not generate a realistic outcome unless you compile A::f and B::f separately to main (i.e., in separate compilation units).
Based on the feedback, perhaps even -O2 is too a... |
2,925,167 | 2,933,707 | Qt: How can I access the actual widgets on a page in WebKit? | Is there a way to access the widgets generated by INPUT and SELECT on a page in WebKit, using Qt?
On a related note, does WebKit provide these widgets, or does it delegate back to Qt to generate them?
| Everything inside in QWebView does not use the conventional Qt widget system. It's only HTML, rendered by WebKit. But you can access to html by using the evalJS function. Example of code:
QString Widget::evalJS(const QString &js)
{
QWebFrame *frame = ui->webView->page()->mainFrame();
return frame->evaluate... |
2,925,268 | 2,925,294 | TinyXML and fetching values | I'm trying to load data from xml-file with TinyXML (c++).
int height = rootElem->attrib<int>("height", 480);
rootElem is a root element of loaded xml-file. I want to load height value from it (integer). But I have a wrapper function for this stuff:
template<typename T>
T getValue(const string &key, const string &defa... | The reason is you are calling the int version of TiXmlElement::attrib, but you are giving it a defualtValue of type const std::string &, however, the function expects a defaultValue of type int.
|
2,925,279 | 3,066,267 | IWebBrowser2: how to force links to open in new window? | The MSDN documentation on WebBrowser Customization explains how to prevent new windows from being opened and how to cancel navigation. In my case, my application is hosting an IWebBrowser2 but I don't want the user to navigate to new pages within my app. Instead, I'd like to open all links in a new IE window. The desir... | What I ended up doing was using IHTMLDocument directly rather than IWebBrowser. IWebBrowser is a superset of IHTMLDocument, and the navigation model implemented by IWebBrowser isn't customizable to the degree I wanted.
I actually got MS Developer Support involved and this approach was their recommendation. They say thi... |
2,925,352 | 2,925,373 | C++ STL: Trouble with iterators | I'm having a beginner problem:
bool _isPalindrome(const string& str)
{
return _isPalindrome(str.begin(), str.end()); // won't compile
}
bool _isPalindrome(string::iterator begin, string::iterator end)
{
return begin == end || *begin == *end && _isPalindrome(++begin, --end);
}
What am I doing wrong here? Why d... | Assuming that you have a declaration of the second function before the first function, the main issue is that you are passing the strings by const reference.
This means that the only overloads of begin() and end() that you have access to are the const versions which return std::string::const_iterator and not std::strin... |
2,925,601 | 2,925,621 | Can I use #undef this way? | I want to get some settings I store in the registry, and if they differ from a #define I want to redefine it, could I do it this way?:
#define DEFINED_X "testSetting"
void LoadConfig()
{
regConfigX = some value previusly stored in the registry;
if(regConfigX!=DEFINED_X)
{
#undef DEFINED_X
#... | No, use a static variable to store the value of DEFINED_X.
|
2,925,614 | 2,925,697 | C++ STL: Trouble with string iterators | I'm making a simple command line Hangman game.
void Hangman::printStatus()
{
cout << "Lives remaining: " << livesRemaining << endl;
cout << getFormattedAnswer() << endl;
}
string Hangman::getFormattedAnswer()
{
return getFormattedAnswerFrom(correctAnswer.begin(), correctAnswer.end());
}
string Hangman::ge... | The problem is in the evaluation of:
displayChar(*begin) + getFormattedAnswerFrom(++begin, end)
In executing this statement, it is evident that your compiler is first incrementing begin, returning the "next" begin for use as the first argument to getFormattedAnswerFrom, and then dereferencing begin for the argument to... |
2,925,726 | 4,163,102 | Win32 DLL importing issues (DllMain) | I have a native DLL that is a plug-in to a different application (one that I have essentially zero control of). Everything works just great until I link with an additional .lib file (links my DLL to another DLL named ABQSMABasCoreUtils.dll). This file contains some additional API from the parent application that I woul... | I just had exactly the same problem. This is an issue with the Abaqus API rather than with the loading of DLLS.
I think it is because the Abaqus API overrides the new and delete functions (as you seem to have noticed). If you call new or delete in your program before initializing the Abaqus API, such as by calling odb_... |
2,925,881 | 2,925,962 | how a thread can signal when it's finished? | #include <iostream>
#include <boost/thread.hpp>
using std::endl; using std::cout;
using namespace boost;
mutex running_mutex;
struct dostuff
{
volatile bool running;
dostuff() : running(true) {}
void operator()(int x)
{
cout << "dostuff beginning " << x << endl;
this_thread::sleep(pos... | The problem in this example is that there are two instances of dostuff, so the version being set to false in operator() is different then the one in main.
From the thread management documentation:
A new thread is launched by passing an object of a callable type that can be invoked with no parameters to the constructor... |
2,926,034 | 2,926,112 | Include pdbs in installer? | Is there any reason to not include pdb files in an installer? I have C++ logging functionality that walks the stack, and reports line numbers and file names. It would be great if my customers could send me logs with this information. However, they would need the pdb files. Is there any downside (other than installer pa... | Two possible downsides:
The PDB file might make it easier for someone to reverse-engineer your application.
As a result of the previous, someone might come to expect to be able to call undocumented functions in your DLLs.
If those don't bother you, I can't see any downside. Note though that you don't really need this... |
2,926,037 | 2,926,052 | Creating a "mountable" File System, where to start? | A friend and I are thinking about creating a simple file system for learning purposes. We're going to write it in C/C++, and try to get it to a mountable state from within linux. We've both been coding or over 16 years (32 combined), so I suppose its just a matter of finding some documentation, and a ton of learning.... | I don't have much experience with this, but FUSE ("Filesystem in Userspace") seems to be the way to go - see http://fuse.sourceforge.net, http://en.wikipedia.org/wiki/Filesystem_in_Userspace
|
2,926,066 | 2,926,085 | In C or C++, is there a way to extend a class without inheritance? | Is there a way to implement functionality like Class Categories (of Objective-C) or Extension Methods (of C# 3.0) in C and/or C++?
| With regard to C#'s extension methods: Not directly. C++ has less need for these things because C++ supports free functions. I've never used Objective-C so I can't comment there.
|
2,926,138 | 2,926,163 | Enums, Constructor overloads with similar conversions | Why does VisualC++ (2008) get confused 'C2666: 2 overloads have similar conversions' when I specify an enum as the second parameter, but not when I define a bool type?
Shouldn't type matching already rule out the second constructor because it is of a 'basic_string' type?
#include <string>
using namespace std;
enum EM... | The reason for the ambiguity is that one candidate function is better than another candidate function only if none of its parameters are a worse match than the parameters of the other.
The problem is that the string literal, which has a type of const char[5] is convertible to both std::string (via a converting construc... |
2,926,319 | 2,926,345 | When does a const return type interfere with template instantiation? | From Herb Sutter's GotW #6
Return-by-value should normally be const for non-builtin return types. ...
Note: Lakos (pg. 618) argues against returning const value,
and notes that it is redundant for builtins anyway
(for example, returning "const int"), which he notes may
interfere with template instantiation.
W... | Here's a simple example involving function pointers:
const int f_const(int) { return 42; }
int f(int) { return 42; }
template <typename T>
void g(T(*)(T))
{
return;
}
int main()
{
g(&f_const); // doesn't work: function has type "const int (*)(int)"
g(&f); // works: function has type "int (*)(int)"
... |
2,926,413 | 2,926,423 | Win32 select/poll/eof/ANYTHING? | Using the standard Win32 file I/O API's (CreateFile/ReadFile/etc), I'm trying to wait for a file to become readable, or for an exception to occur on the file. If Windows had any decent POSIX support, I could just do:
select(file_count, files_waiting_for_read, NULL, files_waiting_for_excpt, NULL, NULL);
And select wil... | Windows has a completely different architecture for asynchronous I/O. You will need to use overlapped I/O with or without the related I/O completion ports.
Note that the standard Winsock interface does have a POSIX-like select() function, but that only works with network sockets.
|
2,926,454 | 3,457,224 | Embeddable unit testing framework for mixed Windows app | I want to test portions of a very complex app which includes both a major native Windows component and a substantial WPF GUI. Due to complexities I can't detail, it is impossible to run the native portion independently nor can I isolate the areas I want to test (spare me the lectures, we're talking a huge legacy code b... | The answer is C++/CLI.
You can use managed code test frameworks such as mbUnit, NUnit and xUnit.Net with C++/CLI code and they work fine. The contents of the tests then call native functions from the native libraries.
There are two minor gotchas:
There's a bug in xUnit.Net that prevents their InlineData attribute bein... |
2,926,640 | 2,931,360 | Why is T() = T() allowed? | I believe the expression T() creates an rvalue (by the Standard). However, the following code compiles (at least on gcc4.0):
class T {};
int main()
{
T() = T();
}
I know technically this is possible because member functions can be invoked on temporaries and the above is just invoking the operator= on the rvalue ... | This is why several classes in the Standard library can be implemented. Consider for example std::bitset<>::operator[]
// bit reference:
class reference {
friend class bitset;
reference();
public:
˜reference();
reference& operator=(bool x); // for b[i] = x;
reference& operator=(const reference&); //... |
2,926,878 | 2,926,917 | Determine if a string contains only alphanumeric characters (or a space) | I am writing a function that determines whether a string contains only alphanumeric characters and spaces. I am effectively testing whether it matches the regular expression ^[[:alnum:] ]+$ but without using regular expressions. This is what I have so far:
#include <algorithm>
static inline bool is_not_alnum_space(cha... | Looks good to me, but you can use isalnum(c) instead of isalpha and isdigit.
|
2,927,036 | 2,927,155 | Does operator precedence in C++ differ for pointers and iterators? | The code below demonstrates this difference:
#include <iostream>
#include <string>
int main()
{
char s[] = "ABCD";
std::string str(s);
char *p = s;
while(*p) {
*p++ = tolower(*p); // <-- incr after assignment
}
std::cout << s << std::endl;
... | The problem is that the order of evaluation of arguments of operator= is unspecified. This is according to C++ Standard 5.2.2/8. Consider the following:
*it++ = tolower(*it);
is equal to
operator=( *it++, tolower(*it) );
Now *it++ could be computed before tolower(*it) and vice versa.
|
2,927,109 | 2,927,182 | Strange overloading rules in C++ | I'm trying to compile this code with GCC 4.5.0:
#include <algorithm>
#include <vector>
template <typename T> void sort(T, T) {}
int main()
{
std::vector<int> v;
sort(v.begin(), v.end());
}
But it doesn't seem to work:
$ g++ -c nm.cpp
nm.cpp: In function ‘int main()’:
nm.cpp:9:28: error: call of overloaded ‘s... | You can explicitly specify your sort function by fully qualifying the name as ::sort.
The ambiguous overload is due to argument dependent lookup. The C++ standard doesn't specify how std::vector<*>::iterator should be implemented. The gcc library writers have chosen to use a template (__gnu_cxx::__normal_iterator) with... |
2,927,120 | 2,928,623 | Profiler for IAR EW for ARM | I am trying to get the profiler plug-in for IAR Embedded Workbench for ARM to work. I have set everything in the documentation but when I fire up C-Spy and start the plug-in I get errors. I tried to different emulators and each gave a different error:
Segger SAM-ICE JTAG Emulator - The following appears in the debug lo... | I think there's a better way. Use the GDB Server and use this technique.
|
2,927,136 | 2,927,717 | Developing a sector based partition copying program? | I want to develop a program that copies a partition's 'data' only, to another partition. And I want to do it such that the program starts from the first sector of source partition and checks if a sector is used.
If it is used
copy it to the destination parition.
Else
don't copy.
In other words it's like cop... | Your question is fundamentally flawed. NTS can store data and metadata in the same cluster. Both are handled as file attributes.
I'm also wondering what the point is. Without the metadata, raw data is useless. You can't even tell where one file ends and another begins.
|
2,927,165 | 2,927,322 | Confused about definition of a 'median' when constructing a kd-Tree | Im trying to build a kd-tree for searching through a set of points, but am getting confused about the use of 'median' in the wikipedia article. For ease of use, the wikipedia article states the pseudo-code of kd-tree construction as:
function kdtree (list of points pointList, int depth)
{
if pointList is empty
... | It appears to me that you understand the meaning of median, but you are confused with something else. What do you mean be distinct set of points?
The code presented by Wikipedia is a recursive function. You have a set of points, so you create a root node and choose a median of the set. Then you call the function recur... |
2,927,250 | 2,927,407 | How to write a flexible modular program with good interaction possibilities between modules? | I went through answers on similar topics here on SO but could't find a satisfying answer. Since i know this is a rather large topic, i will try to be more specific.
I want to write a program which processes files. The processing is nontrivial, so the best way is to split different phases into standalone modules which t... | This looks very similar to a plugin architecture. I recommend to start with a (informal) data flow chart to identify:
how these blocks process data
what data needs to be transferred
what results come back from one block to another (data/error codes/ exceptions)
With these Information you can start to build generic in... |
2,927,444 | 2,927,492 | sending data packet just before closing socket | Before disconnect the client, the server wants to send some info to the client - why do I(server) disconnect you(client).
If I send packet to the info and close the client socket immediately, closesocket() returns -1 and if I use linger option to work closesocket() successfully, the info cannot be sent completely.
How... | try to call shutdown() on socket first.
http://msdn.microsoft.com/en-us/library/ms740481%28VS.85%29.aspx
http://www.opengroup.org/onlinepubs/000095399/functions/shutdown.html
|
2,927,448 | 2,927,527 | Sleep Function Error In C | I have a file of data Dump, in with different timestamped data available, I get the time from timestamp and sleep my c thread for that time. But the problem is that The actual time difference is 10 second and the data which I receive at the receiving end is almost 14, 15 second delay. I am using window OS. Kindly guide... | If I understand well:
you have a thread that send data (through network ? what is the source of data ?)
you slow down sending rythm using sleep
the received data (at the other end of network) can be delayed much more (15 s instead of 10s)
If the above describe what you are doing, your design has several flaws:
sleep... |
2,927,914 | 2,928,313 | Generation of .tlb Files in Windows 7 Pro 32-bit | I have a C++ DLL that imports a .tlb file generated in a C# project. The C++ DLL is a wrapper DLL containing functions that call the corresponding C# functions.
When I call the C++ functions on the computer that I built the projects, all works well. But when I copy the DLL's and generated tlb's to another computer with... | The HRESULT you get would be crucial to diagnose this. Forced to guess: did you run Regasm.exe on that machine? Required to make the necessary registry entries so COM can find the server. It is automatic when you build in the IDE.
|
2,928,036 | 2,928,139 | Makefile issue with compiling a C++ program | I recently got MySQL compiled and working on Cygwin, and got a simple test example from online to verify that it worked. The test example compiled and ran successfully.
However, when incorporating MySQL in a hobby project of mine it isn't compiling which I believe is due to how the Makefile is setup, I have no experien... | Try changing
$(COMPILER) -o $(MUD_EXE) $(L_FLAGS) $(O_FILES)
to
$(COMPILER) -o $(MUD_EXE) $(O_FILES) $(L_FLAGS)
The linker searches and processes libraries and object files in the order they are specified. Thus when you mention the libraries before the object files, the functions used in the object files may not be l... |
2,928,158 | 2,928,768 | How can I load scripts, styles and images from a non-URL source? | I am integrating WebKit (via Qt) into an application. Instead of having WebKit retrieve scripts, CSS files and images via URLs, I want my application to provide them (e.g. retrieved from a database).
For example, a "regular" web page may contain this tag:
<IMG src="photos/album1/123456.jpg">
Instead of WebKit fetchi... | Maybe this is a bit overkill, but maybe it could work for you.
Simply have your application act as a HTTP server. Then you could have paths like this:
<IMG src="http://localhost:73617/photos/album1/123456.jpg">
Where 73617 is a random port, you can have your application listen on another port. Then, when your app retr... |
2,928,409 | 2,928,761 | boost::filesystem::path(std::wstring) throw exception | this code:
boost::filesystem::is_directory("/usr/include");
work fine.
both this code:
boost::filesystem::is_directory(L"/usr/include");
throw an exception:
terminate called after throwing an
instance of 'std::runtime_error'
what():
locale::facet::_S_create_c_locale name
not valid
OS - Linux Mint
boost-1.4... |
Don't use wide strings on Linux. You don't need them..
What happens that it tries to convert wide string to normal one and for this
creates a locale and probably this locale is not configured in your system.
Bring output of commands:
locale
locale -a
GCC-4.6 wasn't released yet ;-), check if this works with ordinary... |
2,928,713 | 2,930,443 | Out of Process COM Server - function calls and threads | When you have an out of process COM Server and you call a function from a Client inside this server from Thread X inside the client, then how this function get executed in the COM Server?
In the thread its currently executing on, or on its main thread?
| Normal COM apartment threading rules are observed. If the object was created by the client in an STA apartment then your client thread need to use a marshaled interface pointer or it gets RPC_E_WRONG_THREAD. The actual method call will execute on the server in its STA thread, it needs to pump a message loop for that ... |
2,928,715 | 2,928,779 | Function should return reference or object? | Let's discuss these two functions:
complex& operator+=(const T& val);
complex operator+(const T& val);
Where "complex" is a name of a class that implements for example complex variable.
So first operator returnes reference in order to be possible to write a+=b+=c ( which is equivalent to b=b+c; a=a+b;).
Second operat... | In 1, a+=b, the += operator modifies a. Therefore it can return a reference to itself, because a itself is the correct result of the operation.
However, in 2. a new object is required because a+b returns something that is not a, so returning a reference to a wouldn't be correct.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.