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,693,651 | 2,693,737 | C++: Vector of objects vs. vector of pointers to new objects? | I am seeking to improve my C++ skills by writing a sample software renderer. It takes objects consisting of points in a 3d space and maps them to a 2d viewport and draws circles of varying size for each point in view. Which is better:
class World{
vector<ObjectBaseClass> object_list;
public:
void generate(){
... | You wont get what You want with this code
class World{
vector<ObjectBaseClass> object_list;
public:
void generate(){
object_list.clear();
object_list.push_back(DerivedClass1());
object_list.push_back(DerivedClass2());
What is going to happen is called object slicing. You will get a vect... |
2,693,665 | 2,693,929 | Do I really need to return Type::size_type? | I often have classes that are mostly just wrappers around some STL container, like this:
class Foo {
public:
typedef std::vector<whatever> Vec;
typedef Vec::size_type size_type;
const Vec& GetVec() { return vec_; }
size_type size() { return vec_.size() }
private:
Vec vec_;
};
I am not so sure about returning... | STL defines these types as an abstract interface for containers. It is intended to support any type of backing storage. That might be NUMA or disk-backed storage, where size_type and ptr-type are different from those for system memory. Or - in a NUMA architecture - it might be a specific memory node that's fast, and ca... |
2,693,683 | 2,693,702 | Tail recursion in C++ | Can someone show me a simple tail-recursive function in C++?
Why is tail recursion better, if it even is?
What other kinds of recursion are there besides tail recursion?
| A simple tail recursive function:
unsigned int f( unsigned int a ) {
if ( a == 0 ) {
return a;
}
return f( a - 1 ); // tail recursion
}
Tail recursion is basically when:
there is only a single recursive call
that call is the last statement in the function
And it's not "better", except in the sense ... |
2,693,753 | 2,693,813 | Compiler turning a string& into a basic_string<>& | I'm coming back to C++ after long years spent on other technologies and i'm stuck on some weird behavior when calling some methods taking std::string as parameters :
An example of call :
LocalNodeConfiguration *LocalNodeConfiguration::ReadFromFile(std::string & path)
{
// ...
throw configuration_file_error(string("Con... | The problem is not basic_string, because basic_string<char, restOfMess> is equivalent to string.
The problem is the function only provides
f(string&, string&) {
//------^
but you are calling as
f(string("blah"), path);
// ^^^^^^^^^^^^^^
This is a rvalue (temporary object), and a rvalue cannot be bound to a mutable r... |
2,693,997 | 2,694,950 | What are options for GWT to C++ communication? | I am looking for GWT to C++ communication solution.
Currently I am trying to figure out how to run WSDL in GWT, but actually, have absolutely no experience in WSDL, and only little in GWT.
So, my question is about feasibility of working with WSDL in GWT (and how?) and other approaches would also be interesting if exis... | GWT Side:
RequestBuilder and com.google.gwt.json.client.JSONObject for quick and really not that dirty marshaling api.
Overlay types require you to know your data configuration at compile time. With JSONObject (and it's JSONValue's), you can treat it like a slightly unwieldy key/value map.
Set your RequestBuilder to P... |
2,694,298 | 2,694,538 | Move constructor and assignment operator: why no default for derived classes? | Why there is default move constructor or assignment operator not created for derived classes? To demonstrate what I mean; having this setup code:
#include <utility>
struct A
{
A () { }
A (A&&) { throw 0; }
A& operator= (A&&) { throw 0; }
};
struct B : A
{ };
either of the following lines throws:
A x (std::mo... | Reading through 12.8 in the 0x FCD (12.8/17 in particular for the move ctor), this appears to be a GCC bug. I see the same thing happening in 4.5 as you do in 4.4.
I may be missing a corner case on deleted functions, or something similar, but I don't see any indication of that yet.
|
2,694,462 | 2,694,477 | How to maintain 2 lists of object | My c++ program needs to maintain 2 list of objects.
list<A*> inuse;
list<A*> free;
So objects A can even in 'inuse' list or in 'free' list, but not both.
http://www.cplusplus.com/reference/stl/list/
I am think of using 'list' as the data structure for my lists.
My questions are
why i can't randomly access an elmenet... | Use std::vector.
It has random element access ([] or at()).
//does NOT check for out of range
myvector[i];
//does check for out of range
myvactor.at(i);
You can remove an element from vector using erase(), and it will handle holes automatically (#3 becomes #2, and so on)
//erase the 6th element
myvector.erase (myvec... |
2,694,802 | 2,694,975 | Qt, can't display child widget | I have two widgets defined as follows
class mainWindow : public QWidget
{
Q_OBJECT
public:
mainWindow();
void readConfig();
private:
SWindow *config;
QVector <QString> filePath;
QVector <QLabel*> alias,procStatus;
QVector <int> delay;
QGridLayout *mainLayout;
QVector<QPushButton*> st... | By default a QWidget isn't a window. If it is not a window and you specify a parent, it will be displayed inside the parent (so in your case it is probably hidden by other widgets inside your mainWindow).
Look at windowFlags() too. Or you could make your SWindow inherit from QDialog, depending on what you use it for.
... |
2,694,973 | 2,749,079 | (How) Can I approximate a "dynamic" index (key extractor) for Boost MultiIndex? | I have a MultiIndex container of boost::shared_ptrs to members of class Host. These members contain private arrays bool infections[NUM_SEROTYPES] revealing Hosts' infection statuses with respect to each of 1,...,NUM_SEROTYPES serotypes. I want to be able to determine at any time in the simulation the number of people i... | To implement option 2, define an enumerated type for the serotypes within another class, then write a templated key extractor. I'm not certain that boost::multi_index_container supports reindexing (I doubt it does), so this approach may be doomed from the start.
class ... {
enum Serotype {
...
sup ... |
2,695,012 | 2,695,440 | Compiler reordering around mutex boundaries? | Suppose I have my own non-inline functions LockMutex and UnlockMutex, which are using some proper mutex - such as boost - inside. How will the compiler know not to reorder other operations with regard to calls to the LockMutex and UnlockMutex? It can not possibly know how will I implement these functions in some other ... |
It can not possibly know how will I implement these functions in some other compilation unit.
This is the key - since the compiler cannot know (in general) about the implementation of the function calls, it can't move the store to _field outside those function calls.
Generally, since _field is accessible outside of S... |
2,695,125 | 2,695,200 | C++: Is windows.h generally an efficient code library? | I heard some people complaining about including the windows header file in a C++ application and using it. They mentioned that it is inefficient. Is this just some urban legend or are there really some real hard facts behind it? In other words, if you believe it is efficient or inefficient please explain how this can b... | If you precompile it, then the compilation speed difference is barely noticeable. The downside to precompiling, is that you can only have one pre-compiled header per project, so people tend to make a single "precompiled.h" (or "stdafx.h") and include windows.h, boost, stl and everything else they need in there. Of cour... |
2,695,169 | 2,697,445 | Are raw C++ pointers first class objects? | According to Wikipedia:
An object is first-class when it:
can be stored in variables and data structures
can be passed as a parameter to a subroutine
can be returned as the result of a subroutine
can be constructed at runtime
has intrinsic identity (independent of any given name)
Somebody had once told me that raw po... | Actually both - "Pointers are FCO" and "Pointers are not FCO" - are correct. We need to take the statements in the respective context. (FCO - First Class Object)
When we talk of a 'pointer' in C++, we are talking of a data type that stores the address of some other data. Now whether this is FCO or not, depends really o... |
2,695,311 | 2,695,406 | C++ game designing & polymorphism question | I'm trying to implement some sort of 'just-for-me' game engine and the problem's plot goes the following way:
Suppose I have some abstract interface for a renderable entity, e.g. IRenderable.
And it's declared the following way:
interface IRenderable {
// (...)
// Suppose that Backend is some abstract backend used
... | I'm not a c++ programmer but hopefully faux-code will help...
Class Renderable has the function Render
Class Movable inherits from Renderable and also has properties such as x, y, z and functions like Move
Class Ball inherits from Movable
Now your game state can have a list of Renderable objects and, when the time come... |
2,695,493 | 2,695,509 | Check if file data is binary | when I write a number to binary file, it won't display. but in case of a character, it does. why? how would you check to see if the file containing character is binary?
| It has all to do with how you interpret what is in the file. Everything in a file is binary, a character an integer etc.
When you do TYPE in the console on a file (or CAT or whatever OS u have) the contents of the file are interpreted as text by default because the programmer of TYPE decided to write it like that.
Whe... |
2,695,607 | 2,695,628 | Is it a good idea to index an STL map with a pair? | I'm just wondering if it is a good idea to make a data structure like
std::map< std::pair<int,int>,std::string >
Just wondering how the pairs would be ordered internally... :S
Thanks!
| The pairs would be ordered using the pair operator< (the default compare operation for std::map), which
Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second)
(C++03, 20.2.2/6)
Note that it could get confusing using a pair as a map key, especially when working with map iterators (it->first.firs... |
2,695,657 | 2,695,692 | STL Static-Const Member Definitions | How does the following work?
#include <limits>
int main()
{
const int* const foo = &std::numeric_limits<int> ::digits;
}
I was under the impression that in order to take an address of a static const-ant member we had to physically define it in some translation unit in order to please the linker. That said, after lo... | Well, what makes you think that it is not defined? The very fact that your attempt to take the address succeeded automatically indicates that it is defined somewhere. It is not required to reside in your tranlation unit, of course, so looking through the preprocessor output doesn't make much sense.
|
2,695,667 | 2,697,386 | Improving I/O performance in C++ programs[external merge sort] | I am currently working on a project involving external merge-sort using replacement-selection and k-way merge. I have implemented the project in C++[runs on linux]. Its very simple and right now deals with only fixed sized records.
For reading & writing I use (i/o)fstream classes. After executing the program for few i... | Such high performance I/O is easiest done with mmap. This gives the kernel far more freedom to perform I/O and schedule CPU time for your app. For instance, when you read in 1 MB using ifstream, the kernel can only return when all the data is read. But with mmap(), the data can be returned incrementally as it becomes a... |
2,695,743 | 2,695,760 | Assign C++ instance method to a global-function-pointer? | Greetings,
My project structure is as follows:
\- base (C static library)
callbacks.h
callbacks.c
paint_node.c
.
.
* libBase.a
\-app (C++ application)
main.cpp
In C library 'base' , I have declared global-function-pointer as:
in singleheader file
callbacks.h
#ifndef CALLBACKS_H_
#... | This is answered in the C++ FAQ, [1]. This doesn't work, because the pointer isn't associated with a particular object instance. The solution is given there too, create a global function that uses a particular object:
Sacm* sacm_global;
void sacm_global_paintPixel(int x,int y,int index)
{
sacm_global->paintPix... |
2,695,750 | 2,695,783 | Set Carret position in Text Field (Win32API) | I'v created a text box and when it gets focus it sets the caret position to 0 rather than the end. I want to set it to the end.
Thanks
|Text Here -> Text Here|
| The caret position is basically the same as the current selection -- when the beginning and end are at different positions, you have some text selected. If the beginning and end of selection are at the same place, that's the caret position.
You can set the selection with EM_SETSEL. To put it at the end, use -1 for both... |
2,695,753 | 2,695,759 | operator << overload | //using namespace std;
using std::ifstream;
using std::ofstream;
using std::cout;
class Dog
{
friend ostream& operator<< (ostream&, const Dog&);
public:
char* name;
char* breed;
char* gender;
Dog();
~Dog();
};
im trying to overload the << operator. I'm also tryin... | You have using std::ofstream instead of using std::ostream, so it doesn't know what ostream is.
You also need to include <ostream>.
Really, though, there's no reason to use using anything; you should just qualify the names with the namespace (especially if this is a header file, to avoid polluting the global namespace ... |
2,695,878 | 2,700,987 | Creating a QLineEdit search field for items displayed in a QListView | I want to create a search field that filters the items shown in a QListView. Basically the user could type in "foo" and only items with "foo" in the DisplayRole are shown.
I already have a few ideas on how to do this, but thought I'd ask those more experienced than I.
My idea would be to use some signals and slots to ... | Answering my own question for reference.
Looks like what is needed here is a QSortFilterProxyModel.
The code looks something like:
QListView *myview = new QListView(this);
MyModel *model = new MyModel(this);
QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this);
proxy->setSourceModel(model);
myview->setModel... |
2,695,919 | 2,695,926 | Why do people use Command-line instead of IDE? | Hi I am learning C++ and at the very beginning used a Command-line... then I started using Xcode (and since then couldn't switch back to command line) and was just wondering some specific reasons/situations to use Command-line instead of IDE...
| More efficent for large systems -
Try opening a VS solution with a 100 projects and 10,000 files.
Simpler for a lot of tasks, you edit in one window, run make in another, have gdb in a third.
Easier to automate tasks, often easier to work in teams or cross-platform if everyone has gcc and vi (or emacs)
|
2,696,074 | 2,696,081 | Why am I not getting correct result when I calculate exponent with ^ in C++? | I am using Bode's formuala to calculate distance of nth planet from sun
dist = (4 + 3*(2^(n-2)))/10
If I calculate the distance this way, I get the right values:
dist[2] = ((4 + 3*1)/10.0) ;
dist[3] = ((4 + 3*2)/10.0) ;
dist[4] = ((4 + 3*4)/10.0) ;
But doing it this way, gives me incorrect values:
vector <double>... | The ^ character represents a bitwise exclusive or, not the exponential function that you expect.
Since you're calculating this in a loop already you can easily generate the powers of 2 that you need in the equation, something simple (and close to your code) would be:
vector<double> dist(5);
unsigned int j = 1;
for(unsi... |
2,696,156 | 2,749,285 | How to reduce redundant code when adding new c++0x rvalue reference operator overloads | I am adding new operator overloads to take advantage of c++0x rvalue references, and I feel like I'm producing a lot of redundant code.
I have a class, tree, that holds a tree of algebraic operations on double values. Here is an example use case:
tree x = 1.23;
tree y = 8.19;
tree z = (x + y)/67.31 - 3.15*y;
...
std::c... | Just a quick late answer: If the class in question is moveable, the move is very cheap, and you would always move from all the arguments if you can, then passing the arguments by value might be an option:
tree operator +(tree a, tree b);
If tree is moveable and an rvalue ref is passed as the actual argument,... |
2,696,166 | 2,696,367 | What kind of .lib file begins with "!<arch>"? | I have a .lib file, just wondering what compiler it's from: it begins with "!<arch>" ?
Thanks
| !<arch> sounds like an ar archive.
|
2,696,171 | 2,696,233 | Inject runtime exception to pthread sometime fails. How to fix that? | I try to inject the exception to thread using signals, but some times the exception is not get caught. For example the following code:
void _sigthrow(int sig)
{
throw runtime_error(strsignal(sig));
}
struct sigaction sigthrow = {{&_sigthrow}};
void* thread1(void*)
{
sigaction(SIGINT,&sigthrow,NULL);
try
... | G++ assumes that exceptions can only be thrown from function calls. If you're going to violate this assumption (eg, by throwing them from signal handlers), you need to pass -fnon-call-exceptions to G++ when building your program.
Note, however that this causes G++ to:
Generate code that allows trapping instructions to... |
2,696,257 | 2,696,352 | Why is visual studio not aware that an integer's value is changing? (debugging) | I have a few simple lines of code (below). [bp] indicates a breakpoint.
for(int i=0;i<300;i++){}
int i=0;
cout<<i;
[bp] for (i=0;i<200;i++){}
When I debug this in visual studio, it tells me that i is equal to 300 on the breakpoint. Annoyingly, 0 is printed to the console. Is there any way to make it rea... | in my visual studio, looking at the debugger Locals window
i 300 int
argc 1 int
argv 0x00214b88 wchar_t * *
i 0 int
NOTE! there are two i varibles in the debug output, i == 300 and i == 0
I'm thinking the reason its getting confused is a quirk/bug of the debugger where i... |
2,696,635 | 2,696,652 | Normal pointer vs Auto pointer (std::auto_ptr) | Code snippet (normal pointer)
int *pi = new int;
int i = 90;
pi = &i;
int k = *pi + 10;
cout<<k<<endl;
delete pi;
[Output: 100]
Code snippet (auto pointer)
Case 1:
std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;
int k = *pi + 10; //Throws unhandled exception error at this point while debugging.
cout<<k<<endl;
/... | You tried to bind auto_ptr to a stack allocated variable.
std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;
never try to do that - only bind auto_ptr to variables allocated with new. Otherwise auto_ptr will try to delete a stack allocated variable and that's undefined behavior.
|
2,696,637 | 2,696,671 | C++ reference variables | I have these two functions (with Point2D & LineVector (has 2 Point2D member variables) classes and SQUARE macro predefined)
inline float distance(const Point2D &p1,const Point2D &p2) {
return sqrt(SQUARE(p2.getX()-p1.getX())+SQUARE(p2.getY()-p1.getY()));
}
inline float maxDistance(const LineVector &lv1,const LineV... | Looks like you may be calling std::distance instead of your own distance function. There are a few reasons why this might be happening, but it's usually because of gratuitous use of
using namespace std;
Try explicitly using the namespace or class name when calling the distance function, or if it's in the global names... |
2,696,717 | 2,696,760 | Indices instead of pointers in STL containers? | Due to specific requirements [*], I need a singly-linked list implementation that uses integer indices instead of pointers to link nodes. The indices are always interpreted with respect to a vector containing the list nodes.
I thought I might achieve this by defining my own allocator, but looking into the gcc's implem... | We had to write our own list containers to get exactly this. It's about a half day's work.
|
2,696,754 | 2,696,761 | "Forced constness" in std::map<std::vector<int>,double> >? | Consider this program:
#include <map>
#include <vector>
typedef std::vector<int> IntVector;
typedef std::map<IntVector,double> Map;
void foo(Map& m,const IntVector& v)
{
Map::iterator i = m.find(v);
i->first.push_back(10);
};
int main()
{
Map m;
IntVector v(10,10);
foo(m,v);
return 0;
}
Using g++ 4.4... | The keys in a map are constant. A map is a tree, and you can't just going around changing the keys or you'll break its invariants. The value_type of a map with Key and Value is std::pair<const Key, Value>, to enforce this.
Your design needs some changing. If you really need to modify the key, you need to remove the ele... |
2,696,789 | 2,696,802 | Can C++ Constructors be templates? | I have non-template class with a templatized constructor. This code compiles for me. But i remember that somewhere i have referred that constructors cannot be templates. Can someone explain whether this is a valid usage?
typedef double Vector;
//enum Method {A, B, C, D, E, F};
struct A {};
class Butcher
{
public:
te... | Yes, constructors can be templates.
|
2,696,864 | 2,752,446 | Are free operator->* overloads evil? | I was perusing section 13.5 after refuting the notion that built-in operators do not participate in overload resolution, and noticed that there is no section on operator->*. It is just a generic binary operator.
Its brethren, operator->, operator*, and operator[], are all required to be non-static member functions. Thi... | Googling around a bit, I found more instances of people asking whether operator->* is ever used than actual suggestions.
A couple places suggest T &A::operator->*( T B::* ). Not sure whether this reflects designer's intent or a misimpression that T &A::operator->*( T A::* ) is a builtin. Not really related to my questi... |
2,697,137 | 2,697,263 | C++ and its type system: How to deal with data with multiple types? | "Introduction"
I'm relatively new to C++. I went through all the basic stuff and managed to build 2-3 simple interpreters for my programming languages.
The first thing that gave and still gives me a headache: Implementing the type system of my language in C++
Think of that: Ruby, Python, PHP and Co. have a lot of built... | There are a couple of different things that you can do here. Different solutions have come up in time, and most of them require dynamic allocation of the actual datum (boost::variant can avoid using dynamically allocated memory for small objects --thanks @MSalters).
Pure C approach:
Store type information and a void po... |
2,697,304 | 2,702,123 | Results from two queries at once in sqlite? | I'm currently trying to optimize the sluggish process of retrieving a page of log entries from the SQLite database.
I noticed I almost always retrieve next entries along with count of available entries:
SELECT time, level, type, text FROM Logs
WHERE level IN (%s)
ORDER BY time DESC, id DESC
... | You can make the count query return the same number of columns as the selection query and make a UNION of the count query and the selection one.
The first row of the result set will contain the total count then.
Another possible solution is described in the post about SQL_CALC_FOUND_ROWS from sqlite-users maillist.
And... |
2,697,367 | 2,697,839 | Remove pointer object whose reference is maintained in three different lists | I am not sure how to approach this problem:
'Player' class maintains a list of Bullet* objects:
class Player
{
protected:
std::list< Bullet* > m_pBullet_list;
}
When the player fires a Bullet, it is added to this list. Also, inside the constructor of bullet, a reference of the same object is updated in CollisionMg... | You are not storing bullets in these lists, but pointers to bullets, so no destructor will be called. The objects can be safely removed from all lists, but you will need to call delete yourself.
|
2,697,437 | 2,697,469 | Coordinate geometry operations in images/discrete space | I have images which have line segments, rays etc. I am representing these line segments using Bresenham algorithm (means whatever coordinates I get using this algorithm between two points). Now I want to do operations such as finding intersection point between two line segments, finding the projection of one vector on... | Bresenham is just a way to rasterise a geometric entity, and is used to avoid per-pixel floating-point operations. There's nothing stopping you from reverting to analytic geometry to find intersections.
|
2,697,516 | 2,721,081 | Unable to run DLL linked C++ exe. "This program cannot be run in DOS mode." error | I am trying to run a console C++ application linking with my DLL files from the command prompt in a XP windows machine. Recently I have started getting "This program cannot be run in DOS mode." as an error message. As I understand this is a filler message in all DLL's to print if this exe was invoked in a pure MS-DOS e... | First open the EXE with hex editor ,what u want to run .After open ,can u see the MZ signature at starting...if there is other than MZ ,there may be ,Exe is not a correct form....after this ,u can move next..
|
2,697,607 | 2,697,628 | Alias for a C++ template? | typedef boost::interprocess::managed_shared_memory::segment_manager
segment_manager_t; // Works fine, segment_manager is a class
typedef boost::interprocess::adaptive_pool
allocator_t; // Can't do this, adaptive_pool is a template
The idea is that if I want to switch between boost interprocess' several differ... | Yes, (if I understand your question correctly) you can "wrap" the template into a struct like:
template<typename T>
class SomeClass;
template<typename T>
struct MyTypeDef
{
typedef SomeClass<T> type;
};
and use it as:
MyTypeDef<T>::type
Edit: C++0x would support something like
template<typename T>
using MyType =... |
2,697,808 | 2,698,729 | boost::interprocess::message_queue stops working in Release mode with visual C++ | I am using boost::interprocess::message_queue, with VC++ (in Microsoft Visual Studio 2005).
It is working properly in Debug mode.
Then when I compile my program in Release mode it stops working, every time I call "try_send" it returns false.
I don't understand what could be the settings that are different between Relea... | It turns out that my Release version does not do as much logging as the debug one. The thread that accumulates the messages in the queue is quicker, which means that the other thread (which flushes the messages) does not catch up.
In the end the message queue if full.
I need to use timed_send to make so that the other ... |
2,697,862 | 2,708,820 | Setting existing cookies to use with libcurl | does current version of libcurl support firefox 3.0 and above cookies file (cookies.sqlite) ?
I'm trying to set the file to allow cookies to be used when retrieving the data from web address.
int return_val = curl_easy_setopt(hCurl, CURLOPT_COOKIEFILE, \..\cookies.sqlite);
return_val is zero but i don't get to see the... | You can try to parse the SQLite file.
However, there's addon for firefox that exports cookies in Netscape (*.txt) format.
https://addons.mozilla.org/en-US/firefox/addon/8154
|
2,697,930 | 2,697,953 | Hiding Mouse Pointer on window Screen using GDI in c++ | How to hide the mouse pointer on the window screen of GDI, kindly give me some hints.
| Try ShowCursor(false);
Sources:
http://msdn.microsoft.com/en-us/library/ms648396.aspx
http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0045.html
|
2,697,974 | 2,698,007 | How do I go about overloading C++ operators to allow for chaining? | I, like so many programmers before me, am tearing my hair out writing the right-of-passage-matrix-class-in-C++. I have never done very serious operator overloading and this is causing issues. Essentially, by stepping through
This is what I call to cause the problems.
cMatrix Kev = CT::cMatrix::GetUnitMatrix(4, true... | Your operators + and * must return by value, not by reference. You're returning a temporary variable by reference. Also, you're arguments are passed by value when it should be a const reference:
cMatrix cMatrix::operator+(cMatrix const& m)
{
cMatrix matrix(*this);
matrix += m;
return matrix;
}
cMatrix cMa... |
2,697,995 | 2,698,035 | Get time of execution piece of code | How do I get milliseconds time of execution of a piece of code in Qt/C++?
| Use the QTime class. Start it with .start() (or .restart()) and then check the amount of milliseconds passed with .elapsed(). Naturally, the precision ultimately depends on the underlying OS, although with the major platforms you should have no trouble getting a real millisecond resolution.
|
2,698,163 | 2,699,055 | Windows 7 UAC elevation | I have a single thread that I'd like to run as an administrator in my application. The rest of the application I can happily run as the default user level (asInvoker). Is this possible? I notice there is an "ImpersonateLoggedOnUser" function. Can I somehow use this to log the administrator on and then get the threa... | No, elevation is per process, not thread.
If the rest of the application has to run non-elevated, you could run yourself elevated with some parameter (myapp.exe /uac "ipcparamhere") and use some sort of Inter-process communication to communicate back to the "main instance" of your app. (If the elevated process only pe... |
2,698,172 | 2,698,415 | per process configurable core dump directory | Is there a way to configure the directory where core dump files are placed for a specific process?
I have a daemon process written in C++ for which I would like to configure the core dump directory. Optionally the filename pattern should be configurable, too.
I know about /proc/sys/kernel/core_pattern, however this wou... | No, you cannot set it per process. The core file gets dumped either to the current working directory of the process, or the directory set in /proc/sys/kernel/core_pattern if the pattern includes a directory.
CoreDumpDirectory in apache is a hack, apache registers signal handlers for all signals that cause a core dump ,... |
2,698,261 | 2,704,246 | How to use QSerialDevice in Qt? | I am trying to use QSerialDevice in Qt to get a connection to my serial port. I also tried QextSerialPort before (which works on Windows Vista but unfortunately not on Windows XP ..) but I need an API which supports XP, Vista and Win7...
I build the library and configured it this way:
CONFIG += dll
CONFIG +... | Tobias,
try use from SVN:
svn checkout svn://scm.fireforge.net/svnroot/qserialdevice
|
2,698,474 | 2,698,775 | design patterns used in STL(standard template library) | I am learning STL and design patterns .
i wanted to know is there any document or link that explains how design patterns are implemented in STL
i did the google but not able to get much data
| I hope you mean, "which design patterns can be identified in the STL".
The STL stack is a container adapter. An adapter is a design pattern. The iterator is also a design pattern. The STL function objects are related to the command pattern.
Patterns:
Adapter (container adapters)
stack
queues
priority queues
Iterato... |
2,698,842 | 2,700,004 | C++ Windows IOCP - HTTP POST data missing | I have written a very simple IOCP HTTP server that works for the GET verb, but not POST.
I create a socket and a listen thread in which accept() is waiting for a connection.
When a client connects I call ioctlsocket() to unblock the socket then I associate the socket with IOCP and finally call WSARecv() to read the dat... | All reads on a TCP socket will return anywhere between 1 byte and the total amount sent depending on the buffer size of the buffer that you supply. What's likely happening is that the web server is sending the data as two separate writes and this happens to be being transmitted by the server's TCP stack as two separate... |
2,699,060 | 2,699,091 | How can I sort an STL map by value? | How can I implement STL map sorting by value?
For example, I have a map m:
map<int, int> m;
m[1] = 10;
m[2] = 5;
m[4] = 6;
m[6] = 1;
I'd like to sort that map by m's value. So, if I print the map, I'd like to get the result as follows:
m[6] = 1
m[2] = 5
m[4] = 6
m[1] = 10
How can I sort the map in this way? Is there ... | You can build a second map, with the first map's values as keys and the first map's keys as values.
This works only if all values are distinct. If you cannot assume this, then you need to build a multimap instead of a map.
|
2,699,102 | 2,700,603 | CDateTimeCtrl - preventing 'focus' change when setting date | I'd like to use a CDateTimeCtrl to allow the user to select a non-weekend date. So, if the user increments the day (via a keypress) - and the resulting day is found to fall on a weekend - then the control should skip forward to the following Monday (don't let issues about month changes distract you, it's not relevant).... | Not sure, but one possible workaround:
keybd_event(VK_RIGHT, 0, 0, NULL);
keybd_event(VK_RIGHT, 0, KEYEVENTF_KEYUP, NULL);
|
2,699,155 | 2,699,224 | Binder and variadic template ends up in a segmentation fault | I wrote the following program
#include <iostream>
template<typename C, typename Res, typename... Args>
class bind_class_t {
private:
Res (C::*f)(Args...);
C *c;
public:
bind_class_t(Res (C::*f)(Args...), C* c) : f(f), c(c) { }
Res operator() (Args... args) {
return (c->*f)(args...);
}
};
template<typenam... | You need perhaps
return bind_class_t<C, Res, Args...>(f, c);
instead of
return bind_class<C, Res, Args...>(f, c);
Otherwise you'll get endless recursion.
|
2,699,336 | 2,699,363 | Function template overloading: link error | I'm trying to overload a "display" method as follows:
template <typename T> void imShow(T* img, int ImgW, int ImgH);
template <typename T1, typename T2> void imShow(T1* img1, T2* img2, int ImgW, int ImgH);
I am then calling the template with unsigned char* im1 and char* im2:
imShow(im1, im2, ImgW, ImgH);
This compile... | You probably forgot to define your template function properly. Where are the definitions? I don't see any in your post.
|
2,699,411 | 2,699,521 | How is application virtualization implemented? | I am trying to understand how software like App-V and sandboxie (http://www.sandboxie.com/) work. But for the life of me, I can't think of anything that could make this possible. How do they intercept API calls and trick the target software? If someone would say that it's just magic and pixie dust, I would believe them... | Sandboxie does it by essentially injecting code into core Windows API, the same way a virus would (which is why Vista x64 prevents this behaviour, and why Sandboxie doesn't work on that OS).
Here is a project explaining API hooking. I learned how all this work by studying the sourcecode for Metamod:Source (used for So... |
2,699,443 | 2,699,467 | C++ change sort method |
Possible Duplicate:
C++ struct sorting
Is it possible to sort a vector in C++ according to a specified sorting method, like used in Java's Collections.sort that takes a Comparator?
| Yes. See the answers to this question from this morning: C++ struct sorting
|
2,699,484 | 2,699,495 | Random number generation | I am using below code to generate random numbers in range...
int randomNumberWithinRange(int min,int max)
{
int snowSize = 0;
do
{
snowSize = rand()%max;
}
while( snowSize < min || snowSize > max );
return snowSize;
}
for(int i = 0; i < 10 ; i++)
NSlog... | Do something like for example srand(time(NULL)), i.e. sync it with time (in the initialisation of your program, of course).
|
2,699,534 | 2,699,545 | How to convert int* to int | Given a pointer to int, how can I obtain the actual int?
I don't know if this is possible or not, but can someone please advise me?
| Use the * on pointers to get the variable pointed (dereferencing).
int val = 42;
int* pVal = &val;
int k = *pVal; // k == 42
If your pointer points to an array, then dereferencing will give you the first element of the array.
If you want the "value" of the pointer, that is the actual memory address the pointer contai... |
2,699,642 | 2,700,300 | How should I compare pairs of pointers (for sort predicate) | I have a STL container full of billions of the following objects
pair<SomeClass*, SomeClass*>
I need some function of the following form
/*returns items sorted biggest first */
bool sortPredicate (pair<SomeClass*, SomeClass*>two, pair<SomeClass*, SomeClass*> one)
{
return ???;
}
Is there some trick I can use to v... | It is a quirk of C++ that arbitrary pointers of the same type are not (necessarily) comparable with <, but are comparable with std::less.
Unfortunately, the operator< for std::pair is defined in terms of operator< on the components, not std::less.
So, assuming that you want two pairs to fall in the same sort position i... |
2,699,680 | 2,699,711 | std::list iterator: get next element | I'm trying to build a string using data elements stored in a std::list, where I want commas placed only between the elements (ie, if elements are {A,B,C,D} in list, result string should be "A,B,C,D".
This code does not work:
typedef std::list< shared_ptr<EventDataItem> > DataItemList;
// ...
std::string Compose(DataIte... | You cannot do it + N because you have no random access for list iterators. You can only do one step at a time with list iterators (these are bidirectional iterators).
You can use boost::next and boost::prior
// Lookahead in list to see if next element is end
if(boost::next(iterItems) == dilList.end())
{
Or you can ... |
2,699,988 | 2,700,181 | Best environment to port C/C++ code from Linux to Windows | I'd like to make a big project of mine buildable on Windows platforms.
The project itself it's written in C/C++ following POSIX standards, with some library dependencies such as libxml2, libcurl and so on.
I'm more a Linux developer rather than a Windows developer, so i have no idea of which compiler suite i should use... | If it were me, I would install the following:
MinGW port of the GCC compiler from Twilight Dragon (this is only at 4.4.1 at present, but I'd guess it will meet your needs, and I've found it to be very reliable)
The MSYS environment (bash etc. for Windows) from http://sourceforge.net/apps/mediawiki/cobcurses/index.php?... |
2,699,993 | 2,700,265 | Using pthread condition variable with rwlock | I'm looking for a way to use pthread rwlock structure with conditions routines in C++.
I have two questions:
First: How is it possible and if we can't, why ?
Second: Why current POSIX pthread have not implemented this behaviour ?
To understand my purpose, I explain what will be my use: I've a producer-consumer model d... | I assume that by "conditions", you mean "conditional variables". They're different things.
No, you cannot use a rwlock when waiting on a conditional variable. I cannot answer as to the "why", but that's the way POSIX has decided to do it. Perhaps just to keep things simple.
You can still get the behavior you want, howe... |
2,700,087 | 2,700,097 | Why does this hex value get output as a negative number? | char buffer_b[5] = { 0xDA, 0x00, 0x04, 0x00, 0x07 };
printf("%d\n%d\n%d", buffer_b[0], buffer_b[2], buffer_b[4]);
This gives me output:
-38
4
7
However I am expecting:
218
4
7
Thanks.
| char is signed. Use unsigned char.
use %ud also.
|
2,700,195 | 2,700,520 | Write a MAT file without using matlab headers and libraries | I have some data that I would like to save to a MAT file (version 4 or 5, or any version, for that matter). The catch: I wanted to do this without using matlab libraries, since this code will not necessary run in a machine with matlab. My program uses Java and C++, so any existing library in those languages that achiev... | C: matio
Java: jmatio
(I'm really tempted to, so I will, tell you to learn to google)
But really, it's not that hard to write matfiles using fwrite if you don't need to handle some of the more complex stuff (nested structs, classes, functions, sparse matrix, etc).
See: http://www.mathworks.com/access/helpdesk/help/pdf_... |
2,700,396 | 2,702,040 | How to get the next prefix in C++? | Given a sequence (for example a string "Xa"), I want to get the next prefix in order lexicographic (i.e "Xb"). The next of "aZ" should be "b"
A motivating use case where this function is useful is described here.
As I don't want to reinvent the wheel, I'm wondering if there is any function in C++ STL or boost that can ... | I'm not sure I understand the semantics by which you wish the string to transform, but maybe something like the following can be a starting point for you. The code will increment the sequence, as if it was a sequence of digits representing a number.
template<typename Bi, typename I>
bool increment(Bi first, Bi last, I ... |
2,700,786 | 2,700,803 | Base class pointer vs inherited class pointer? | Suppose I have a class Dog that inherits from a class Animal. What is the difference between these two lines of code?
Animal *a = new Dog();
Dog *d = new Dog();
In one, the pointer is for the base class, and in the other, the pointer is for the derived class. But when would this distinction become important? F... | For all purposes of type-checking, the compiler treats a as if it could point to any Animal, even though you know it points to a Dog:
You can't pass a to a function expecting a Dog*.
You can't do a->fetchStick(), where fetchStick is a member function of Dog but not Animal.
Dog *d2 = dynamic_cast<Dog*>(d) is probably j... |
2,700,902 | 2,701,032 | How to correctly inherit std::iterator | Guys if I have class like below:
template<class T>
class X
{
T** myData_;
public:
class iterator : public iterator<random_access_iterator_tag,/*WHAT SHALL I PUT HERE? T OR T** AND WHY?*/>
{
T** itData_;//HERE I'M HAVING THE SAME TYPE AS MAIN CLASS ON WHICH ITERATOR WILL OPERATE
};
};
Questions are in code next to appr... | As a starting point, your value type should be the type of object your container holds. My guess would be either T or T*, you don't really provide enough information to say. See here for an explanation of what the various parameters mean. The rest can often be left as defaults.
|
2,700,940 | 2,700,976 | avoiding the tedium of optional parameters | If I have a constructor with say 2 required parameters and 4 optional parameters, how can I avoid writing 16 constructors or even the 10 or so constructors I'd have to write if I used default parameters (which I don't like because it's poor self-documentation)? Are there any idioms or methods using templates I can use... | You might be interested in the Named Parameter Idiom.
To summarize, create a class that holds the values you want to pass to your constructor(s). Add a method to set each of those values, and have each method do a return *this; at the end. Have a constructor in your class that takes a const reference to this new clas... |
2,701,092 | 2,715,173 | c++ property class structure | I have a c++ project being developed in QT. The problem I'm running in to is I am wanting to have a single base class that all my property classes inherit from so that I can store them all together. Right now I have:
class AbstractProperty
{
public:
AbstractProperty(QString propertyName);
... | Another solution is to use the Curiously Recurring Template Pattern. This allows a templated class to define comparison operators based on a derived class.
Example:
template <class Descendant>
struct Numeric_Field
{
Descendant m_value;
bool operator==(const Descendant& d)
{
return m_value =... |
2,701,235 | 2,701,252 | Help me to understand the termination parameter of this C++ for loop | I do not understand the termination parameter of this for loop. What does it mean? Specifically, what do the ?, ->, and : 0 represent?
for( i = 0; i < (sequence ? sequence->total : 0); i++ )
| This: (sequence ? sequence->total : 0) (it's called a "ternary if", since it takes three inputs) is like saying:
if (sequence)
replaceEntireExpressionWith(sequence->total);
else
replaceEntireExpressionWith(0);
-> is a dereferencer, just like *, but it makes user data-types like structs easy to use.
sequence->t... |
2,701,279 | 2,701,354 | Why can't I sort this container? | Please don't mind that there is no insert fnc and that data are hardcoded. The main purpouse of it is to correctly implement iterator for this container.
//file Set.h
#pragma once
template<class T>
class Set
{
template<class T>
friend ostream& operator<<(ostream& out, const Set<T>& obj);
private:
T** myDat... | Your code is unfortunately a complete mess.
What prohibits it from compiling is probably the following:
class iterator : public std::iterator<std::random_access_iterator_tag, T*>
This says that when you perform *iterator, it yields a T*. But look at what operator* actually returns:
T operator*() const
I can make it c... |
2,701,470 | 2,701,946 | Simple, Custom Parsing with c++ | I have been reading SO for some time now, but I truly cannot find any help for my problem.
I have a c++ assignment to create an IAS Simulator.
Here is some sample code...
0 1 a
1 2 b
2 c
3 1
10 begin
11 . load a, subtract b and offset by -1 for jump+
11 load M(0)
12 sub M(1)
13 sub M(3)
14 halt
Using... | Splitting the leading number and the rest of the line is not too difficult of a task. Use something like getline to read one line at a time from your input file, and store the line in a string char cur_line[]. For each line, try something like this:
Declare a pointer char* pString and an integer int line_num
Use th... |
2,701,539 | 2,701,587 | Crash the program with cmd line args | Lets us consider the following program :
#include <stdlib.h>
int main(int argc, char **argv){
int a,b;
if (argc != 3)
return -1;
a = atoi(argv[1]);
b = atoi(argv[2]);
a = b ? a/b : 0;
return a;
}
The task is to crash the program by providing arguments in command-line.
| Pass a as the platform's INT_MIN and b as -1. Then you get an overflow error on any two's complement machine, although that's not necessarily a crash.
|
2,701,560 | 2,704,937 | Qt as a true multi-platform dev-env | Inspired by the maturity problems I am facing porting on Mono Mac & Linux. I am investigating the use of Qt as an alternative. I am curious to hear about your favorite Qt experiences, tips or lesser known but useful features you know of.
Please, include only one experience per answer.
| I've used Qt 4.5 & 4.6 for some applications such as TCP/IP game with a uCsimm and a shooting game with graphics. Qt made my life easy as I need to write code once and have it running on Windows, Linux & Mac.
A free & quality book to start with: http://cartan.cas.suffolk.edu/oopdocbook/opensource/ .
Qt may not have all... |
2,701,774 | 2,701,833 | Pruning: When to Stop? | When does pruning stop being efficient in a depth-first search? I've been working on an efficient method to solve the N-Queens problem and I'm looking at pruning for the first time. I've implemented it for the first two rows, but when does it stop being efficient? How far should I prune to?
| The N-Queens problem is typically recursive. Implementing pruning at one depth should mean implementing it at any depth.
The answer would depend on what sort of pruning you're doing. If you're pruning for symmetric moves, then it's not worth pruning when the cost of checking is more than the cost of evaluating a whole... |
2,701,860 | 2,701,926 | Add newline to a text field (Win32) | I'm making a Notepad clone. Right now my text loads fine but where their are newline characters, they do not make newlines in the text field.
I load it like this:
void LoadText(HWND ctrl,HWND parent)
{
int leng;
char buf[330000];
char FileBuffer[500];
memset(FileBuffer,0,500);
FileBuffer[0] = '*'... | Ensure that you have ES_MULTILINE|ES_WANTRETURN set.
Multiline edit controls use "soft line break characters" to force it to wrap. To indicate a "soft line break", use CRCRLF (source). So I guess you need to replace all your CRLF's (or whatever eol character your file uses) with CRCRLF. You're already reading your f... |
2,701,974 | 2,701,994 | std::basic_string full specialization (g++ conflict) | I am trying to define a full specialization of std::basic_string< char, char_traits<char>, allocator<char> > which is typedef'd (in g++) by the <string> header.
The problem is, if I include <string> first, g++ sees the typedef as an instantiation of basic_string and gives me errors. If I do my specialization first the... | You are only allowed to specialize a standard library if the specialization depends on a user-defined name with external linkage. char doesn't meet this requirement and you are getting undefined behaviour.
This is specified in 17.4.3.1 [lib.reserver.names]/1.
The particular error that you are getting is because your im... |
2,702,097 | 2,702,108 | Recipes/tutorials/libraries for GUI-like terminal navigation (vim/lynx-style)? | Several console based applications like vim or lynx offer a rich user interface which enables the user to navigate freely around the console, manipulate data directly on screen, access menus and much more, similar to "modern" gui applications.
How is that being achieved in principal on Unix/Linux with C++? Do you direc... | The ncurses library.
|
2,702,157 | 2,702,205 | Get list of fonts (Win32) | I want to make a combo box with all of the computer's installed fonts enumerated in it. I'm not sure how this is done. Do I need to access the registry to get this?
Thanks
| You should use the Win32 API function EnumFontFamiliesEx. You call that function, passing a callback function matching the type of EnumFontFamExProc. The callback function is called once for every font found by EnumFontFamiliesEx.
I'd recommend using the unicode version (EnumFontFamiliesExW), as I've seen the ascii ver... |
2,702,167 | 2,702,217 | C++ - Breaking code implementation into different parts | The question plot (a bit abstract, but answering this question will help me in my real app):
So, I have some abstract superclass for objects that can be rendered on the screen. Let's call it IRenderable.
struct IRenderable {
// (...)
virtual void Render(RenderingInterface& ri) = 0;
virtual ~IRenderable() { }
};
... | My understanding and recollection from when I dinked with graphic programming is the Visitor is indeed appropriate.
|
2,702,386 | 2,702,511 | Squigglly line under a word (Win32) | I want to implement basic spell checking in a Notepad clone project I'm doing. I want to underline misspelled words with a squiggly like like Word does. I think I need to use GDI and draw on the text field, but I'm not sure how to draw on controls.
Thanks
| If you're basing your editor on an edit control (as Notepad does), then I think it's going to be difficult. By subclassing the edit control window, you could probably augment its WM_PAINT handling. But the problem is the control doesn't expose a way for you to find out exactly where a word appears within the control.... |
2,702,487 | 2,702,517 | Linked List pop() function | Consider the following list:
[LinkNode * head -- LinkNode * node1 -- LinkNode * node2]
I'm creating a stack of FIFO.
I Call pop() which I want to pop node1.
LinkNode::LinkNode(int numIn) {
this->numIn = numIn;
next = null;
}
.
.
.
int LinkNode::pop() {
Link * temp = head->next;
head = temp->next;
... |
LinkNode * is a pointer. So I'm not sure what you are asking.
The variable goes out of scope but this does not automatically remove the dynamically allocated data. In C++, if you dynamically allocate data (call new) you need to free it (call delete)
|
2,702,561 | 2,702,666 | Update Text Field after font change (Win32) | After I use setcontrolfont, the text of the text field does not update. The onnly way I fixed this is by removing then readding all text but this seems hackish. How can I do it properly?
Thanks
*its a function I made:
void SetControlFont(HWND hand, int size, char* name)
{
HGDIOBJ hfDefault;
hfDefault = (HGDIOB... | SendMessage(hand, WM_SETFONT, (WPARAM)hfDefault, MAKELPARAM(FALSE, 0))
The MAKELPARAM(FALSE, 0) is telling the window that it should not redraw itself. Have you tried using MAKELPARAM(TRUE, 0) instead?
If you do not want to change the SetControlFont function, you could tell the text field to redraw itself after call... |
2,702,632 | 2,702,653 | Why isn't the compiler smarter in this const function overloading problem? | The following code does not compile:
#include <iostream>
class Foo {
std::string s;
public:
const std::string& GetString() const { return s; }
std::string* GetString() { return &s; }
};
int main(int argc, char** argv){
Foo foo;
const std::string& s = foo.GetString(); // error
return 0;
}
I get the follow... | I can't recall exactly why they don't allow overloading on return type (I think it's because return values can be discarded and thus the function wouldn't be distinct), but you can fix the problem with a const_cast hint to the compiler:
const std::string& s = const_cast<const Foo&>(foo).GetString();
|
2,702,638 | 2,702,651 | Function equivalent to sprintf() with maximum number of characters to be copied? | function(char* name)
{
char sql[50];
sprintf(sql, "select %s;", name);
}
What's the best way to make sure only 50 chars of name are copied to sql in the case name is larger than what sql can hold? (sprintf with a N parameter?)
Thank You.
| There is snprintf, which also takes a size parameter:
int snprintf(char *str, size_t size, const char *format, ...);
|
2,702,750 | 2,702,755 | pointer and reference question (linked lists) | I have the following code
struct Node {
int accnumber;
float balance;
Node *next;
};
Node *A, *B;
int main() {
A = NULL;
B = NULL;
AddNode(A, 123, 99.87);
AddNode(B, 789, 52.64);
etc…
}
void AddNode(Node * & listpointer, int a, float b) {
// add a new node to the FRONT of the list
Node *temp;
tem... | Node * &foo is a reference to a Node *
So when you call it with
AddNode(A, 123, 99.87);
it will change A.
|
2,702,853 | 2,703,437 | Direct access to harddrive? | I was wondering how hard disk access works. Ex, how could I view/modify sectors? Im targeting Windows if that helps.
Thanks
| This page seems to have some relevant information on the subject:
You can open a physical or logical
drive using the CreateFile()
application programming interface
(API) with these device names provided
that you have the appropriate access
rights to the drive (that is, you must
be an administrator). You mu... |
2,702,918 | 2,704,536 | Is a signal sent with kill to a parent thread guaranteed to be processed before the next statement? | Okay, so if I'm running in a child thread on linux (using pthreads if that matters), and I run the following command
kill(getpid(), someSignal);
it will send the given signal to the parent of the current thread.
My question: Is it guaranteed that the parent will then immediately get the CPU and process the signal (kil... | Signals get delivered asynchronously, so you can't expect the thread handling them to handle them immediately; moreover, it will have to do some work to handle it.
And if a sigprocmask() call had masked the signal in all threads, the signal will only be acted upon after it is unmasked.
Signals don't go to any particula... |
2,703,015 | 2,703,053 | O(log n) algorithm to find the element having rank i in union of pre-sorted lists | Given two sorted lists, each containing n real numbers, is there a O(log n) time algorithm to compute the element of rank i (where i coresponds to index in increasing order) in the union of the two lists, assuming the elements of the two lists are distinct?
EDIT:
@BEN: This i s what I have been doing , but I am still ... | Yes:
You know the element lies within either index [0,i] of the first list or [0,i] of the second list. Take element i/2 from each list and compare. Proceed by bisection.
I'm not including any code because this problem sounds a lot like homework.
EDIT: Bisection is the method behind binary search. It works like this... |
2,703,101 | 2,703,111 | Main Function Error C++ | I have this main function:
#ifndef MAIN_CPP
#define MAIN_CPP
#include "dsets.h"
using namespace std;
int main(){
DisjointSets s;
s.uptree.addelements(4);
for(int i=0; i<s.uptree.size(); i++)
cout <<uptree.at(i) << endl;
return 0;
}
#endif
And the following class:
class DisjointSets
{
public:
void addele... | You can't access a private element of a class from outside the class. Try making uptree public, or provide a means to access it through DisjointSets. Also, addelements() is a member of class DisjointSets, not vector uptree.
#ifndef MAIN_CPP
#define MAIN_CPP
#include "dsets.h"
using namespace std;
int main(){
Disjoi... |
2,703,435 | 2,703,501 | Sockets and multithreading | I have an interesting (to me) problem... There are two threads, one for capturing data from std input and sending it through socket to server, and another one which receives data from blocking socket. So, when there's no reply from server, recv() call waits indefenitely, right? But instead of blocking only its calling ... | You are holding the nvtMutex inside the call to NVT::recv. Since both threads need to lock the mutex to make it through an iteration, until NVT::recv returns the other thread can't progress.
Without knowing the details of this NVT class, it's impossible to know if you can safely unlock the mutex before calling NVT::re... |
2,703,516 | 2,703,630 | How do you perform macro expansion within #ifdef? | I have some fairly generic code which uses preprocessor macros to add a certain prefix onto other macros. This is a much simplified example of what happens:
#define MY_VAR(x) prefix_##x
"prefix_" is actually defined elsewhere, so it will be different each time the file is included. It works well, but now I have some... | Is there more to your program than this question describes? The directive
#define MY_VAR(x) prefix_##x
defines exactly one preprocessor identifier. The call
blah ^&* blah MY_VAR(hello) bleh <>? bleh
simply goes in one end of the preprocessor and comes out the other without defining anything.
Without some other magic ... |
2,703,528 | 2,703,668 | What code have you written with #pragma you found useful? | I've never understood the need of #pragma once when #ifndef #define #endif always works.
I've seen the usage of #pragma comment to link with other files, but setting up the compiler settings was easier with an IDE.
What are some other usages of #pragma that is useful, but not widely known?
Edit:
I'm not just after a li... | Every pragma has its uses, or they wouldn't be there in the first place.
pragma "once" is simply less typing and tidier, if you know you won't be porting the code to a different compiler. It should be more efficient as well, as the compiler will not need to parse the header at all to determine whether or not to include... |
2,703,629 | 2,703,713 | How to open a .a file | I've a little problem: I have to open a linker file that has .a extension. I use Dev-C++.
| .a files are ar archives (something like zip archives) of object (.o) files. You can list files in .a file using ar program:
ar t file.a
And extract all files:
ar x file.a
|
2,703,716 | 2,703,877 | Performance of Serialized Objects in C++ | I'm wondering if there is a fast way to dump an STL set to disk and then read it back later.
The internal structure of a set is a binary tree, so if I serialize it naively, when I read it back the program will have to go though the process of inserting each element again. I think this is slow even if it is read back i... | As each set element is somewhere on the heap, you cannot just dump the structure to disk. You therefore need a proper serialization routine that goes through each element.
To read the element back again, you can use "hints", which allow you to hint to the insert method where the element should be inserted. This can bri... |
2,704,167 | 2,705,080 | Type Declaration - Pointer Asterisk Position | in C++, the following means "allocate memory for an int pointer":
int* number;
So, the asterisk is part of the variable type; without it, that would mean "allocate memory for an int".
Then, wouldn't it make more sense if the following meant "allocate memory for two int pointers"?
int* number1, number2;
| Stroustrup was asked this and he said (paraphrasing)
if you think more C-ish you will say int *a and Employee *pE
(so in your head you're thinking "the content of a is an integer")
if you think more C++-ish you will say int* a and Employee* pE
(so in your head it's "a is an integer pointer")
You can think howe... |
2,704,521 | 2,704,552 | generate random double numbers in c++ | How to generate random numbers between two doubles in c++ , these numbers should look like xxxxx,yyyyy .
| Here's how
double fRand(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
Remember to call srand() with a proper seed each time your program starts.
[Edit]
This answer is obsolete since C++ got it's native non-C based random library (see Alessandro Jacopsons a... |
2,704,606 | 2,711,375 | Handling wm_mousewheel message in WTL | I am trying to handle wm_mousewheel for my application.
Code:
BEGIN_MSG_MAP(DxWindow)
MESSAGE_HANDLER(WM_MOUSEWHEEL, KeyHandler)
END_MSG_MAP()
.
.
.
LRESULT DxWindow::KeyHandler( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled )
{
if(uMsg==wm_mousewheel)
{
//Perform task.
}
r... | From the doc:
The WM_MOUSEWHEEL message is sent to the focus window when the mouse wheel is rotated. The DefWindowProc function propagates the message to the window's parent. There should be no internal forwarding of the message, since DefWindowProc propagates it up the parent chain until it finds a window that process... |
2,704,704 | 2,704,886 | Moving inserted container element if possible | I'm trying to achieve the following optimization in my container library:
when inserting an lvalue-referenced element, copy it to internal storage;
but when inserting rvalue-referenced element, move it if supported.
The optimization is supposed to be useful e.g. if contained element type is something like std::vector... | I think you may need to forward the argument:
template <typename Arg>
void do_insert (Arg&& arg)
{ element x (std::forward<Arg>(arg)); }
Full code:
#include <iostream>
#include <utility>
struct element
{
element () { };
element (const element&) { std::cerr << "copying\n"; }
element (element&&) { std:... |
2,704,899 | 2,704,927 | ISO C++ forbids declaration of 'QPushButton' with no type in QT Creator | I am running QT Creator on a Linux Ubuntu 9.10 machine. I just got started with QT Creator, and I was going through the tutorials when this error popped up while I was trying to build my project: "ISO C++ forbids declaration of 'QPushButton' with no type". This problem appears in my header file:
#ifndef MAINWINDOW_H
#d... | I think you are simply missing the appropriate header file. Can you try
#include <QtGui/QtGui>
instead, or if you prefer
#include <QtGui/QPushButton>
|
2,705,126 | 2,726,096 | Difference among STLPort and SGI STL | Recently, I was buzzed by the following problem STL std::string class causes crashes and memory corruption on multi-processor machines while using VC6.
I plan to use an alternative STL libraries instead of the one provided by VC6.
I came across 2 libraries : STLPort and SGI STL
I was wondering what is the difference be... | Here is the story behind the relation of STLPort and SGI STL
http://stlport.sourceforge.net/History.shtml
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.