question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
6,882,561
6,882,643
Are begin(container) and end(container) standardized?
Are the non-member function templates begin(container) and end(container) part of C++0x? If so, in which header file do they live?
Yes, but just as swap is defined in different places and depends on ADL, so are begin and end. The 'generic' versions are defined in <iterator>: // 24.6.5, range access: template <class C> auto begin(C& c) -> decltype(c.begin()); template <class C> auto begin(const C& c) -> decltype(c.begin()); template <class C> auto ...
6,882,661
6,901,393
Limit physical memory per process
I am writing an algorithm to perform some external memory computations, i.e. where your input data does not fit into main memory and you have to consider the I/O complexity. Since for my tests I do not always want to use real inputs I want to limit the amount of memory available to my process. What I have found is, tha...
You can try with 'cgroups'. To use them type the following commands, as root. # mkdir /dev/cgroups # mount -t cgroup -omemory memory /dev/cgroups # mkdir /dev/cgroups/test # echo 10000000 > /dev/cgroups/test/memory.limit_in_bytes # echo 12000000 > /dev/cgroups/test/memory.memsw.limit_in_bytes # echo <PID> > /dev/cgroup...
6,882,753
6,882,846
Using long data inside signal handler.
How can I set a variable of type long (on 64 bit machine = 8 bytes) inside a signal handler? I've read that you can only use variables of type sig_atomic_t, which is actually implemented as volatile int inside a signal handler and it is unsafe to modify data types bigger than an int.
You can use a long inside a signal handler, you can use anything, in fact. The only thing you should take care of is proper synchronization in order to avoid race conditions. sig_atomic_t should be used for variables shared between the signal handler and the rest of the code. Any variable "private" to the signal handle...
6,882,799
6,882,816
Does clearing a vector affect its capacity?
I instantiate an std::vector foo(1000). foo.size() is now 1000 and foo.capacity() is also 1000. If I clear the vector with foo.clear(), the size() is now 0, but what is the capacity()? Does the standard say anything about that?
No, it doesn't. The capacity of a vector never decreases. That isn't mandated by the standard but it's so both in standard library implementations of VC++ and g++. In order to set the capacity just enough to fit the size, use the famous swap trick vector<T>().swap(foo); In C++11 standard, you can do it more explicitly...
6,882,817
17,909,143
Building static C++ lib for use with Objective-c app in Xcode 4
I found examples and posts to Create a static C++ lib for use in a C++ application Create a static Objective C lib for use in an Objective C app. What I couldn't find and have hassled around with for days now, is the correct way to create a static C++ lib for use in a Objective-C app under XCode 4. I just want to us...
Answered in my own comment ;) the point was to include the std++ lib into the compiling of the resulting objective-c project, too.
6,882,944
6,885,588
Track a file [C++ or Python]
How can I "track" a file using C++, or Python (I'm guessing C++ will be way more powerfull. Just putting Python in there in case there is a way with it, which would be simpler than C++). When I mean track, I mean registering any moving of the file to a different path, changes in name, etc. Changes in the actual content...
(migrated from comment) You can do that using launchd on OS X. Check out: Is there a command like "watch" or "inotifywait" on the Mac?
6,882,985
6,883,102
Qt attaching itemChanged signal to QStandardItem doesn't work
I'm using qtreeview trying to find out when ever the check box state changes, but the SLOT method never fires. Here is my code: // in the init connect(ui.treeView_mainwindow, SIGNAL(itemChanged( const QModelIndex &)), this, SLOT(tree_itemChanged( const QModelIndex &))); // this method never trigere...
QTreeView doesn't have an itemChanged signal, so your QObject::connect call will fail. This is a good example of why you should always check the return value from QObject::connect. Also, the failed connection would have appeared in your debug output, which you should also be monitoring. Possibly you're looking for QTre...
6,883,032
6,883,057
Do I need to use delete after pthread_mutex_destroy
Suppose I use pthread_mutex_t *m = new pthread_mutex_t; pthread_mutex_init(m, NULL); to initialize a mutex. Then after I'm done, and invoke pthread_mutex_destroy, do I need to use delete m; to release all resources?
You need to free the memory, as pthread_mutex_destroy can't do it for you. Why doesn't pthread_mutex_destroy free the memory for you ? Because you are allowed to do this: pthread_mutex_t m; pthread_mutex_init(&m, NULL); pthread_mutex_destroy(&m); /* Can't free &m. */ You can try it using valgrind: ==836== LEAK SUMMAR...
6,883,055
6,896,104
What is wrong with this makefile
At the top of my makefile I have the following. USE_44 = 0 ifeq($(USE_44), 0) CXX = g++ else CXX = g++44 endif But I get the error makefile:2: *** missing separator. Stop. what wrong am I doing here?
GNU make has a very useful yet often overlooked feature called computed variable names. Using this feature allows to avoid conditionals and make the code shorter and more readable: USE_44 := 0 cxx.0 := g++ cxx.1 := g++44 CXX := ${cxx.${USE_44}} Normally though, you want to accept the compiler name from the user and s...
6,883,128
6,883,145
Qt Custom Widget Size
I am writing a custom widget with qt. I was wondering if there was a way that I could hard code the width of the widget so it will always remain that size? Thanks
widget->SetFixedWidth(myWidth); widget->SetFixedHeight(myHeight); widget->SetFixedSize(mySize);
6,883,162
8,728,748
Eclipse CDT: Change Annotation icons on that left bar D: ?
Hoi. I love Eclipse. But i hate that huge square annotation on the left, popping up every two seconds: How can i change it? Been able to get rid of it, but I'd like something else than nothing. (hate squares)
Right click on it -> General -> Editors -> Text Editors -> Annotations. Here you can configure which icons and where to show.
6,883,258
6,885,567
Preventing newline when pressing enter in WxWidgets text control
I am writing an application with WxWidgets, and have run into an issue with a multiline text control (wxTextControl). It is the input field in a chat window, and it needs to be multi line in case the user types a longer message that needs to wrap. I want the send event, e.g. the action that is taken when the Send butto...
You might track wxEVT_COMMAND_TEXT_UPDATED and clear the editor when a new-line is entered (it assumes you are also clearing the editor when Enter is pressed). BEGIN_EVENT_TABLE(Test,wxFrame) EVT_TEXT_ENTER(EditorID, Test::OnEnter) EVT_TEXT(EditorId, Test::OnText) END_EVENT_TABLE() void Test::OnEnter(wxCommand...
6,883,276
6,883,743
What is the difference between "Include Directories" and "Additional Include Directories"
In configuration properties of my project, under the "VC++ directories" there is an entry for "Include Directories". But under "C/C++" option, there is another entry called "Additional Include Directories". Same thing happens with library directories. What are the difference between these two entries?
This is awkwardness that got introduced in VS2010. The VC++ Directories settings used to be located in Tools + Options, Projects and Solutions, VC++ Directories. Global settings that applied to every project that was built on the machine. It is still there but points out that you should now change it in your project...
6,883,325
6,883,397
Is there any library to determine whether a numerical value can be translated to a valid, printable, and meaningful character in a specific charset?
I hope there is any library out there that provides such functionality so that I do not need to dig too much on charset specification. C++, and hopefully Chinese, and hopefully Windows.
Yes, ICU is a mature library providing Unicode and Globalization support. Among other things it provides easy access to all of the many Unicode character properties, Unicode Normalization, Case Folding and other fundamental operations as specified by the Unicode Standard.
6,883,502
6,883,575
How can I implement the observer design pattern streaming data in C++?
I would like to send data from a server to a client, continuously (streaming), without the need for the client to continuously loop through and check for any data. I think I am right in believing this is the observer design pattern? How is this possible? Could someone provide me with a list of things I can google? How ...
The observer design pattern is slightly different from what you're describing: Note that each observer gets notified by the "observable" object; so if you have a server that's continuously streaming data, then would you expect the server to "notify" you and what would you expect the server to notify you of? Every pack...
6,883,547
6,883,640
How can a function execute an action after recursing?
I know that recursion is a technique to call a function within the function itself. but the below code confuses me on how it is able to do the cout part after the first recursion: (This code solves the tower of hanoi puzzle) #include <iostream> using namespace std; void move_rings(int n, int src, int dest, int other);...
Recursion can be a bit tough to grasp at first. It "clicked" for me when I thought about it like this: you have a base case, which is the condition that will lead the recursive function not to call itself anymore, and then you have the other part ("else" in your code), where the function will continue to be called. The...
6,883,562
6,883,603
The fastest solution to port the php function addslashes to c++
string addslashes ( string $str ) Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte). I'm working on a c++ equivalent of this php function. Right now my function uses...
Go over the string in a single pass (for loop) and switch on each character. When encountering a character that needs escaping, push a backslash into the output buffer Push current character into the output buffer. Use a std::ostringstream for the output buffer. This is very efficient (single pass, buffered output) a...
6,883,592
6,883,652
Add element to pointer array
I have a pointer array of a custom Vector typedef (just 3 floats). I'm writing a Wavefront object loader and I want to be able to add to an array of these vectors whenever a vertex row in the file is encountered. My problem at the moment is allocating memory for the new vector. Vector typedef struct { float x; ...
You are allocating space for exactly one Vector struct. sizeof(vertices) will be the size of a pointer on your machine and is absolutely meaningless here. sscanf(line, "v %f %f %f", &(verticies->x), &(verticies->y), &(verticies->z)); is going to do what you need. But this only enabling you to read in a single Vector....
6,883,880
6,883,919
winsock errors visual studio
I want to write an app which uses libcurl, I added the lib and without writing any code trying to compile it, it gives me some compiler errors Fehler 79 error C2375: 'WSAAsyncSelect': Neudefinition; unterschiedliche Bindung C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\winsock2.h 2461 Fehler 55 error C2...
Refer to this post Hope this helps.
6,883,892
6,883,946
how to define a functor inside a function
Sometimes, I need some functor-helper to manipulate list. I try to keep the scope as local as possible. #include <iostream> #include <algorithm> using namespace std; int main() { struct Square { int operator()(int x) { return x*x; } }; int a[5] = {0, 1, 2, 3, 4}; ...
You cannot do it. However, in some cases, you can use boost::bind or boost::lambda libraries to build functors without declaring an outside structure. Also, if you have a recent compiler (such as gcc version 4.5) you can enable the new C++0x features which allow you to use lambda expressions, allowing such syntax: tran...
6,883,901
6,885,432
Is there a safe bool idiom helper in boost?
25% of programmers work time is spended by checking if the required code already exist. I'm searching for a base class for implementing the safe bool idiom.
bool_testable<> in Boost.Operators looks promising. The reference mentions that: bool_testable provides the antithesis of operator bool, such that the expression if (!p) is valid, whilst also making operator bool safer by preventing accidental conversions to integer types. ... bool_testable<> prevents these acc...
6,884,041
6,890,543
Messaging system: Callbacks can be anything
I'm trying to write an event system for my game. The callbacks that my event manager will store can be both plain functions as well as functors. I also need to be able to compare functions/functors so I know which one I need to disconnect from the event manager. • Initially I tried using boost::function; it handles fun...
No matter, I found the solution. A little template magic and things become simple(r): template<typename F> void EventManager::removeEventHandler(Event::Type evType, F func) { auto compare = [func](const Callback& other) -> bool { F const* f = other.target<F>(); if (f == nullptr) return false; ...
6,884,093
6,884,102
warning C4003: not enough actual parameters for macro 'max' - Visual Studio 2010 C++
I have the following warnings while compiling an openFrameworks 007 project on Visual Studio 2010 SP1: d:\pedro\development\videoflow\openframeworks\libs\openframeworks\types\ofcolor.h(127): warning C4003: not enough actual parameters for macro 'max' d:\pedro\development\videoflow\openframeworks\libs\openframeworks\typ...
Add #undef max to the top of the relevant files.
6,884,285
6,884,316
C++ Opengl render part of an image
Let's say i have a method that get a GLuint texture as a parameter and I'd like to render a part of it. Think about a tile set for instance, i want to be able to load a tile set and render parts (tiles) of it when I load my level. It would be optimal if I somehow would be able to define the height, width, posX and posY...
You do this using glTexCoord function. For example, if you tileset contains 4 tiles, and you want to display the top left corner[*] tile, you would do something like this: glTexCoord2f( 0, 0); glVertex2f( -sizeX,-sizeY); glTexCoord2f( 0.5, 0); glVertex2f(sizeX,-sizeY); glTexCoord2f( 0.5, 0.5); glVertex2f(sizeX,sizeY); ...
6,884,300
6,884,342
How to allow a std:string parameter to be NULL?
I have a function foo(const std::string& str); that it does crash if you call it using foo(NULL). What can I do to prevent it from crashing?
std::string has a constructor that takes a const char* parameter. That's constructor is going to crash when you pass NULL to it, and that constructor is called implicitly when you write foo(NULL). The only solution I can think of is to overload foo void foo(const std::string& str) { // your function } void foo(const...
6,884,359
6,884,552
c++ practical computational complexity of <cmath> SQRT()
What is the difference in CPU cycles (or, in essence, in 'speed') between x /= y; and #include <cmath> x = sqrt(y); EDIT: I know the operations aren't equivalent, I'm just arbitrarily proposing x /= y as a benchmark for x = sqrt(y)
The answer to your question depends on your target platform. Assuming you are using most common x86 cpus, I can give you this link http://instlatx64.atw.hu/ This is a collection of measured instruction latency (How long will it take to CPU to get result after it has argument) and how they are pipelined for many x86 an...
6,884,538
6,884,565
Is there a way to communicate data between computers without while loops? C++
I have been struggling to try and find my answer for this on google, as I dont know the exact terms I am looking to search for. If someone were to build an msn messenger-like program, is it possible to have always-open connections and no while(true) loop? If so, could someone point me in the direction of how this is ac...
Using boost::asio library for socket handling, i think it is possible to define callbacks upon data reception.
6,884,584
6,884,596
C++: member function address (function pointers)
I have a class X which has this method: void setRxHandler(void (*h)(int)); And I want to pass to it a member function that exists in instances of class Y. void comm_rxHandler(int status); I tried the following: x.setRxHandler(comm_rxHandler) But it get the following compile error (I'm using Qt): error: no matching...
As it is now, the setRxHandler prototype takes a pointer to a function that doesn't return anything and takes an int. As you have noticed, this won't work with member functions because they can't be called like a normal function (you have to handle the this pointer as well, which means having an instance of that class ...
6,884,592
6,884,613
c++ classes - conflicting declaration error
I just started learning classes in C++ and I get this error for the code below: conflicting declaration 'std::string PizzaOrder::toppings_offered' Can someone explain what's wrong with my code here? class PizzaOrder { public: //all the toppings that are offered, constant array of strings static string toppin...
You forgot that toppings_offered is an array of strings, rather than a string: string PizzaOrder::toppings_offered[5] = {"onions", ... }; // ^ // | (BTW, I'd expect a pizza order to order toppings, not offer them. Could it be that your design still is ...
6,884,708
6,885,929
Ranking and unranking of permutations with duplicates
I'm reading about permutations and I'm interested in ranking/unranking methods. From the abstract of a paper: A ranking function for the permutations on n symbols assigns a unique integer in the range [0, n! - 1] to each of the n! permutations. The corresponding unranking function is the inverse: given an integer ...
One way is to rank and unrank the choice of indices by a particular group of equal numbers, e.g., def choose(n, k): c = 1 for f in xrange(1, k + 1): c = (c * (n - f + 1)) // f return c def rank_choice(S): k = len(S) r = 0 j = k - 1 for n in S: for i in xrange(j, n): ...
6,884,714
6,884,725
C++ allocating space for objects using inheritance
I've got a question about how a C++ compiler knows how much space it needs to allocate for an object when using inheritance. Imagine the following classes, for an adult and a child which extend a Person class, but where a child has a short book with them. class Person { }; class Adult : public Person { //No book...
How does the compiler know how much space it needs to ensure the array is a contiguous memory block, if it doesn't know whether the array will be filled with Adult or Child The people array cannot contain Adult or Child objects: it can only contain Person objects. When you perform the assignment people[0] = child1;,...
6,884,835
6,884,841
Removing an element from a list with only its iterator
Is it possible to remove an element from an std::list if you have only the iterator that points to the element you want to remove? I have a large amount of functions that take iterators to list elements, and it would be a huge inconvenience to have to pass the owning list to every one of them.
Edit: You cant with a single iterator. If you have the begin/end iterators, you could use the std::remove algorithm to move all the elements you want to erase to the end, and delete them at a later point. If you don't, or the above isn't feasible with your current design, i'd recommend altering your functions to take a...
6,884,945
6,884,988
dereferencing SDL_Surfaces?
is there any way to copy a SDL surface to another, like creating a backup copy, without modifying the original when the copy is modified? *surface = *original_surface dosnt work. SDL_Surface does not have any constructors, so i cant do anything like surface = new SDL_Surface (original_surface). currently, i am opening ...
You can create a new compatible surface: copy = SDL_CreateRGBSurface(flags, width, height, original->format.BitsPerPixel, original->format.Rmask, original->format.Gmask, original->format.Bmask, original->format.Amask); And then blit the original into the copy: SD...
6,884,946
6,885,421
Pagefaults when starting application from Visual Studio
I'm using Visual Studio 2010 to write and debug a small program. The problem is, whenever I start the application through Visual Studio 2010 the process of my application produces page-faults in the range of 100000 per second and that slows down the program by factor 10 or more. When I start the generated executable fr...
Page faults are normal. It's part of the process of allocating memory. This is nothing to worry about.
6,884,960
6,885,500
Qt WindowMaximize not changing geometry (C++)
So I'm making a web browser as my first Qt project (surprise!) and I'm wondering why calling setWindowState(Qt::WindowMaximized) is not changing window geometry. I have this code: From mainwindow.h: namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWin...
I would have to double check, but your geometry might not get updated properly until your main window gets a show event. However, I would suggest you put your QWebView inside of a layout instead of trying to size it manually every time your main window changes size.
6,885,063
6,885,137
Where should I define operator >> for my specialization of std::pair?
Consider the following program: #include <iostream> #include <iterator> #include <vector> #include <utility> using namespace std; //just for convenience, illustration only typedef pair<int, int> point; //this is my specialization of pair. I call it point istream& operator >> (istream & in, point & p) { return in ...
Adding an overload of operator>> in namespace std is forbidden, but adding a template specialization is sometimes allowed. However, there are no user-defined types here, and the operators on standard types are not yours to redefine. Specializing operator>>(istream&, pair<mytype, int>) would be reasonable. section [na...
6,885,125
6,885,179
Unrelated specialization must exist to compile?
The following code (which compiles and executes properly, doing what I want) is a minimal example of an oddity I experienced while writing a class to store properties of various types that needed the ability to delete pointers when it no longer knows their types. My solution was to make a Deleter class with a templated...
This template <class locale> static void Delete(void* ptr) { delete (locale*)ptr; } is not a specialization. This is an overload. A specialization would be like this template <> static void Delete(locale* ptr) { delete (locale*)ptr; } So actually it's equivalent to writing just template <class T> static void...
6,885,177
6,885,202
Trouble with defining my own operator...
I'm just toying around to watch how defining operators work. The following code gives me an error about "No candidate functions found". Any criticism other than that of the root cause is welcome, too. Thanks! #include <iostream> using std::cout; using std::cin; using std::endl; using std::string; class SomeClass {...
const string getStr() { return str; } should be const string& getStr() const { return str; } Otherwise you cannot call a non-const function on a const parameter of SomeClass& operator=(const SomeClass& rh)
6,885,284
6,885,339
How do I use fstream to write to a file above the executable's directory in C++?
I'm trying to write to a file that is not in the directory that the executable is in; I also want it to work no matter where the executable is (I believe that would rule out using ".."). I need this to work on Linux. Thank-you.
A relative path is usually resolved starting from the running directory, which is not necessarily the executable directory (rather the current directory in the shell from which the executable is launched). Under linux, you can read the directory of the executable with: readlink /proc/self/exe or you could use boost fs...
6,885,583
6,885,592
C++ linux time freezes application
I am importing <sys/time.h> and using the struct time_t *start; A class has a member time_t *start; and a member function getETA() : template <class S, class P> double Task<S,P>::getETA() { time_t *stop; time(stop); return difftime(*stop , *start); } Also note that time_t *start is initialized in the class co...
You've to pass a valid pointer to time() function. So why don't you do this: time_t start; time(&start); time_t stop; time(&stop); That is, don't declare start and stop as pointer. Declare them as non-pointer, automatic variables. If you declare them as pointers, then you've to do this: time_t *start = new time_t; t...
6,885,610
6,885,835
Comparing objects returned by Boost.Bind?
Is it possible? The instruction bool b = (boost::bind(func, 1) == boost::bind(func, 1)) does not compile because it "cannot convert from 'boost::_bi::bind_t' to 'bool'". (The signature of func is void func(int).)
Don't know if this is "oficially supported functionality" but bind_t does seem to provide a function_equal method: http://www.boost.org/doc/libs/1_47_0/boost/bind/bind.hpp
6,885,707
6,885,729
Writing classes to be used with unordered_map.
I want to use the boost map and the documentation says I need an equality function and a hash function. I think understand what they should do but since I can't find any examples I'm not sure how to do it so I am looking for a trivial example, like a point class with members x, y or something close. Edit: Finally got i...
Equality and hash aren't too tough to define. Equality: class Point { int x, y; bool operator==(const Point& p) { return (x == p.x && y == p.y); } }; Hashing tends to involve specializing a function or class. template<> class boost::hash<Point> { public: size_t operator()(const Point& p) { ...
6,885,867
6,885,912
Why valarray does not have a swap function like vector in C++03?
As title, I am confused about this. swap should be extremely useful if we are facing an iterative problem. The old vector and the new vector can be swapped by exchanging pointer-to-memory instead of contents. However, this is valid in std::vector but not in std::valarray. I am wondering why. In C++0x it seems the funct...
Because it doesn't. I doubt there is a much better answer than that. Omissions and mistakes happen (see also std::vector::resize taking its second argument by value, the missing std::copy_if algorithm, and the very long list of closed Standard Library defects). It's a good thing that the language continues to evolve a...
6,886,145
6,886,293
IPC between Credential Provider and a system service
What is the best way to communicate with a custom Credential Provider from a system service ? Is it possible to send a message through the message pump ? Can I use named pipes ? Any suggestions would be appreciated.
The credential provider runs in the session of the user, while the system service runs in the system session. As far as I know, this rules out Windows Messages. Messages also requires a window to be created and the process having a message pump, which a service normally doesn't have. I would suggest named pipes. The sy...
6,886,381
6,886,399
Get motherboard deviceID and BIOS serial in Linux
Well, i'm doing a Library (DLL) which lets you get the motherboard deviceID and BIOS Serial in Linux. I have other for Windows, but since i can't (Or i don't know) how to check if Operating System is Windows or Linux. But since i'm Windows user, i don't have idea. So my question is, is possible to get Motherboard devic...
You can find this information in the files in /sys/class/dmi/id. These files are ordinary text files, simply open them and read. Note that not all motherboard BIOSes bother filling in these IDs, but for those mobos that do provide the data, it will be reported there.
6,886,449
6,886,459
Why do C or C++ books not contain anything on networking?
I've just been looking at the following books: -K&R C -The Complete Reference C++ -The Complete Reference C -Deitel How to Program C -Deitel How to Program C++ and not one of them contains any networking, how to create sockets etc. Is there any 'definitive' reference for C network programming? Google wasn't particularl...
"C books" usually describe the language and the standard library. Sockets aren't in the standard library. If you want a good book on sockets, UNP by Stevens is arguably the best.
6,886,553
6,886,585
2D Game Programming for Linux, OSX, and Windows - C++/Python/OpenGL?
A friend of mine is making the jump from graphic designer to game developer, and I have decided to work with him in my free time. Neither of us have much development experience, but I am very interested in learning Python, and my friend wants to learn C++. I have read that C++ is the common denominator in game programm...
There's actually a handy set of libraries and modules for Python, pygame, that is extremely useful, well documented and has a ton of community support and a lot of fun games have been built with it. And the best part, to answer part of your question, is that OpenGL is not required. And, because it's based on Python, it...
6,886,569
6,886,646
Selectively Enable Visual Styles on Dialogs/Windows
I've implemented the use of visual styles on all common controls through the use of a manifest file as directed by this article - http://msdn.microsoft.com/en-us/library/bb773175.aspx. Is there a way to disable the use of visual styles for a particular dialog/window or a control ?
The answer is mentioned on the page you referenced. http://msdn.microsoft.com/en-us/library/bb773175.aspx#turnoff
6,886,750
6,886,785
Declaring a reference to object and the assignment operator
I feel like this question is basic enough to be out there somewhere, but I can't seem to be able to find an answer for it. Suppose I have this code: //class member function std::map< std::string, std::string > myMap; const std::map< std::string, std::string >& bar() { return myMap; } void myFunc( std::map< std::st...
References are not reseatable in C++. This means that once they're initialized, you can't reassign them. Instead, any assignment actually involve the referred object. So in your code, foo1 = bar(); std::map< std::string, std::string >& foo2 = bar(); the first line calls std::map::operator= on the object that was passe...
6,886,918
6,887,047
Cache Hit/Miss for a value in C/C++ Program
This is my requirement, I know that certain algorithms makes good use of Cache, some do not, some do more I/O than others on particular data set, etc. I would like to see and analyze that happening myself. So I was wondering if there was a way I could know how a certain memory/variable is read, i.e. is it from cache, o...
If you really want to know when your caches are hitting/missing, modern processors have performance counters that you can use for exactly this purpose. I have used them extensively for academic research. The easiest way to use them is through perfmon2. Perfmon2 has both a library you can link into your program or a ...
6,886,995
6,911,564
Calling Windows API with libffi on MinGW
I'm trying to have FFI support for my new programming language, which is written in C++ with QT Creator using the MinGW toolchain. To do this I used a custom-built version of libffi found here: http://ftp.gnome.org/pub/GNOME/binaries/win32/dependencies/libffi-dev_3.0.6-1_win32.zip I also tried it with another build: ht...
you should pass the address to the values array instead of the values. the working code under mingw64 is #include <stdio.h> #include <ffi.h> #include <Windows.h> int main() { ffi_cif cif; HINSTANCE dllHandle = LoadLibrary("user32.dll"); int n = 4; ffi_type ...
6,887,024
6,887,089
Initializing and maintaining structs of structs
I’m writing C++ code to deal with a bunch of histograms that are populated from laboratory measurements. I’m running into problems when I try to organize things better, and I think my problems come from mishandling pointers and/or structs. My original design looked something like this: // the following are member varia...
Are you sure that Histogram *SomeHistograms[4] initialized the data? How do you populate the Histogram structs? The problem here is not the structs so much as the pointers that are tripping you up. When you do this: MeasurementSet ms; it declares an 'automatic variable' of type MeasurementSet. What it means is that all...
6,887,330
6,887,342
C++: What's wrong on int *j; *j=50; ?
This is a newbie C++ pointer question. I have no clue on why this happen... I found that if i write this code. It is totally valid. Code1 int *j; //create an pointer j *j = 50; //assign 50 to the *j, meaning value pointed by address 50 is xxx However, when I wanna try to make it more simple. The compiler give me ...
There's a bit of ambiguity in the C syntax there. int *j = 50; is equivalent to int *j; j = 50; Actually, what you're doing in the first snippet of code is dangerous because you haven't allocated any memory for j before assigning a value to it yet. You'll need to make memory for it like so: in C: int *j = (int*) mall...
6,887,482
6,887,549
C++: function inside class for multiple variable values
a bit of a noob problem. Inside a class called 'cell', I have an enum 'Example' say typedef enum Example { E1=0, E2, E3, E4 }; Example inputValueE; Also I have a function inside class as follows void evolveE(Example type_); Outside the class, I attempt to define the function for seve...
When overloading a function (providing more than one function with the same name in a class), you need to provide a different set of argument types to each function like this: void cell::evolveE(Example type_){****some stuff****;} void cell::evolveE(OtherExample size_){****some diff stuff****;} Notice that here, one f...
6,887,523
6,887,540
MSVC++ says the stack around a variable is getting corrupted but program works
Sorry if this sounds like an "It compiles, so it must work!" question, but I want to understand why something is happening (or not happening, as the case may be). In Project Settings, I set Basic Runtime Checks to Both. The debugger informs me that: Run-Time Check Failure #2 - Stack around the variable 'beg' was corru...
Your question isn't answerable without code to reproduce the problem. But to give a vague answer to your general problem - If the compiler or debugger detected a problem, you probably have one. In C++, just because something "goes wrong" doesn't mean your program will crash - it might keep running with completely unpre...
6,887,537
6,887,694
Shouldn't declaration match its definition when array is involved?
There are two source files in my program. An array is defined in A.cpp. // compiler: MSVC2005 SP2 // A.cpp // defines an array of type "int [100]" int a[100] = {3}; It is used in B.cpp. // B.cpp // declares an array of type "int []" extern int a[]; int main() { // prints 3 correctly cout << a[0] << endl; ...
In both C and C++ a declaration of an object a of incomplete type will match the definition of object a where the type is complete. What you observe simply illustrates the fact that in C++ you are allowed to use incomplete types in non-defining declarations. But once you get to the definition the type must be complete....
6,887,838
6,887,863
Improving Minimax Algorithm
Currently I'm working on an Othello/Reversi game in c++. I have it "finished" except that the Minimax algorithm I'm using for the Computer player is painfully slow when I set it at a depth that produces a semi-challenging AI. The basic setup of my game is that the board is represented by a 2-dimensional array, with eac...
Calculating minimax is slow. The first possible optimization is alpha-beta pruning: http://en.wikipedia.org/wiki/Alpha-beta_pruning
6,887,842
6,887,892
Add icon resource without changing the EXE icon?
I've added an icon resource to my program. Unfortunately, it's a 16x16 icon meant as a visual aid on a button, and now it's set as the executable's main icon. Obviously, this looks terrible. Is it possible to add a resource while retaining the EXE's icon as the Windows default? I'm using Visual Studio 2010, if that hel...
It looks like your 16x16 icon is the only icon resource in your application, or the one with the smallest identifier. In that case, both Explorer (for its file lists) and the window manager (for the window's title bar) will default to that icon. You should add another icon to your application, with an id less than the ...
6,887,906
6,888,006
Template overloading (diff. number of arguments)
I wanted to create these function templates you see below. Their purpose is to compare functors, but I needed to cover a special case for the boost.bind type of functors. template<typename R, typename F, typename L> void compare(boost::_bi::bind_t<R, F, L>& lhs, boost::_bi::bind_t<R, F, L>& rhs) { std::cout << lhs....
boost::bind returns a value which can't be bound to a non-const reference. Your better specialized template needs to take it's arguments by value or by const reference otherwise it won't be considered in the call: compare( boost::bind(func, 1), boost::bind(func, 1) ). This test program compiles and works correctly on m...
6,887,981
6,888,003
C++ Friend Syntax/Semantics Question
My code was reviewed on: https://codereview.stackexchange.com/questions/3754/c-script-could-i-get-feed-back/3755#3755 The following was used: class Point { public: float distance(Point const& rhs) const { float dx = x - rhs.x; float dy = y - rhs.y; return sqrt( dx * dx + dy ...
And how can the client access them when they are private using the following? Yes. Since friend functions are not member of the class, it doesn't matter where you define them or declare them. Any can use them. The access rules don't apply on them. Could someone expound on what exactly is being returned? operator>>(...
6,888,375
6,888,598
QSettings how to save QMap<QString,int> into configuration file
After reading Save QList<int> to QSettings, I'm tring to do the same with QMap<QString,int>. I would like the configuration file to look like this: 1111=1 2222=3 4444=0 But I'm getting a compilation error: Q_DECLARE_METATYPE(QMap<QString,int>) Warning C4002: too many actual parameters for macro 'Q_DECLARE_METAT...
The error message you're getting is caused by the fact that the preprocessor doesn't know about templates. So it's parsing that macro call is if it had two arguments - QMap<QString and int>, which makes no sense. To save the data as you want it, you're better of serializing it yourself to your QSettings. Something like...
6,888,464
6,888,480
going to the next element in for loop through for statement not the general way
can help me in simple code below?? i commented where problem is TIA for(int i=0;i<10;i++) { if(x[i] !=1000) { //do something } else { //i want it to go to the next i and again check x[i] != 1000,not i++ } if(y != x[i]) { //do something } }
I am not sure who j is but you may be looking for this: if(x[i] !=1000) { //do something } else { //i want it to go to the next i and again check x[i] != 1000,not j++ continue; }
6,888,579
6,888,605
Private parameters in public methods
Neither g++ nor javac emit warnings when the parameters to non-private methods are of private types (e.g., private nested classes). Such methods cannot be used by clients, but they can appear as part of a class's public API. In C++, putting such methods into the public section of a class Foo, for example, could allow ...
This is allowed and might be required. While you might not be allowed to create a variable of the private type; it might be return by a function. This would allow data to be transfered around the system without being persistent in parts of the system that have no reason to hold a reference to it. This idiom is not comm...
6,888,585
6,888,627
C++ - Linux/shell script run child processes & get their return statuses
I'm looking for a solution to writing a piece of program in C++ on Linux that parses a file which contains programs with a set arguments, then runs those programs with their arguments arguments. Each program (line) is executed one at a time and then the parent process waits for each child to exit and inspects it's exi...
I agree with Ignacio. But if you have to do it , then I would prefer you using System/popen command. BUT MAKE SURE YOU ARE NOT RUNNING ANY COMMAND THAT WOULD LAND YOU TO TROUBLE.. like " rm -rf * ". This is very likely to happen if you are going to read from a file which cannot be trusted with. And no need to copy ...
6,888,630
6,888,790
C++ socket programming: maximize throughput/bandwidth on localhost (I only get 3 Gbit/s instead of 23GBit/s)
I want to create a C++ server/client that maximizes the throughput over TCP socket communication on my localhost. As a preparation, I used iperf to find out what the maximum bandwidth is on my i7 MacBookPro. ------------------------------------------------------------ Server listening on TCP port 5001 TCP window size: ...
My previous answer was mistaken. I have tested your programs and here are the results. If I run the original client, I get 0m7.763s If I use a buffer 4 times as large, I get 0m5.209s With a buffer 8 times as the original I get 0m3.780s I only changed the client. I suspect more performance can be squeezed if you also ...
6,888,793
6,888,842
Confusing Nulls in c
Please explain following things in regard of C or C++: The null pointer The internal representation of a null pointer The null pointer constant - 0 The NULL macro The ASCII null character (NUL) The null string ("").
The null pointer is a pointer that doesn't point to any object. The internal representation is not specified, and specifically doesn't have to be all bits zero. The value 0 can be converted to a null pointer. The NULL macro is defined as a value that can be converted to a null pointer, in C++ it is often just 0 and in ...
6,888,800
6,889,680
boost::asio::io_service - why use post function?
I'd like for someone to tell me the pros (and cons) for using the post function. Why and when should I prefer using post and why/when should I not want to use it?
Post is very useful when you want the callback to occur essentially now, but not in the current context. Reasons might include: The current context is holding locks and you want the function to be called after they have been released. This would allow the function to acquire those locks itself without causing a deadlo...
6,888,863
6,888,902
Asynchronous network calls
I made a class that has an asynchronous OpenWebPage() function. Once you call OpenWebPage(someUrl), a handler gets called - OnPageLoad(reply). I have been using a global variable called lastAction to take care of stuff once a page is loaded - handler checks what is the lastAction and calls an appropriate function. For ...
You are inviting all manner of bugs if you try and use a single member variable to maintain state for an arbitrary number of asynchronous operations, which is what you describe above. There is no way for you to determine the order that the OpenWebPage calls complete, so there's also no way to associate the value of las...
6,888,965
7,125,037
Any way to speed up/reduce CPU usage when drawing with Cairo?
I wrote an app that uses Cairo to draw things on screen (on a Gtk::DrawingArea, to be exact). It needs to redraw everything frequently. It turns out, that despite the draphics drawn are very simple, the X server uses LOTS of CPU when redrawing, and the applications works terribly slow. Is there any way to speed this up...
I finally forced to use maximally 25 fps, by using a lock flag. bool lock = 0; bool needs_redraw = 0; void Redraw(){ if(lock){ needs_redraw = 1; return; } //draw image to a surface needs_redraw = 0; lock = 1; Glib::signal_timeout().connect(Unlock, 20); queue_draw(); } bo...
6,888,975
6,889,038
Alternative to lexical_cast<T>(std::string)
I've got templated code that uses lexical_cast. Now I want to remove all the lexical_cast calls (because it doesn't work well with /clr). I need to cast object between std::string and their value. So, the first direction is easy (T _from, std::string _to) : std::ostringstream os; os << _from; _to = os.str(); But I ca...
lexical_cast uses streaming in both directions, << and >>. You could do the same: std::stringstream sstr; sstr << _from; sstr >> _to; Be sure to include sanity checks though.
6,889,024
6,889,225
C Compiler cannot create executables, OpenSolaris Erlang/OTP ./configure error
was running the ./configure script for OTP14B03 on OpenSolaris and got the following output Ignoring the --cache-file argument since it can cause the system to be erroneously configured Disabling caching checking build system type... i386-pc-solaris2.11 checking host system type... i386-pc-solaris2.11 checking for gcc...
Your linker cannot find the values-Xa.o object file. According to this FAQ, it either means your system is missing a package required by the compiler, or that the required packages are installed but your default library path does not reflect it. As a quick check, you can try adding /usr/ccs/lib to the library path: ./c...
6,889,067
6,889,096
How to perform bitwise operations on files in linux?
I wanna do some bitwise operations (for example xor two files) on files in Linux , and I have no idea how I can do that. Is there any command for that or not? any help will be appreciated.
You can map the file with mmap, apply bitwise operations on the mapped memory, and close it. Alternatively, reading chunks into a buffer, applying the operation on the buffer, and writing out the buffer works too. Here's an example (C, not C++; since everything but the error handlings is the same) that inverts all bits...
6,889,161
6,889,205
Problem with Class for processing of strings
I read lines from a text file and would like to repeated delimiters as \t\t. Normally I have between delimiters a parameter but for readability reasons it is sometimes nice to use strings as \t\t\t in order to line out text sequences. I wrote a class in my main.cpp that worked well. Because I would like to keep my main...
If you want to use C++ std::string you should include the <string> header. The similarly named <string.h> is for C language string functions.
6,889,162
6,889,422
Free/open source C/C++ library of vectorized math functions?
I'm looking for a free/open source C/C++ (either is acceptable) library of vectorized versions of common math functions (such as ln or exp) similar to Intel's Vector Math Library for Linux. I'd like a library that would provide me with the ability to write something like: double a[ARRAY_SIZE], b[ARRAY_SIZE]; for (int ...
you might find AMD's LibM Library (it is for x64 however) combined with SSEPlus to be of use. There is also an opensource x86 variant of Sony's Vector Math library.
6,889,199
6,889,241
substr in c++ problem
When I try to execute the program, the output is coming as expected for the first iteration. but for second iteration, out is not coming as expected... int main(){ string insertBuffer; string valSep; valSep = ":"; string configParamSep = "\r\n"; int configParamSepSize = 2; ...
From this link http://en.cppreference.com/w/cpp/string/basic_string/substr I read that the second parameter is a count and not a position. Does that help, or am I wrong here?
6,889,368
6,889,388
How to catch the QSystemTrayIcon quit event?
I have a QSystemTrayIcon subclass. Inside it, I have: quitAction = new QAction(tr("&Quit"), m_parent); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); CloseEvent doesn't work here. How can I catch this quit event? I want to save data before closing.
You should connect your cleanup/save code to the QCoreApplication::aboutToQuit() signal. This signal is emitted when the application is about to quit the main event loop, e.g. when the event loop level drops to zero. This may happen either after a call to quit() from inside the application or when the users shuts down...
6,889,385
6,890,813
Identifying local minima in a histogram
I'm interested in finding the local minima in a histogram that roughly resembles I'd want to find the local minimum at 109.258, and the easiest way to do so would be to identify whether the number of counts at 109.258 is lower than the average number of counts around in some interval around (and including 109.258). It...
If I understand correctly kmore wants to partition two "peaks" based on the largest separation (product of histogram count and bin distance). If this is true: Find all maxs. for each max build rectangles like in Fig. Find rectangle with max white area, which gives you the x range to find desirable bin 109.258
6,889,395
6,892,042
C++0x tuples have no iterators, right?
Looking into the standard N3291 I do not find any reference for tuple to support begin() and end(). But when I look at my notes from years back I seem to have jotted down that I need to look into that later. And here we are. I can not find any trace of tuple<...>.begin() or tuple<...>.end() in the current C++0x standar...
Boost.Fusion has iterable tuples -- boost::fusion::vector<> -- along with many iteration, query, and transformation algorithms for tuples. It also has code to adapt boost::tuple<> for use with those iterators and algorithms; you could take that code and modify it to work with std::tuple<> instead.
6,889,511
6,889,531
again "undefined symbol" in runtime, c++
I have a data type and I can instantiate a variable of that type. like this: FetchAddr faddr(VirtualMemoryAddress( 0x0a )); The definition of FetchAdr is: struct FetchAddr { VirtualMemoryAddress theAddress; FetchAddr(VirtualMemoryAddress anAddress) : theAddress(anAddress) { } }; Now I have a class that...
When you declare a static member you also have to define it somewhere, like in a .cpp file. And also remember to link to this file. Problem number 2 - FetchAddr doesn't have a default constructor. If you need to have faddr as a static member of the class, you also need to give it a value when it is defined, like: Fetc...
6,889,522
6,889,936
/fp:fast vs :fp:precise what kind of errors can I encounter?
I'm wondering what kind of errors I can encounter if I set /fp:fast instead of fp:precise? I work under MSV10 I perform /,*,+,- operations on double with max digits equal to 8, like 1.4379294 (currency rate).
The same errors you always get with double calculations: you never get more than 15 significant digits after you convert the result to decimal, the rest are just random noise digits. The difference between /fp:fast and /fp:precise is what happens to those noise digits. The /fp:precise option solves a problem with the ...
6,889,565
6,889,618
Unresolved external symbol after every change in code
I've got a problem with my code. It basically looks like this: someclass.hpp: class SomeClass { public: SomeClass(); ~SomeClass(); //... some other methods }; someclass.cpp: #include "SomeClass.hpp" SomeClass::SomeClass() { } SomeClass::~SomeClass() { } SomeClass.cpp doesn't include anything else. The ...
In addition to what @Nawaz says, it's likely your build files are out of sync with the linker so that when Visual Studio goes to re-link, it can't because the files are out of sync. Just re-build and be done with it. By the way, it may even be a bug in Visual Studio 2010 as seen here.
6,889,949
6,890,277
How to install Boost libraries with CodeBlocks?
So I'm about at the end of my line here; I was looking into saving files and serialization, only to learn that C++ doesn't have the kind of native serialization ability that Python has with its wonderful pickle. But luckily, it has Boost - so began my quest to install Boost 1.47 on my system, in order to be able to se...
From the error message you posted I assume you're using some version of Visual Studio. In order to use its compiler from the command line you need to define a few environment variables. This is done automatically for you if you use the Visual Studio command prompt. Better yet you might want to try and follow this tuto...
6,890,100
6,890,118
Run a function "In Background" of a WinForm (VS2010 c++)
I have a function that run over hours.. I want that on click on a button, this function will start to run, and on click on anoter button (Stop) this function will be stopped (break) - but the problem is that the form become "stuck" when the function is running - and there is no option to click on button Stop. So how to...
Read a bit about the concept of threads. WinAPI provides both functions to start new thread and control it, search MSDN for them - creating a new form is not the way to go.
6,890,258
6,891,276
SFML and GTK+ - GtkFileChooserDialog
I'm writing an app using SFML and I want to use GTK+ to create file chooser dialogs. I have this code: gtk_init(&argc, &argv); GtkWidget *dialog; dialog = gtk_file_chooser_dialog_new ("Open file...", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); ...
In the gtk_dialog_run documentation there is a note After gtk_dialog_run() returns, you are responsible for hiding or destroying the dialog if you wish to do so. So the dialog should not get destroyed automaticaly, the programmer must do it. EDIT: The another problem is that you are not running GTK main loop (gtk_...
6,890,331
6,890,501
Where can I find a description about the usage of "int C::*"?
In a piece of code, I find something as : template<typename T> class IsClassT { private: typedef char One; template<typename C> static One test(int C::*); ... The question is where can I find a description about why the usage of "int C::*" is valid in function test() definition?
I won't describe what int C::* means since @Charles Bailey already did that very well. I will however answer your question: (...) why the usage of "int C::*" is valid in function test() definition? The key point is that the usage of int C::* (pointer to member of type int) is valid if and only if C is a class type....
6,890,571
6,890,583
Which data structure would be best for this?
For my game, when an object enters a sensor, I need to add it to a list, and when the object leaves the sensor it needs to be removed from that list. I also need to quickly be able to find that object. So essentially: I need it to do: quick adding, quick removal and quick find. What sort of data structure would be best...
With 10 objects anything will do (std::vector, deque or set), and nobody can tell which one performs better before profiling. If you don't know what to use, perhaps you'll find that std::set has a nicer syntax for looking up elements. This is what I would use in this situation, because I wouldn't like to write std::fin...
6,890,656
6,890,676
Passing an auto_ptr to a function effectively makes it a sink. Why?
I'm reading some notes about shared pointers. They say the first attempt by STL with the auto_ptr had the following major drawbacks: They can't be used in STL containers Copying the auto_ptr transfers ownership Passing an auto_ptr to a function effectively makes it a sink I understand the first two, but am unsure wha...
This is because once you copy the auto_ptr into a variable, you forfeit the ownership of the pointer to the new variable. When you have: void foo(std::auto_ptr<bar> x); and you call foo with an auto_ptr, you make a copy of the auto_ptr for foo's use. This effectively transfers ownership to foo and thus the pointer get...
6,890,757
6,890,782
Counting file in a directory
I want to count number of file in a directory, I used count method in QDir class but it always return number of file plus two! why does it do this work ? thanks
QDir.count() returns the total count of files and directories in the directory. This includes the . (this) and .. (parent) directory entries. So the count is always two more than the "real" files and subdirectories.
6,890,883
6,890,929
Run-time detection of memory deletion
The code: int *ptr = new int[10]; int *q = ptr; delete q; works fine without any issues (no run-time error). However, the following code: int *ptr = new int[10]; int *q = ptr; q++; delete q; results in run-time error. I am using Microsoft Visual Studio-8 and Win-7 as platform. I am not able to figure out why there ...
Your code is causing an Undefined Behavior. An Undefined Behavior means anything can happen, the behavior cannot be defined. The program works just by pure luck its behavior cannot be explained. Basically, If you are allocating dynamic memory with new you MUST use delete to deallocate it. If you are allocating dynamic...
6,891,064
6,891,190
Parsing list of strings ending with double NULL
How to parse in c++ list of null-terminated Unicode strings where the list is terminated with two NULL characters?
There's this little example on Raymond Chen's blog (which, perhaps not surprisingly, is the first find in Google for "double null terminated string"): This reinterpretation of a double-null-terminated string as really a list of strings with an empty string as the terminator makes writing code to walk through a dou...
6,891,183
6,891,213
Confusion regarding Image compression algorithms
I had been reading a webpage on Image Compression (Lossy and Non-lossy). Now this is my problem, I was successful in making a project on Face detection using opencv - however - my Project Guide is not satisfied - my project simply captures the frames from a Capture device [ webcam ] and passes frames in a function to d...
You want to invent your own image compression or implement one of the standard ones? ( I assume this is for some sort of class/assignment, you wouldn't do this in the real world!) You can compress simple images a little using something like Run-Length, especially if you can reduce the number of colours ie. a cartoon or...
6,891,252
6,891,279
c++ newline character under windows command line redirection
I found that Windows command line redirection will replace '\n' with '\r\n' automatically. Is there any method to avoid this situation? Because after stdout or stderr redirection, you will got '\r\r\n' instead of '\r\n' if you write '\r\n' to the console. Thanks a lot! you can just try a simple program: fprintf(stdout,...
The way to avoid it is to not write "Hello, world!\r\n". Either fprintf(stdout,"Hello, world!\n"); or std::cout << "Hello, world!" << std::endl; is sufficient. This isn't particular to command-line redirection or stdout, the same would be true with any file descriptor open in character mode (as opposed to binary mode)....
6,891,274
6,891,668
Async glTexSubImage2D and OGL thread blocking
I'm working on a GPGPU application that transfers data between the cpu and gpu using PBOs. One requirement in my application is that the OpenGL rendering thread should be blocking as little as possible and the processing should have as low latency as possible. My question is whether I have to add latency between the ca...
I would say that the most latency will be in the call to copy() and/or glUnmapBuffer(), but it will depend on so many things (your hardware, mainly) that your best bet is to do one transfer at the beginning of the program and measure them. For the timing you should use the glFinish() function with a high resolution t...
6,891,394
6,891,437
Is this a sign of heap fragmentation?
To test if my object had a memory leak, I instanced it 10000 times and deleted it 10000 times. After, my program was using about 500kb more. I do not think my object is leaking though. Thanks
On Linux at least, the C library does not release memory back to the OS just because you call delete. It puts the memory on a "free list" inside your process. So if you are using a command like top or cat /proc/XXX/status to measure the virtual memory use, you will see the size consumed by everything in your process ...
6,891,401
6,891,441
Making strange polymorphism
I'm trying to make some kind of strange polymorphism on C++: I have two trees of classes: State <-- Stage <-- Stage_1, Stage_2, Stage_3 Action <-- ActionState <-- ActionState_Clear, ActionState_Begin, ActionState_[...] I want to define some methods on Stage_1 that get an Action as parameter: State { virtual void e...
You can only override in your base classes contravariantly: the type of the argument in the derived class method must be less derived than the one in the base class. Otherwise (as in your case), you are just writing a different function.
6,891,652
6,892,562
Formatting a string into multiple lines of a specific length in C/C++
Is there a common C/C++ library (or common technique) for taking a line(s) of input text and splitting the words into separate lines. Where each line of output has a max width and words are not split across lines. Whitespace being collapsed or preserved is ok. Punctuation must be preserved. Small and compact library i...
Here's my approach, it's certainly not the fastest but I tried to make it as readable as possible. The result is the same as your example. #include <iostream> #include <string> std::string splitInLines(std::string source, std::size_t width, std::string whitespace = " \t\r") { std::size_t currIndex = width - 1; ...
6,891,748
6,891,877
exception handling(restricting exceptions)
i was dealing with the following code,& got confused,please have a look at it #include<iostream> #include<conio.h> #include<string.h> using namespace std; void Xhandler(int test) throw(char,double) /*i am restricting an integer exception here by not including it in the argument list of throw*/ { if(test==0) thro...
You did not specified the compiler. If you are using Microsoft visual C++ there is a note at Exception Specifications page on the MSDN Visual C++ departs from the ANSI Standard in its implementation of exception specifications. The following table summarizes the Visual C++ implementation of exception specifications: ....
6,891,750
6,891,764
Non static const data members
How do I define a non-static const data member of a class in C++? If I try compiling the following code: class a { public: void print() { cout<<y<<endl; } private: const int y=2; }; int main() { a obj; obj.print(); } I get an error ISO C++ forbids initialization of member ‘y’
In C++03 you can initialize const fields of a class using a member-initializer list in the constructor. For example: class a { public: a(); void print() { cout<<y<<endl; } private: const int y; }; a::a() : y(2) { // Empty } Notice the syntax : y(2) after the constructor. This tells...
6,891,847
6,891,861
How much every character occurs in the given string
I need to calculate how many times every character occurs in the given string. I need to do it on C or C++, I can use any library. The problem is that I am not a C/C++ developer, so I am not sure that my code is optimal. I want to get the best performance algorithm, it is the main reason for this question. I am using t...
You are doing it right using bucket sort. There cannot be a faster (non-parallel) algorithm for counting elements in a finite universe (such as characters). If you only use ASCII characters, you can use a simple array int table[256] to avoid the overhead of C++ containers. Using Duff's device (which is actually slower ...
6,892,145
6,892,214
C++ unlimited parameters to array
I have a function with following signature char requestApiCall(int num, const wchar_t* pParams = 0, ...) { ... } Now I want to to get all pParams in an array (or to be able to iterate over it). I know this is possible with some macros, but I have no idea how to do it. Any help would be appreciated. P.S. I'm using Min...
You need to look at the functions and macros declared in stdarg.h. Here is a tutorial that explains it. http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html I'm not sure what your function parameters are supposed to represent but I think you'll find that it needs to change. By the way, I find that for C++ I ...