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(){
object_list.clear();
object_list.push_back(DerivedClass1());
object_list.push_back(DerivedClass2());
or...
class World{
vector<ObjectBaseClass*> object_list;
public:
void generate(){
object_list.clear();
object_list.push_back(new DerivedClass1());
object_list.push_back(new DerivedClass2());
?? Would be using pointers in the 2nd example to create new objects defeat the point of using vectors, because vectors automatically call the DerivedClass destructors in the first example but not in the 2nd? Are pointers to new objects necessary when using vectors because they handle memory management themselves as long as you use their access methods? Now let's say I have another method in world:
void drawfrom(Viewport& view){
for (unsigned int i=0;i<object_list.size();++i){
object_list.at(i).draw(view);
}
}
When called this will run the draw method for every object in the world list. Let's say I want derived classes to be able to have their own versions of draw(). Would the list need to be of pointers then in order to use the method selector (->) ?
| 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 vector of ObjectBaseClass.
To make polymorphism work You have to use some kind of pointers. There are probably some smart pointers or references in boost or other libraries that can be used and make the code much safer than the second proposed solution.
|
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 size_type. Often, some function will call size() and pass that value on to another function and that one will use it and maybe pass it on. Now everyone has to include that Foo header, although I'm really just passing some size value around, which should just be unsigned int anyway ...? What is the right thing to do here? Is it best practice to really use size_type everywhere?
| 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 can work with a very small size_type and ptr_type - which is a relevant optimization on many architectures.
At least, that were the design goals, also driven by anticipation what could be platforms supporting C++. Some early concessions also allowed shortcuts for STL implementers that basically disable this flexibility, and I've never worked with an STL implementation that made use of this. I'd say that's because linear memory access has become much less of a problem, and STL development at that level isn't actually easy.
Still, how much does it hurt you? It would be the right thing to do.
|
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 that a good compiler can remove the recursion, transforming it into a loop. This may be faster and will certainly save on stack usage. The GCC compiler can do this optimisation.
|
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("Configuration file empty"), path);
// ...
}
When I compile I get this (I cropped file names for readability) :
/usr/bin/g++ -g -I/home/shtong/Dev/OmegaNoc/build -I/usr/share/include/boost-1.41.0 -o CMakeFiles/OmegaNocInternals.dir/configuration/localNodeConfiguration.cxx.o -c /home/shtong/Dev/OmegaNoc/source/configuration/localNodeConfiguration.cxx
.../localNodeConfiguration.cxx: In static member function ‘static OmegaNoc::LocalNodeConfiguration* OmegaNoc::LocalNodeConfiguration::ReadFromFile(std::string&)’:
.../localNodeConfiguration.cxx:72: error: no matching function for call to ‘OmegaNoc::configuration_file_error::configuration_file_error(std::string, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)’
.../configurationManager.hxx:25: note: candidates are: OmegaNoc::configuration_file_error::configuration_file_error(std::string&, std::string&)
.../configurationManager.hxx:22: note: OmegaNoc::configuration_file_error::configuration_file_error(const OmegaNoc::configuration_file_error&)
So as I understand it, the compiler is considering that my path parameter turned into a basic_string at some point, thus not finding the constructor overload I want to use. But I don't really get why this transformation happened.
Some search on the net suggested me to use g++ but I was already using it. So any other advice would be appreciated :)
Thanks
| 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 reference. You either need to change the prototype to accept const references or just pass-by-value:
f(const string&, string&) {
//----^^^^^^
or
f(string, string&) {
Or provide a mutable reference (if you really need to modify the 1st argument in that function):
string s = "blah blah blah";
f(s, path);
|
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 exist.
I am trying to avoid coding Java on the server and coding JavaScript on client.
| 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 POST and serialize your payload by pushing it into a JSONObject and calling toJSON();
C++ side..
Find a favorite JSON library (may I suggest from the fine choices at http://www.json.org/)
(You'll have to build a method dispatching scheme, but if your app is simple, just use some simple if ()'s)
Send back a response with mime-type of text/javascript;charset=UTF-8.
Back in your GWT code, you read back the results using something like so:
if (Response.SC_OK == response.getStatusCode()) {
try {
String txtResponse = response.getText();
if (txtResponse != null && txtResponse.length() > 0) {
JSONObject result = (JSONObject)JSONParser.parse(testResponse);
//Do something useful...
}
} catch (......)
Now you can talk back and forth with no magic. (And goodness know, no WDSL!!!)
|
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::move (A ());
A x; x = A ();
but neither of the following does:
B x (std::move (B ());
B x; x = B ();
In case it matters, I tested with GCC 4.4.
EDIT: Later test with GCC 4.5 showed the same behavior.
| 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 in the list, I look at the above api, I don't see a way to get inuse[2];
How can I remove an element in the list? There is an erase(), but how can I use it to remove element #2? And after I remove element 2? will STL list fill the erased spot automatically? e.g. #3 will become #2, #4 will become #3 and so on?
Thank you.
| 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 (myvector.begin()+5);
// erase the first 3 elements:
myvector.erase (myvector.begin(),myvector.begin()+3);
But if you need to delete many objects 1 by 1, and there cannot be 2 objects that are the same in the list, you can try to use std::map. Use some unique property of object as a key, and object itselt as value (or object itself a key, and true as value). It also has similar random access operator [] and erase() function.
|
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*> stopButton,restartButton;
QVector<QProcess*> proc;
QSignalMapper *stateSignalMapper, *stopSignalMapper, *restartSignalMapper;
public slots:
void openSettings();
void startRunning();
void statusChange(int);
void stopProc(int);
void restartProc(int);
void renew();
};
class SWindow : public QWidget
{
Q_OBJECT
public:
SWindow(QWidget *parent=0);
void readConfig();
void addLine(int);
private:
QVector<QPushButton*> selectButton;
QVector<QLabel*> filePath;
QVector<QLineEdit*> alias;
QSignalMapper *selectSignalMapper;
QVector<QSpinBox*> delay;
QGridLayout *mainLayout;
public slots:
void selectFile(int);
void saveFile();
void addLineSlot();
};
when i create and display SWindow object from mainWindow like this
void mainWindow::openSettings()
{
config = new SWindow();
config->show();
}
everything is ok, but now i need to access the mainWindow from SWindow, and
void mainWindow::openSettings()
{
config = new SWindow(this);
config->show();
}
doesn't display SWindow. How can i display SWindow?
How do i call a function on widget close?
| 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.
As for calling a function on widget close : you could reimplement closeEvent().
|
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 infected with a given serotype, but I'm not sure how:
Ideally, Boost MultiIndex would allow me to sort, for example, by Host::isInfected( int s ), where s is the serotype of interest. From what I understand, MultiIndex key extractors aren't allowed to take arguments.
An alternative would be to define an index for each serotype, but I don't see how to write the MultiIndex container typedef ... in such an extensible way. I will be changing the number of serotypes between simulations. (Do experienced programmers think this should be possible? I'll attempt it if so.)
There are 2^(NUM_SEROTYPES) possible infection statuses. For small numbers of serotypes, I could use a single index based on this number (or a binary string) and come up with some mapping from this key to actual infection status. Counting is still darn slow.
I could maintain a separate structure counting the total numbers of infecteds with each serotype. The synchrony is a bit of a pain, but the memory is fine. I would prefer a slicker option, since I would like to do further sorts on other host attributes (e.g., after counting the number infected with serotype s, count the number of those infected who are also in a particular household and have a particular age).
Thanks in advance.
Update
I'm going to be traveling and unable to check up on any answers until Wednesday, May 5. This means that whoever's answer is most popular, according to others' votes, will win the bounty (assuming some minimum threshold is met)--I will not be back in time to select what I think is the best answer. Please assume for the purpose of this bounty that NUM_SEROTYPES ~8-10, so I do not want to go with the third option or anything requiring some awful combinatoric enumeration. I'm really hoping to find a way to sort the MultiIndex on the host's infection status with respect to a given serotype.
Also, if this is a stupid question, I'd love to know why. Thanks.
Update 2, May 6
These replies are helpful and help me understand my options as I continue to optimize and customize the program. I'm unable to award the bounty or solution at this point, but if I could, it would go to outis for providing the most thorough and informative solution.
My current strategy will be to maintain int allInfecteds[ ALL_AGES ][ NUM_SEROTYPES ]. Maintenance of the array will be built into event definitions (e.g., for dying, recovering, aging, and becoming infected). Getting the total number of infected household members in a particular age will be done by individually querying hosts after sorting the MultiIndex by the household of interest. (Households are extremely small relative to the total number of hosts.) As my queries become more complex, I might replace the two-dimensional array with multimaps and use count_if. If we ultimately simulate with relatively few serotypes, I might try to use the metaprogramming example below or use an explicit index.
A sincere thanks again to all commentors for helping me learn about the various options and their costs. If I attempt reindexing or the metaprogramming solutions proposed below, I will post results here.
| 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 // 1 greater than the highest serotype
};
...
};
template <class H, typename H::Serotype s>
struct serotype_key_extractor {
typedef bool result_type;
result_type operator()(const boost::shared_ptr<Host>& h) const
{ ! return h->isInfected(s); }
};
Of course, this requires an index for each serotype on your multi_index_container (Serotype::sup total), with a probable performance of O(I * lg(n)) for each index over the lifetime of the simulation (where I is the number of infection events and n is the number of hosts). If there are a one or two common queries, you could use composite keys, with the serotype key extractors one component.
Option 4, keeping track of infected hosts in a map of sets std::map<H::Serotype, std::set<boost::shared_ptr<Host> > >, can be made more performant over infection events at the cost of querying. Insertion to/removal from a set might be O(lg(n)), so it might be better to use a hash or list rather than a set, though this will increase the cost of queries. Since you're running a simulation, keeping this structure synchronized isn't too bad. Update it during an infection (or cure, if they exist) event. If you're using event based programming, it's quite easy.
For querying with option 4, you could build other sets based on the other attributes, then find the intersection of those sets. This is O(f(I)+f(n)+g(S,T)) overall, where f(x) is the cost of inserting x elements, g(X,Y) is the cost of intersecting sets and S and T are the size of the sets (the O(f(I)+f(N)) comes from building all the sets; I'm playing it a little loose with the timing, since I might be assuming f(x) is homomorphic, which it likely isn't). At best, f(x)=x and g(X,Y)=X+Y, depending on your set implementation. Alternatively, fold over one of the sets (e.g. find all the hosts of a particular age, then count infected; count_if is a particular fold you could use, where count_if(start, end, pred) is equivalent to foldl(start, end, [](int count, const boost::shared_ptr<Host>& h){return count + pred(h); })). In the latter case, make use of the most restrictive index to reduce the sub-population you need to scan as much as possible. This is O(f(I)+S) overall.
Part of the difficulty in designing a performant solution is that you can really only make use of one independent index at a time. Within the groups from an index, other attributes you might index on are arranged essentially randomly. If two indices aren't independent (those that are geographically close are more likely to have the same infections), you might be able to make use of both simultaneously, though this doesn't gain you much: you can get most of the sub-population early in the query, but you'd still have to examine the rest of the group from the primary index.
If you're not married to C++, you could switch to C# and handle the queries with LINQ.
As for switching to a database, as mathmike suggests, you'd probably only want to use an object-oriented, in-memory database. Christopher Brown lists some, including FastDB and OOFile, though I can't say how suitable they are for your project.
|
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 compilation unit.
void SomeClass::store(int i)
{
LockMutex(_m);
_field = i; // could the compiler move this around?
UnlockMutex(_m);
}
ps: One is supposed to use instances of classes for holding locks to guarantee unlocking. I have left this out to simplify the example.
|
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 SomeClass::store() (it's not a local), the compiler can't know whether or not it's modified by the external function, therefore it must perform the store to _field between the function call sequence points.
The underlying hardware platform might need some attention in the form of memory barriers or cache flushes to deal with caching or out of order operations that occur in the hardware. The platform's implementation of the mutex APIs will deal with those issues if necessary.
|
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 be with facts.
I am no C++ Windows programmer guru. It would really be appreciated to have detailed explanations.
*Edit: I want to know at compile time and execution. Sorry for not mentioning it.
| 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 course, that means you end up including windows.h stuff in every .cpp file, not just the ones that need it. That can be a problem in cross-platform applications, but you can get around that by doing all your win32-specific stuff in a static library (that has windows.h pre-compiled) and linking to that in your main executable.
At runtime, the stuff in windows.h is about as bare-metal as you can get in Windows. So there's really no "inefficiencies" in that respect.
I would say that most people doing serious Windows GUI stuff would be using a 3rd-party library (Qt, wxWidgets, MFC, etc) which is typically layered on top of the Win32 stuff defined in windows.h (for the most part), so as I said, on Windows, the stuff in windows.h is basically the bare metal.
|
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 pointers are not first class objects while smart pointers like std::auto_ptr are. But to me, a raw pointer (to an object or to a function) in C++ does seem to me to satisfy the conditions stated above to qualify as a first class object. Am I missing something?
| 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 on how we envisage to use it. Unfortunately, this use semantics is not built-in for Pointers in C++.
If we are using pointers merely to 'point' to data, it will satisfy the requirements of being an FCO. However, if we use a pointer to 'hold' a data, then it can no longer be considered an FCO as its copy and assignment semantics do not work. Such 'resource handling' pointers (or more directly referred as 'raw pointers') are our interest in the context of Smart Pointer study. These are not FCO while the corresponding Smart Pointers are. In contrast, mere tracking pointers would continue to meet the requirements for an FCO.
The following paragraph from "Modern C++ Design" book nicely elucidates the point.
I quote from the Chapter on Smart Pointers:
An object with value semantics is an
object that you can copy and assign
to. Type int is the perfect example of
a first-class object. You can create,
copy, and change integer values
freely. A pointer that you use to
iterate in a buffer also has value
semantics—you initialize it to point
to the beginning of the buffer, and
you bump it until you reach the end.
Along the way, you can copy its value
to other variables to hold temporary
results.
With pointers that hold values
allocated with new, however, the story
is very different. Once you have
written
Widget* p = new Widget;
the variable p not only points to, but also owns, the memory
allocated for the Widget object. This
is because later you must issue delete
p to ensure that the Widget object is
destroyed and its memory is released.
If in the line after the line just
shown you write
p = 0; // assign something else to p
you lose ownership of the object previously pointed to by p, and you
have no chance at all to get a grip on
it again. You have a resource leak,
and resource leaks never help.
I hope this clarifies.
|
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
// for rendering, and it's implementation is not important
virtual void Render(Backend& backend) = 0;
};
What I'm doing right now is something like declaring different classes like
class Ball : public IRenderable {
virtual void Render(Backend& backend) {
// Rendering implementation, that is specific for
// the Ball object
// (...)
}
};
And then everything looks fine. I can easily do something like std::vector<IRenderable*> items, push some items like new Ball() in this vector and then make a call similiar to foreach (IRenderable* in items) { item->Render(backend); }
Ok, I guess it is the 'polymorphic' way, but what if I want to have different types of objects in my game and an ability to manipulate their state, where every object can be manipulated via it's own interface?
I could do something like
struct GameState {
Ball ball;
Bonus bonus;
// (...)
};
and then easily change objects state via their own methods, like ball.Move(...) or bonus.Activate(...), where Move(...) is specific for only Ball and Activate(...) - for only Bonus instances.
But in this case I lose the opportunity to write foreach IRenderable* simply because I store these balls and bonuses as instances of their derived, not base classes. And in this case the rendering procedure turns into a mess like
ball.Render(backend);
bonus.Render(backend);
// (...)
and it is bad because we actually lose our polymorphism this way (no actual need for making Render function virtual, etc.
The other approach means invoking downcasting via dynamic_cast or something with typeid to determine the type of object you want to manipulate and this looks even worse to me and this also breaks this 'polymorphic' idea.
So, my question is - is there some kind of (probably) alternative approach to what I want to do or can my current pattern be somehow modified so that I would actually store IRenderable* for my game objects (so that I can invoke virtual Render method on each of them) while preserving the ability to easily change the state of these objects?
Maybe I'm doing something absolutely wrong from the beginning, if so, please point it out :)
Thanks in advance!
| 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 comes to Render, it can just loop through them.
Other actions, like a tick of the world clock, might loop through looking for objects which are instances of Moveable and tell them to update.
If your Bonus is renderable (I couldn't tell for sure from your question) then it could subclass Collectable which subclasses Moveable.
|
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.
When you write a program to read out data from a file it is up to you to decide how to interpret the data what you read.
That is why you can only guess file contents and that is why often the extension of a file is used to give a hint on how the contents should be interpreted.
|
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.first to get the first element of the key pair just looks ridiculous). But in some cases it might be easier than creating a whole new struct for the key.
As with all things, use with care, and if it's not straightforward and easy to understand, it's probably better to find a different way to do it.
|
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 looking at the preprocessed code for this TU, I couldn't find an external definition for the digits member (or any other relevant members).
I tested this on two compilers (VC++ 10 and g++ 4.2.4) and got identical results from both (i.e., it works). Does the linker auto-magically link against an object file where this stuff is defined, or am I missing something obvious here?
| 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 iterations, I noticed that
I/O read blocks for requests of size more than 4K(typical block size). Infact giving buffer sizes greater than 4K causes performance to decrease.
The output operations does not seem to need buffering, linux seemed to take care of buffering output. So I issue a write(record) instead of maintaining special buffer of writes and then flushing them out at once using write(records[]).
But the performance of the application does not seem to be great. How could I improve the performance? Should I maintain special I/O threads to take care of reading blocks or are there existing C++ classes providing this abstraction already?(Something like BufferedInputStream in java)
| 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 available.
However, you should understand how that happens. Just because the data appears to be in RAM doesn't mean that you should treat it as random accessibly. Don't feed it to std::sort. This will touch random parts of the mmap'ed area, causing page faults left right and center. As a result, you'll be causing heavy disk seeking to resolve the random page faults. Instead, mmap() two inputs and merge them. Because the mmap command told the kernel what data you need in the future, the kernel will feed you data as fast as it can, and your merge sort will page fault (i.e. stall) when it is temporarily out of data.
|
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_
#define CALLBACKS_H_
extern void (*putPixelCallBack)();
extern void (*putImageCallBack)();
#endif /* CALLBACKS_H_ */
in single C file they are initialized as
callbacks.c
#include "callbacks.h"
void (*putPixelCallBack)();
void (*putImageCallBack)();
Other C files access this callback-functions as:
paint_node.c
#include "callbacks.h"
void paint_node(node *node,int index){
//Call callbackfunction
.
.
putPixelCallBack(node->x,node->y,index);
}
I compile these C files and generate a static library 'libBase.a'
Then in C++ application,
I want to assign C++ instance method to this global function-pointer:
I did something like follows :
in Sacm.cpp file
#include "Sacm.h"
extern void (*putPixelCallBack)();
extern void (*putImageCallBack)();
void Sacm::doDetection()
{
putPixelCallBack=(void(*)())&paintPixel;
//call somefunctions in 'libBase' C library
}
void Sacm::paintPixel(int x,int y,int index)
{
qpainter.begin(this);
qpainter.drawPoint(x,y);
qpainter.end();
}
But when compiling it gives the error:
sacmtest.cpp: In member function ‘void
Sacm::doDetection()’:
sacmtest.cpp:113: error: ISO C++
forbids taking the address of an
unqualified or parenthesized
non-static member function to form a
pointer to member function. Say
‘&Sacm::paintPixel’ sacmtest.cpp:113:
error: converting from ‘void
(Sacm::)(int, int, int)’ to ‘void
()()’
Any tips?
| 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->paintPixel(x, y, index);
}
void Sacm::doDetection()
{
putPixelCallBack = &sacm_global_paintPixel;
//call somefunctions in 'libBase' C library
}
You have to somehow setup the global variable properly.
|
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 the beginning and end of selection.
|
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 trying to practice good coding. But my code wont compile unless i uncomment the using namespace std. i keep getting this error and i dont know. im using g++ compiler.
Dog.h:20: error: ISO C++ forbids declaration of ‘ostream’ with no type
Dog.h:20: error: ‘ostream’ is neither function nor member function; cannot be declared friend. if i add line using std::cout; then i get this error.
Dog.h:21: error: ISO C++ forbids declaration of ‘ostream’ with no type.
Can somebody tell me the correct way to overload the << operator with out using namespace std;
| 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 of other files):
friend std::ostream& operator<< (std::ostream&, const Dog&);
|
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 set a filter in the QAbstractItem model and trigger an update() in the QListView.
Are there any helper methods in QListView for filtering I may have missed?
Is there a canonical way of handling this I haven't run across?
edit
Current progress.
I created a public slot called "updateFilter(QString)" in my QFileSystemModel subclass. Then I
connect(myQLineEditSearch, SIGNAL(textChanged(QString)),
myQFileSysModel, SLOT(updateFilter(QString)));
This sets the filter, then in my QFileSystemModel::data(...) method, I have:
void ComponentModel::updateFilter(QString filter)
{
_filter = filter;
emit layoutChanged();
}
QVariant ComponentModel::data(const QModelIndex &index, int role) const
{
QVariant result;
// if our search filter term is set and the item does not match,
// do not display item data. Searches are case insensitive
if (!_filter.isEmpty() &&
!QFileSystemModel::data(index, Qt::DisplayRole)
.toString().toLower().contains(_filter.toLower()))
{
return result;
}
result = QFileSystemModel::data(index, role);
return result;
}
This is almost there. The "glitch" I'm working on has to do with where the object is displayed. Currently, if I apply a search that matches the 3rd item in the list only the first two rows are rendered as blank. In other words, it still renders the rows for non-matched items.
| 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(proxy);
myview->setRootIndex(proxy->mapFromSource(model->index(model->rootPath()));
connect(filterLineEdit, SIGNAL(textChanged(QString)),
proxy, SLOT(setFilterFixedString(QString)));
The only issue I'm seeing in this is the rootIndex seems to get reset when you enter a search string. I'll update when I figure that out.
|
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> dist(5);
for (unsigned int i = 2; i < 5; i++)
{
dist[i] = ((4 + 3*(2^(3-2)))/10.0) ;
}
Why so?
| 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(unsigned int i = 2; i < 5; i++){
dist[i] = (4+3*j)/10.0;
j = j * 2;
}
In this particular instance, we initialize j to the first value of n-2 that you require, then proceed to multiply it by 2 to get the next power of 2 that you require.
|
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::cout << z; // prints "(1.23 + 8.19)/67.31 - 3.15*8.19"
For each binary operation (like plus), each side can be either an lvalue tree, rvalue tree, or double. This results in 8 overloads for each binary operation:
// core rvalue overloads for plus:
tree operator +(const tree& a, const tree& b);
tree operator +(const tree& a, tree&& b);
tree operator +(tree&& a, const tree& b);
tree operator +(tree&& a, tree&& b);
// cast and forward cases:
tree operator +(const tree& a, double b) { return a + tree(b); }
tree operator +(double a, const tree& b) { return tree(a) + b; }
tree operator +(tree&& a, double b) { return std::move(a) + tree(b); }
tree operator +(double a, tree&& b) { return tree(a) + std::move(b); }
// 8 more overloads for minus
// 8 more overloads for multiply
// 8 more overloads for divide
// etc
which also has to be repeated in a way for each binary operation (minus, multiply, divide, etc).
As you can see, there are really only 4 functions I actually need to write; the other 4 can cast and forward to the core cases.
Do you have any suggestions for reducing the size of this code?
PS: The class is actually more complex than just a tree of doubles. Reducing copies does dramatically improve performance of my project. So, the rvalue overloads are worthwhile for me, even with the extra code. I have a suspicion that there might be a way to template away the "cast and forward" cases above, but I can't seem to think of anything.
| 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, then the arguments to the function will be initialized with tree's move constructor where possible, else the copy constructor. Then, the function can do whatever it wants with its arguments in the appropriate way (like, say, moving their internals around).
It does incur an extra move when passing an rvalue reference argument compared with the lots-of-overloads version, but I think it's generally better.
Also, IMO, tree && arguments should maybe accept lvalues via a temporary copy, but this is not what any compilers currently do, so it's not very useful.
|
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
{
while(1) usleep(1);
}
catch(exception &e)
{
cerr << "Thread1 catched " << e.what() << endl;
}
};
void* thread2(void*)
{
sigaction(SIGINT,&sigthrow,NULL);
try
{
while(1);
}
catch(exception &e)
{
cerr << "Thread2 catched " << e.what() << endl; //never goes here
}
};
If I try to execute like:
int main()
{
pthread_t p1,p2;
pthread_create( &p1, NULL, &thread1, NULL );
pthread_create( &p2, NULL, &thread2, NULL );
sleep(1);
pthread_kill( p1, SIGINT);
pthread_kill( p2, SIGINT);
sleep(1);
return EXIT_SUCCESS;
}
I get the following output:
Thread1 catched Interrupt
terminate called after throwing an instance of 'std::runtime_error'
what(): Interrupt
Aborted
How can I make second threat catch exception?
Is there better idea about injecting exceptions?
| 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 throw
exceptions. Note that this requires platform-specific runtime
support that does not exist everywhere. Moreover, it only allows
_trapping_ instructions to throw exceptions, i.e. memory
references or floating point instructions. It does not allow
exceptions to be thrown from arbitrary signal handlers such as
`SIGALRM'.
This means that exceptioning out from the middle of some random code is NEVER safe. You can only except out of SIGSEGV, SIGBUS, and SIGFPE, and only if you pass -fnon-call-exceptions and they were triggered due to a fault in the running code. The only reason this worked on thread 1 is because, due to the existence of the usleep() call, G++ was forced to assume that it might throw. With thread 2, G++ can see that no trapping instruction was present, and eliminate the try-catch block.
You may find the pthread cancellation support more akin to what you need, or otherwise just add a test like this somewhere:
if (*(volatile int *)terminate_flag) throw terminate_exception();
|
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 realize that two variables in different scopes can actually have the same name?
I also want to add some code to the second loop and then debug it - but when I try to do that, i is consistently shown as 300. Very annoying.
| 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 it tracks both i's then gets confused when you hover over an i, it just returns the first i? or some such, I don't think its semantically checking which i to show.
|
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;
//delete pi; (It deletes by itself when goes out of scope. So explicit 'delete' call not required)
Case 2:
std::auto_ptr<int> pi(new int);
int i = 90;
*pi = 90;
int k = *pi + 10;
cout<<k<<endl;
[Output: 100]
Can someone please tell why it failed to work for case 1?
| 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 LineVector &lv2) {
return max(distance(lv1.p1,lv2.p2),distance(lv1.p2,lv2.p1));
}
but it gives compilation error in maxDistance() function (line 238) saying:
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_iterator_base_types.h: In instantiation of `std::iterator_traits<Point2D>':
quadrilateral.cpp:238: instantiated from here
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_iterator_base_types.h:129: error: no type named `iterator_category' in `class
Point2D'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_iterator_base_types.h:130: error: no type named `value_type' in `class Point2D
'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_iterator_base_types.h:131: error: no type named `difference_type' in `class Point2D'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_iterator_base_types.h:132: error: no type named `pointer' in `class Point2D'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_iterator_base_types.h:133: error: no type named `reference' in `class Point2D'
Please suggest what is the error?
| 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 namespace
float result = ::distance(point1, point2);
|
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 implementation of , they explicitly use pointers for the link fields in the list nodes (i.e., they do not use the pointer type provided by the allocator):
struct _List_node_base
{
_List_node_base* _M_next; ///< Self-explanatory
_List_node_base* _M_prev; ///< Self-explanatory
...
}
(For this purpose, the allocator interface is also deficient in that it does not define a dereference function; "dereferencing" an integer index always needs a pointer to the underlying storage.)
Do you know a library of STL-like data structures (i am mostly in need of singly- and doubly-linked list) that use indices (wrt. a base vector) instead of pointers to link nodes?
[*] Saving space: the lists will contain many 32-bit integers. With two pointers per node (STL list is doubly-linked), the overhead is 200%, or 400% on 64-bit platform, not counting the overhead of the default allocator.
EDIT: I'm looking for a SLL implementation that defines nodes in the following manner:
struct list_node
{
int _value; ///< The value in the list
int _next; ///< Next node in the list
...
}
_next is interpreted wrt. an implicit array or vector (must be provided externally to each method operating on the list).
EDIT2: After a bit more searching, I've found that the standard actually requires that allocators intended to be used with standard collections must define the pointer type to be equivalent with T*.
| 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.0, I get his compilation error:
test.cpp: In function 'void foo(Map&, const IntVector&)':
test.cpp:8: error: passing 'const std::vector<int, std::allocator<int> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]' discards qualifiers
I would expect this error if I was using Map::const_iterator inside foo but not using a non-const iterator.
What am I missing, why do I get this error?
| 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 element, change its key, and re-insert it with the new key.
Also concerning your example specifically, you will get undefined behavior (if this did work). Your map is empty when you call foo, so the iterator returned by find will be m.end(); the element doesn't exist. But then you'd go on to modify this non-existent element: ka-boom. Whenever you find something, you should check that it was found before you attempt to use it.
|
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:
template <class Method>
Butcher(Method);
private:
Vector a, b, c;
};
template <>
Butcher::Butcher(struct A)
: a(2), b(4), c(2)
{
// a = 0.5, 1;
// b = -1, 1, 3, 2;
// c = 0, 1;
}
Thanks,
Gokul.
| 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. This precludes definition of a free function overload to an operator commonly used to obtain a reference from an object. But the uncommon operator->* is left out.
In particular, operator[] has many similarities. It is binary (they missed a golden opportunity to make it n-ary), and it accepts some kind of container on the left and some kind of locator on the right. Its special-rules section, 13.5.5, doesn't seem to have any actual effect except to outlaw free functions. (And that restriction even precludes support for commutativity!)
So, for example, this is perfectly legal:
#include <utility>
#include <iostream>
using namespace std;
template< class T >
T &
operator->*( pair<T,T> &l, bool r )
{ return r? l.second : l.first; }
template< class T >
T & operator->*( bool l, pair<T,T> &r ) { return r->*l; }
int main() {
pair<int, int> y( 5, 6 );
y->*(0) = 7;
y->*0->*y = 8; // evaluates to 7->*y = y.second
cerr << y.first << " " << y.second << endl;
}
It's easy to find uses, but alternative syntax tends not to be that bad. For example, scaled indexes for vector:
v->*matrix_width[2][5] = x; // ->* not hopelessly out of place
my_indexer<2> m( v, dim ); // my_indexer being the type of (v->*width)
m[2][5] = x; // it is probably more practical to slice just once
Did the standards committee forget to prevent this, was it considered too ugly to bother, or are there real-world use cases?
| 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 question, but gives an idea of the depth I found in online discussion & literature.
There was a mention of "D&E 11.5.4" which I suppose is Design and Evolution of C++. Perhaps that contains a hint. Otherwise, I'm just gonna conclude it's a bit of useless ugliness that was overlooked by standardization, and most everyone else too.
Edit See below for a paste of the D&E quote.
To put this quantitatively, ->* is the tightest binding operator that can be overloaded by a free function. All the postfix-expression and unary operators overloads require nonstatic member function signatures. Next precedence after unary operators are C-style casts, which could be said to correspond to conversion functions (operator type()), which also cannot be free functions. Then comes ->*, then multiplication. ->* could have been like [] or like %, they could have gone either way, and they chose the path of EEEEEEVIL.
|
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-in types which obviously are implemented in C.
So what I first tried was to make it possible to give a value in my language three possible types: Int, String and Nil.
I came up with this:
enum ValueType
{
Int, String, Nil
};
class Value
{
public:
ValueType type;
int intVal;
string stringVal;
};
Yeah, wow, I know. It was extremely slow to pass this class around as the string allocator had to be called all the time.
Next time I've tried something similar to this:
enum ValueType
{
Int, String, Nil
};
extern string stringTable[255];
class Value
{
public:
ValueType type;
int index;
};
I would store all strings in stringTable and write their position to index. If the type of Value was Int, I just stored the integer in index, it wouldn't make sense at all using an int index to access another int, or?
Anyways, the above gave me a headache too. After some time, accessing the string from the table here, referencing it there and copying it over there grew over my head - I lost control. I had to put the interpreter draft down.
Now: Okay, so C and C++ are statically typed.
How do the main implementations of the languages mentioned above handle the different types in their programs (fixnums, bignums, nums, strings, arrays, resources,...)?
What should I do to get maximum speed with many different available types?
How do the solutions compare to my simplified versions above?
| 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 pointer to memory that has to be interpreted according to the type information (usually an enum):
enum type_t {
integer,
string,
null
};
typedef struct variable {
type_t type;
void * datum;
} variable_t;
void init_int_variable( variable_t * var, int value )
{
var->type = integer;
var->datum = malloc( sizeof(int) );
*((int)var->datum) = value;
}
void fini_variable( variable_t var ) // optionally by pointer
{
free( var.datum );
}
In C++ you can improve this approach by using classes to simplify the usage, but more importantly you can go for more complex solutions and use existing libraries as boost::any or boost::variant that offer different solutions to the same problem.
Both boost::any and boost::variant store the values in dynamically allocated memory, usually through a pointer to a virtual class in a hierarchy, and with operators that reinterpret (down casts) to the concrete types.
|
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
LIMIT LOG_REQ_LINES OFFSET %d* LOG_REQ_LINES ;
together with total count of records that can match current query:
SELECT count(*) FROM Logs WHERE level IN (%s);
(for a display "page n of m")
I wonder, if I could concatenate the two queries, and ask them both in one sqlite3_exec() simply concatenating the query string. How should my callback function look then? Can I distinguish between the different types of data by argc?
What other optimizations would you suggest?
| 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 a small notice about your selection query: if you insert records into the Log table with datetime('now'), and id is the auto incremented primary key of the table, then sorting by time is not required and it's enough to sort by id DESC. Since the auto incremented primary key field is an alias to ROWID, you will get a significant performance improvement.
By the way, time is a built in functions in SQLLite, so you should quote the column name with back-ticks (`).
|
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 CollisionMgr, where CollisionMgr also mantains a list of Bullet*.
Bullet::Bullet(GameGL*a_pGameGL, Player*a_pPlayer)
: GameObject( a_pGameGL )
{
m_pPlayer = a_pPlayer;
m_pGameGL->GetCollisionMgr()->AddBullet(this);
}
class CollisionMgr
{
void AddBullet(Bullet* a_pBullet);
protected:
std::list< Bullet*> m_BulletPList;
}
In CollisionMgr.Update(); based on some conditions, I populate class Cell which again contain a list of Bullet*. Finally, certain conditions qualify a Bullet to be deleted. Now, these conditions are tested upon while iterating through a Cell's list. So, if I have to delete the Bullet object, from all these places, how should I do it so that there are no more dangling references to it?
std::list< Bullet*>::iterator bullet_it;
for( bullet_it = (a_pCell->m_BulletPList).begin(); bullet_it != (a_pCell->m_BulletPList).end(); bullet_it++) {
bool l_Bullet_trash = false;
Bullet* bullet1 = *bullet_it;
// conditions would set this to true
if ( l_Bullet_Trash )
// TrashBullet( bullet1 );
continue;
}
Also, I was reading about list::remove, and it mentions that it calls the destructor of the object we are trying to delete. Given this info, if I delete from one list, the object does not exist, but the list would still contain a reference to it..How do I handle all these problems?
| 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 onto other etc... The problem is I am not working in continuous space. The line segments are being approximated using Bresenham algorithm.
So I want suggestions on what are the best and most efficient ways to do this? A link to C++ library or implementation would also be good enough. Please suggest some books also which deal with such problems.
| 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 environment. So Why am I getting this in a Windows CMD window? Is it telling me that one of my DLLs has a problem?
Also I observed immeditaly after the error message the Windows path depiction changes as follows
<--------------Screen Dump------------------------------>
C:\Program Files\MYPROGRAMS\APPLICATIONS>foo.exe
This program cannot be run in DOS mode.
C:\PROGRA~1\MYPROG~1\APPLICAT~1>
<--------------Screen Dump------------------------------>
Why does the path text change to Win95 style(for want of better phrase)? Is it somehow setting the system into some compatibility mode?
Most of the googling indicates this error occuring only during installation(unlike my scenario). THis link
http://www.personalcopy.com/doserror.htm talks about a variant but the checkboxes are no longer present in the DOS window properties.
Any help and pointers appreciated.
| 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 different options for shared memory and allocators, I just modify the typedefs. Unfortunately the allocators are templates, so I can't typedef the allocator I want to use.
Is there a way to achieve an alias to a template in C++? (Except for the obvious #define ALLOCATOR_T boost::interprocess::adaptive_pool)
| 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 = SomeClass<T>;
Edit2: In case of your example
typedef boost::interprocess::adaptive_pool allocator_t;
can be
template<typename T>
struct allocator_t
{
typedef boost::interprocess::adaptive_pool<T> type;
}
and used as
allocator_t<SomeClass>::type
|
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 Release and Debug mode, and that would make the queue stop working.
| 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 thread gets time to catch up.
|
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 expected data.
| 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);
Kev *= 4.0f;
cMatrix Baz = Kev;
Kev = Kev+Baz; //HERE!
What seems to be happening according to the debugger is that Kev and Baz are added but then the value is lost and when it comes to reassigning to Kev, the memory is just its default dodgy values. How do I overload my operators to allow for this statement?
My (stripped down) code is below.
//header
class cMatrix
{
private:
float* _internal;
UInt32 _r;
UInt32 _c;
bool _zeroindexed;
//fast, assumes zero index, no safety checks
float cMatrix::_getelement(UInt32 r, UInt32 c)
{
return _internal[(r*this->_c)+c];
}
void cMatrix::_setelement(UInt32 r, UInt32 c, float Value)
{
_internal[(r*this->_c)+c] = Value;
}
public:
cMatrix(UInt32 r, UInt32 c, bool IsZeroIndexed);
cMatrix( cMatrix& m);
~cMatrix(void);
//operators
cMatrix& operator + (cMatrix m);
cMatrix& operator += (cMatrix m);
cMatrix& operator = (const cMatrix &m);
};
//stripped source file
cMatrix::cMatrix(cMatrix& m)
{
_r = m._r;
_c = m._c;
_zeroindexed = m._zeroindexed;
_internal = new float[_r*_c];
UInt32 size = GetElementCount();
for (UInt32 i = 0; i < size; i++)
{
_internal[i] = m._internal[i];
}
}
cMatrix::~cMatrix(void)
{
delete[] _internal;
}
cMatrix& cMatrix::operator+(cMatrix m)
{
return cMatrix(*this) += m;
}
cMatrix& cMatrix::operator*(float f)
{
return cMatrix(*this) *= f;
}
cMatrix& cMatrix::operator*=(float f)
{
UInt32 size = GetElementCount();
for (UInt32 i = 0; i < size; i++)
{
_internal[i] *= f;
}
return *this;
}
cMatrix& cMatrix::operator+=(cMatrix m)
{
if (_c != m._c || _r != m._r)
{
throw new cCTException("Cannot add two matrix classes of different sizes.");
}
if (!(_zeroindexed && m._zeroindexed))
{
throw new cCTException("Zero-Indexed mismatch.");
}
for (UInt32 row = 0; row < _r; row++)
{
for (UInt32 column = 0; column < _c; column++)
{
float Current = _getelement(row, column) + m._getelement(row, column);
_setelement(row, column, Current);
}
}
return *this;
}
cMatrix& cMatrix::operator=(const cMatrix &m)
{
if (this != &m)
{
_r = m._r;
_c = m._c;
_zeroindexed = m._zeroindexed;
delete[] _internal;
_internal = new float[_r*_c];
UInt32 size = GetElementCount();
for (UInt32 i = 0; i < size; i++)
{
_internal[i] = m._internal[i];
}
}
return *this;
}
| 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 cMatrix::operator*(float f)
{
cMatrix matrix(*this);
matrix *= m;
return matrix;
}
You should take a look at Boost.Operators. This would let you implement only operator*= and operator+= and automatically provide correct implementations for operator+ and operator*.
PS: If you implement your matrix class just for the learning experience, don't hesitate to look at other implementations like the Matrix Template Library.
PPS: If you don't want to use boost, or if you just want to understand the best practice, take a look at Boost.Operator and do what they do.
|
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 thread to impersonate that person?
It seems as though this ought to be something pretty trivial to do ... but there doesn't appear to be any obvious way to do it. Can anyone help me out?
Edit: So if I have to fire off a seperate process is there any way I can CreateProcess a new process and have it launch from a specific entry point. I can, of course use command line processing to do it, but i'd really rather I could stop the user from entering the command line and starting an unclosable process!
| 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 performs a simple operation, you could probably check for success by using the exit code of the process)
|
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 would change the pattern and directory structure globally.
Apache has the directive CoreDumpDirectory - so it seems to be possible.
| 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 , and changes the current directory in its signal handler.
/* handle all varieties of core dumping signals */
static void sig_coredump(int sig)
{
apr_filepath_set(ap_coredump_dir, pconf);
apr_signal(sig, SIG_DFL);
#if AP_ENABLE_EXCEPTION_HOOK
run_fatal_exception_hook(sig);
#endif
/* linuxthreads issue calling getpid() here:
* This comparison won't match if the crashing thread is
* some module's thread that runs in the parent process.
* The fallout, which is limited to linuxthreads:
* The special log message won't be written when such a
* thread in the parent causes the parent to crash.
*/
if (getpid() == parent_pid) {
ap_log_error(APLOG_MARK, APLOG_NOTICE,
0, ap_server_conf,
"seg fault or similar nasty error detected "
"in the parent process");
/* XXX we can probably add some rudimentary cleanup code here,
* like getting rid of the pid file. If any additional bad stuff
* happens, we are protected from recursive errors taking down the
* system since this function is no longer the signal handler GLA
*/
}
kill(getpid(), sig);
/* At this point we've got sig blocked, because we're still inside
* the signal handler. When we leave the signal handler it will
* be unblocked, and we'll take the signal... and coredump or whatever
* is appropriate for this particular Unix. In addition the parent
* will see the real signal we received -- whereas if we called
* abort() here, the parent would only see SIGABRT.
*/
}
|
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 += debug
I did use the current version from SVN (0.2.0 - 2010-04-05) and the 0.2.0 zip package.
After building the library I did copy it to my Qt Libdir (C:\Qt\2009.05\qt\lib) and also to C:\Windows\system32. Now I try to link against the lib in my project file:
LIBS += -lqserialdevice
I import the needed header (abstractserial.h) and use my own AbstractSerial like this:
// Initialize
this->serialPort->setDeviceName("COM1");
if (!this->serialPort->open(QIODevice::ReadWrite | QIODevice::Unbuffered))
qWarning() << "Error" << this->serialPort->errorString();
// Configure SerialPort
this->serialPort->setBaudRate(AbstractSerial::BaudRate4800);
this->serialPort->setDataBits(AbstractSerial::DataBits8);
this->serialPort->setFlowControl(AbstractSerial::FlowControlOff);
this->serialPort->setParity(AbstractSerial::ParityNone);
this->serialPort->setStopBits(AbstractSerial::StopBits1);
The problem is, that if I run my application, it crashes immediately with exit code -1073741515 (application failed to initialize properly). This is the same error I got using QextSerialPort under Windows XP (it worked with Windows Vista).
If I build the QSerialDevice lib with release config and also my program, it crashes immediately but with exit code -1073741819
Can someone help me with this program or with another solution of getting a serial port to work with Qt (maybe another API or something?) Otherwise I have to use Windows API functions which would mean that my program won't work with UNIX systems..
If you have a solution for the problem with QextSerialPort under WinXP SP3, they are also welcome ;)
Best Regards,
Tobias
| 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
Iterator
Command + Adapter (function adapters)
Iterator + Adapter (iterator adapters)
reverse iterators
insert iterators
stream iterators
Template Method (STL algorithms using user-specified functions)
Which creational pattern? (Allocators)
The way these patterns are implemented is very different from the way they are implemented in an object oriented design. Josuttis wrote "the STL concept contradicts the original idea of object-oriented programming". This is what is causing the confusion around your question.
|
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 data.
Some data is indeed read and when that has happened, IOCP wakes up a worker thread via GetQueuedCompletionStatus() and I recover the request data.
I only ever get the request header when I POST from any browser. Any suggestions as to why?
| 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 blocks of data. Your read is completing because data has arrived. The read doesn't wait until all the data that you the programmer is expecting has arrived or even until your buffer is full.
Network issues can further confuse matters as routers may fragment things and lost data may delay things whilst it's resent.
Always when working with TCP you need to assume that your reads will always return just a single byte at a time and code accordingly; that way things will always work.
You should just issue another read and you'll get the rest of the data when it has arrived.
You might like to take a look at my free IOCP server framework (it does clients too) which can be found here; it sounds like you already have things working but sometimes being able to look at a different way of doing things helps.
When I need to accumulate data before processing I tend to take the following approach. Issue a read and wait for it to complete, look at what I have and, if I haven't got all I need and my buffer still has space in it, adjust the WSABUF that I'm using so that it points to the end of the current data that just arrived in the same buffer and issue another read; we then accumulate in the same buffer until either I have enough data to process it or I need to add another buffer on to get some more.
|
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 any way that I can deal with the key and value with sorted values?
| 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).
Usually it's not a problem: when I handle the DTN_DATETIMECHANGE notification I can check the new date/time and if it's found to be a weekend then I can call SetTime on the control to update the date. However, if I set the style to DTS_SHOWNONE, this call to SetTime causes the control to shift the input 'focus' (term used loosely) to the 'none' checkbox, e.g. away from the day field. This prevents the user from using keyboard input to continue incrementing the date unless they subsequently use the right arrow key to reset the 'focus', which is just nasty.
I would dearly like to prevent this focus shift from occurring. Is it even possible?
| 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<typename C, typename Res, typename... Args>
bind_class_t<C, Res, Args...>
bind_class(Res (C::*f)(Args...), C* c) {
return bind_class<C, Res, Args...>(f, c);
}
class test {
public:
int add(int x, int y) {
return x + y;
}
};
int main() {
test t;
// bind_class_t<test, int, int, int> b(&test::add, &t);
bind_class_t<test, int, int, int> b = bind_class(&test::add, &t);
std::cout << b(1, 2) << std::endl;
return 0;
}
compiled it with gcc 4.3.3 and got a segmentation fault. After spending some time with gdb and this program it seems to me that the addresses of the function and the class are mixed up and a call of the data address of the class isn't allowed. Moreover if I use the commented line instead everything works fine.
Can anyone else reproduce this behavior and/or explain me what's going wrong here?
| 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 compiles fine, but i get a link error "unresolved external symbol" for:
imShow<unsigned char,char>(unsigned char *,char *,int,int)
I don't understand what I did wrong!
| 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. Seriously though, are there any white papers that discuss solutions to this problem?
If this is possible on the CLR level then that would be good but I'm willing to go native if I have to.
| 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 SourceMod for CounterStrike:Source :) )
|
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("@"%d",\t", randomNumberWithinRange(1,100));
If I quit my application and restart, same set of numbers are generated. How to generate different set of random numbers for every launching.
| 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 contains, then cast it (but it's generally not a good idea) :
int pValValue = reinterpret_cast<int>( pVal );
|
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 very quickly compare pairs of pointers?
Edit 1: A clarification
In the end I just want to sort the list of pointer-pairs such that all of the duplicates are next to each other. Assume that there is no clear method in SomeClass that can be used for this purpose---I only have pointer pairs, and I want to find all identical pairs (in parallel). I thought a sort would do the trick, but if you can think of a better parallel method, let me know.
Edit 2: A clarification
Fixed my code (the arguments to the sort predicate were wrong--they should be pairs).
| 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 if and only if they point to the same two objects, you need:
// "less than"
template<typename T>
bool lt(const T &lhs, const T &rhs) {
return std::less<T>()(lhs, rhs);
}
typedef std::pair<SomeClass*, SomeClass*> mypair;
bool sortPredicate(const mypair &lhs, const mypair &rhs) {
return lt(lhs.first, rhs.first)
|| (!lt(rhs.first, lhs.first) && lt(lhs.second, rhs.second));
}
On pretty much any system you can name, this should compile to the same code as return lhs < rhs;, but that is not formally correct. If the referands of the pointers are all subobjects of the same object (for instance if you have a huge array and all the pairs point to elements of that one array), then operator< is OK for the pointers and hence OK for std::pair<pointer,pointer>.
If you want to pairs to fall in the same sort position if and only if the objects they point to sort the same, then you'd add the extra dereference:
bool sortPredicate(const mypair &lhs, const mypair &rhs) {
return lt(*lhs.first, *rhs.first)
|| (!lt(*rhs.first, *lhs.first) && lt(*lhs.second, *rhs.second));
}
and perhaps you'd also add checks for null pointers, if those are permitted. Of course if you know that SomeClass really is a class type, not a pointer type, then you don't need to use std::less in the version above, just define operator< for SomeClass and:
inline bool lessptr(const SomeClass *lhs, const SomeClass *rhs) {
if (lhs == 0) return rhs != 0;
if (rhs == 0) return false;
return *lhs < *rhs;
}
bool sortPredicate(const mypair &lhs, const mypair &rhs) {
return lessptr(lhs.first, rhs.first)
|| (!lessptr(rhs.first, lhs.first) && lessptr(lhs.second, rhs.second));
}
You may or may not be able to optimise that a bit, since there are some repeated null checks performed in both the first and second calls to lessptr. If you care that much, see what the compiler does with it.
|
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(DataItemList& dilList)
{
std::stringstream ssDataSegment;
for(iterItems = dilList.begin();
iterItems != dilList.end();
iterItems++)
{
// Lookahead in list to see if next element is end
if((iterItems + 1) == dilList.end())
{
ssDataSegment << (*iterItems)->ToString();
}
else
{
ssDataSegment << (*iterItems)->ToString() << ",";
}
}
return ssDataSegment.str();
}
How do I get at "the-next-item" in a std::list using an iterator? I would expect that it's a linked-list, why can't I get at the next item?
| 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 print the comma before:
std::string Compose(DataItemList& dilList)
{
std::stringstream ssDataSegment;
for(iterItems = dilList.begin();
iterItems != dilList.end();
++iterItems)
{
if(iterItems != diList.begin())
ssDataSegment << ",";
ssDataSegment << (*iterItems)->ToString();
}
return ssDataSegment.str();
}
|
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 to port the code.
Which one offers more compatibility with gcc 4.4.3 i'm using right now?
My project needs flex and bison, is there any "ready to use" environment to port such projects to windows platforms?
Thanks.
| 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?title=Install-MSYS
Various tools like flex from http://gnuwin32.sourceforge.net/
This is effectively the environment I do my own programming in, and it works very well. If you want an IDE, I'd recommend Code::Blocks, but both gvim and emacs are available for Windows too.
|
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 dealing with one shared array. The consumer will cond_wait when the array is empty, but rdlock when reading some elems. The producer will wrlock when adding(+signal) or removing elems from the array.
The benefit of using rdlock instead of mutex_lock is to improve performance: when using mutex_lock, several readers would block, whereas using rdlock several readers would not block.
| 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, however, by making your own rwlock class by using only a mutex and 2 conditional variables without using a POSIX rwlock:
getReadLock():
lock(mutex)
while(array.empty())
wait(readersCondVar, mutex)
readers++;
unlock(mutex)
releaseReadLock():
lock(mutex)
if (--readers == 0)
broadcast(writerCondVar, mutex) // or signal, if only 1 producer
unlock(mutex)
readerThread:
forever() {
getReadLock()
read()
releaseReadLock()
}
getWriteLock():
lock(mutex)
while(readers) {
wait(writerCondVar, mutex)
}
releaseWriteLock():
broadcast(readersCondVar, mutex)
unlock(mutex)
writerThread():
forever() {
getWriteLock()
write()
releaseWriteLock()
}
Simple and does what you want.
|
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 achieves this could help me out...
I did some research but did not find anything in Java/C++. However, I found that scipy on python achieves this with mio4.py or mio5.py. I thought about implementing this on java or C++, but it seems a bit out of my time schedule.
So the question is: is there any libraries in Java or C/C++ that permits saving MAT files without using Matlab libraries?
Thanks a lot
| 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_doc/matlab/matfile_format.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 help to define this generic function easily?
If not, do you think that this function can be useful?
Notes
Even if the examples are strings, the function should work for any Sequence.
The lexicographic order should be a template parameter of the function.
From the answers I conclude that there is nothing on C++/Boost that can help to define this generic function easily and also that this function is too specific to be proposed for free. I will implement a generic next_prefix and after that I will request if you find it useful.
I have accepted the single answer that gives some hints on how to do that even if the proposed implementation is not generic.
| 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 minval, I maxval)
{
if( last == first ) return false;
while( --last != first && *last == maxval ) *last = minval;
if( last == first && *last == maxval ) {
*last = minval;
return false;
}
++*last;
return true;
}
Maybe you wish to add an overload with a function object, or an overload or specialization for primitives. A couple of examples:
string s1("aaz");
increment(s1.begin(), s1.end(), 'a', 'z');
cout << s1 << endl; // aba
string s2("95");
do {
cout << s2 << ' '; // 95 96 97 98 99
} while( increment(s2.begin(), s2.end(), '0', '9') );
cout << endl;
|
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? For polymorphism, either one would work exactly the same, right?
| 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 just a pointer copy on your compiler. Dog *d3 = dynamic_cast<Dog*>(a) probably isn't (I'm speculating here, I'm not going to bother checking on any compiler. The point is: the compiler likely makes different assumptions about a and d when transforming code).
etc.
You can call virtual functions (that is, the defined polymorphic interface) of Animal equally through either of them, with the same effect. Assuming Dog hasn't hidden them, anyway (good point, JaredPar).
For non-virtual functions which are defined in Animal, and also defined (overloaded) in Dog, calling that function via a is different from calling it via d.
|
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 appropriate lines.
Thank you.
| 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 to make it less tedious? (And easier to maintain?)
| 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 class. This can be used like so:
class Person;
class PersonOptions
{
friend class Person;
string name_;
int age_;
char gender_;
public:
PersonOptions() :
age_(0),
gender_('U')
{}
PersonOptions& name(const string& n) { name_ = n; return *this; }
PersonOptions& age(int a) { age_ = a; return *this; }
PersonOptions& gender(char g) { gender_ = g; return *this; }
};
class Person
{
string name_;
int age_;
char gender_;
public:
Person(const PersonOptions& opts) :
name_(opts.name_),
age_(opts.age_),
gender_(opts.gender_)
{}
};
Person p = PersonOptions().name("George").age(57).gender('M');
|
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);
virtual QString toString() const = 0;
virtual QString getName() = 0;
virtual void fromString(QString str) = 0;
virtual int toInteger() = 0;
virtual bool operator==(const AbstractProperty &rightHand) = 0;
virtual bool operator!=(const AbstractProperty &rightHand) = 0;
virtual bool operator<(const AbstractProperty &rightHand) = 0;
virtual bool operator>(const AbstractProperty &rightHand) = 0;
virtual bool operator>=(const AbstractProperty &rightHand) = 0;
virtual bool operator<=(const AbstractProperty &rightHand) = 0;
protected:
QString name;
};
then I am implementing classes such as PropertyFloat and PropertyString and providing implementation for the comparator operators based on the assumption that only strings are being compared with strings and so on. However the problem with this is there would be no compiletime error thrown if i did
if(propertyfloat a < propertystring b)
however my implementation of the operators for each derived class relies on them both being the same derived class. So my problem is I cant figure out how to implement a property structure so that I can have them all inherit from some base type but code like what I have above would throw a compile time error.
Any ideas on how this can be done? For those familiar with QT I tried using also a implementation with QVariant however QVariant doesn't have operators < and > defined in itself only in some of its derived classes so it didn't work out.
What my end goal is, is to be able to generically refer to properties. I have an element class that holds a hashmap of properties with string 'name' as key and the AbstractProperty as value. I want to be able to generically operate on the properties. i.e. if I want to get the max and min values of a property given its string name I have methods that are completely generic that will pull out the associated AbstactProperty from each element and find the max/min no matter what the type is. so properties although initially declared as PropertyFloat/PropertyString they will be held generically.
| 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 == d.value;
}
bool operator!=(const Descendant& d)
{
return !(*this == d);
}
bool operator< (const Descendant& d)
{
return m_value < d.m_value;
}
bool operator<=(const Descendant& d)
{
return (*this < d) || (*this == d);
}
bool operator> (const Descendant& d)
{
return !(*this <= d);
}
bool operator>=(const Descendant& d)
{
return !(*this < d);
}
protected:
Numeric_Field(const Descendant& new_value = 0)
: m_value(new_value)
{ ;}
};
This could be made a little more generic by replacing m_value by using pure virtual protected setters and getters:
template <class Descendant_Type>
struct Numeric_Field_2
{
virtual const Descendant_Type get_value(void) const = 0;
virtual void set_value(const Descendant& new_value) = 0;
bool operator==(const Descendant_Type& dt)
{
return get_value() == dt.get_value();
}
bool operator< (const Descendant_Type& dt)
{
return get_value() < dt.get_value();
}
};
At this point, you could pass around pointers to Numeric_Field wherever a comparison is needed. I believe this is only a typing saver.
|
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->total means sequence is a pointer to a one of those data types, and you are accessing the total property of what it is pointing to. It's exactly the same as:
(*sequence).total;
So the loop:
for( i = 0; i < (sequence ? sequence->total : 0); i++ )
exits when sequence evaluates to false, since 0 == false.
The ternary if construction is used to make sure they aren't dereferencing (->) a null pointer, because if they just put sequence->total as the condition, they would be dereferencing it every time. Unhappy! =(
|
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** myData_;
std::size_t mySize_;
std::size_t myIndex_;
public:
Set();
class iterator : public std::iterator<std::random_access_iterator_tag, T*>
{
private:
T** itData_;
public:
iterator(T** obj)
{
itData_ = obj;
}
T operator*() const
{
return **itData_;
}
/*Comparing values of two iterators*/
bool operator<(const iterator& obj)
{
return **itData_ < **obj.itData_;
}
/*Substracting two iterators*/
difference_type operator-(const iterator& obj)
{
return itData_ - obj.itData_;
}
/*Moving iterator backward for value*/
iterator operator-(const int value)
{
return itData_ - value;
}
/*Adding two iterators*/
difference_type operator+(const iterator& obj)
{
return itData_ + obj.itData_;
}
/*Moving iterator forward for value*/
iterator operator+(const int value)
{
return itData_ + value;
}
bool operator!=(const iterator& obj)
{
return (itData_ != obj.itData_);
}
bool operator==(const iterator& obj)
{
return (itData_ == obj.itData_);
}
T** operator++()
{
return ++itData_;
}
T** operator--()
{
return --itData_;
}
};
iterator begin() const
{
return myData_;
}
iterator end() const
{
return myData_ + myIndex_;
}
};
template<class T>
ostream& operator<<(ostream& out, const Set<T>& obj)
{
for (int i = 0;i < 3; ++i)
{
out << *obj.myData_[i] << "\n";
}
return out;
}
//file Set_impl.h
#pragma once
#include "stdafx.h"
#include "Set.h"
template<class T>
Set<T>::Set()
{
mySize_ = 3;
myIndex_ = 3;
myData_ = new T*[mySize_];
myData_[0] = new T(3);
myData_[1] = new T(1);
myData_[2] = new T(2);
}
//main
include "stdafx.h"
#include "Set_impl.h"
int _tmain(int argc, _TCHAR* argv[])
{
Set<int> a;
Set<int>::iterator beg_ = a.begin();
Set<int>::iterator end_ = a.end();
std::sort(beg_,end_);//WONT SORT THIS RANGE
cin.get();
return 0;
}
Why sort can't accept this iterators even though I've provided all operators needed for sort to work? I think the best way to check what's going on is to paste this code and run it first.
Thanks
| 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 compile by changing those to:
class iterator : public std::iterator<std::random_access_iterator_tag, T>
and
T& operator*() const
(in addition to numerous other changes since GCC doesn't seem to like this a lot)
/*Comparing values of two iterators*/
bool operator<(const iterator& obj)
{
return **itData_ < **obj.itData_;
}
This is also wrong. It should be related to operators == and !=, that is, it shouldn't be comparing the values, but the iterators. (Luckily for you I doubt, std::sort actually ever uses this method.)
T** operator++()
{
return ++itData_;
}
T** operator--()
{
return --itData_;
}
These should return a reference to the iterator itself (again, the return value is most probably not used by the library).
|
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 c++, I need to be able to read these lines and store them in a "memory register" class that I already have constructed...
For example, the first line would need to store "1 a" in register zero.
How can I parse out the number at the line beginning and then store the rest as a string?
I have setup storage using a class that is called using mem.set(int, string);. int is the memory location at the beginning of the line and string is the stored instruction.
Edit: Some Clarifications:
I must use standard libraries
the grammar for the input file is here: http://www.cs.uwyo.edu/~seker/courses/2150/iascode.pdf
The loader will overwrite duplicate line entries. That means the first line 11 in the sample will be overwritten by the second.
| 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 the strstr function to find the first whitespace character, and assign the result to pString.
Move pString forward one character at a time until it points to a non-whitespace character. This is the start of the string containing the "rest of the line".
Use atoi on cur_line to convert the first entry in the string to an integer, and store the results in line_num
Now, you should be able to call your function like mem.set(line_num, pString)
Interpreting those strings is going to be much more difficult, however...
Edit: As Mike DeSimone mentions, you can combine the strstr and atoi steps above if you use one of the strto* functions instead of atoi.
|
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 the things that Mono/.Net have but for sure, Qt is much more mature than Mono and is truly cross-platform. FYI, Skype and Google Earth use Qt. I like how easy to create cool GUI, state machines & database-driven applications with Qt. Oh, yeah, Qt has great WebKit & Multimedia modules that get you on the fast track of web & media integration.
Give Qt a try and experience it yourself. It has awesome demos & examples, check them out!
|
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 branch times the probability of the branch being symmetric. For the N-Queens problem, symmetry is probably not a very fruitful pruning method after the first two rows.
|
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] = '*';
FileBuffer[1] = '.';
FileBuffer[2] = 't';
FileBuffer[3] = 'x';
FileBuffer[4] = 't';
OPENFILENAMEA ofn;
memset(&ofn, 0, sizeof(OPENFILENAMEA));
ofn.lStructSize = sizeof(OPENFILENAMEA);
ofn.hwndOwner = parent;
ofn.lpstrFile = FileBuffer;
ofn.nMaxFile = 500;
ofn.lpstrFilter = "Filetype (*.txt)\0\0";
ofn.lpstrDefExt = "txt";
ofn.Flags = OFN_EXPLORER;
if(!GetOpenFileNameA(&ofn))
{
return;
}
ifstream *file;
file = new ifstream(FileBuffer,ios::in);
int lenn;
lenn = 0;
while (!file->eof())
{
buf[lenn] = file->get();
lenn += 1;
}
buf[lenn - 1] = 0;
file->read(buf,lenn);
SetWindowTextA(ctrl,buf);
file->close();
}
How can I make it do the new line characters?
Thanks
(Fixed it, turns out the stream was not giving me CR's so I had to insert them.
| 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 file in character by character, so you can just insert an extra CR into the buffer.
As a side note, you'll eventually want to do the file IO on a separate thread (i.e. not the UI thread) so that you don't hang the UI while you're reading the file. It'd be nice if the UI showed some sort of loading animation, or progress bar.
|
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 then I have no issues.
I should be able to define my specialization after <string> is included. What do I have to do to be able to do that?
My Code:
#include <bits/localefwd.h>
//#include <string> // <- uncommenting this line causes compilation to fail
namespace std {
template<>
class basic_string< char, char_traits<char>, allocator<char> >
{
public:
int blah() { return 42; }
size_t size() { return 0; }
const char *c_str() { return ""; }
void reserve(int) {}
void clear() {}
};
}
#include <string>
#include <iostream>
int main() {
std::cout << std::string().blah() << std::endl;
}
The above code works fine. But, if I uncomment the first #include <string> line, I get the following compiler errors:
blah.cpp:7: error: specialization of ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ after instantiation
blah.cpp:7: error: redefinition of ‘class std::basic_string<char, std::char_traits<char>, std::allocator<char> >’
/usr/include/c++/4.4/bits/stringfwd.h:52: error: previous definition of ‘class std::basic_string<char, std::char_traits<char>, std::allocator<char> >’
blah.cpp: In function ‘int main()’:
blah.cpp:22: error: ‘class std::string’ has no member named ‘blah’
Line 52 of /usr/include/c++/4.4/bits/stringfwd.h:
template<typename _CharT, typename _Traits = char_traits<_CharT>,
typename _Alloc = allocator<_CharT> >
class basic_string;
As far as I know this is just a forward delcaration of the template, NOT an instantiation as g++ claims.
Line 56 of /usr/include/c++/4.4/bits/stringfwd.h:
typedef basic_string<char> string;
As far as I know this is just a typedef, NOT an instantiation either.
So why are these lines conflicting with my code? What can I do to fix this other than ensuring that my code is always included before <string>?
| 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 implementation already instantiates the template that you are trying to specialize and, if you provide a specialization for any template, it must be before the template is ever instantiated with the parameters for which you want to provide the specialization.
14.7.3 [temp.expl.spec]/6
|
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 directly manipulate some kind of character buffer or is the screen constantly cleared and reprinted to stdout?
Is there a set of libraries to implement such behavior or even some kind of a "modern" event-driven GUI toolkit for the console?
| 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 version (EnumFontFamiliesExA) display some very weird behaviour for East Asian language fonts.
The linked articles have example code.
|
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() { }
};
And suppose I also have some other objects that derive from IRenderable, e.g. Cat and Dog.
So far so good. I add some Cat and Dog specific methods, like SeekForWhiskas(...) and Bark(...). After that I add specific Render(...) method for them, so my code looks this way:
class Cat : public IRenderable {
public:
void SeekForWhiskas(...) {
// Implementation could be here or moved
// to a source file (depends on me wanting
// to inline it or not)
}
virtual void Render(...) {
// Here comes the rendering routine, that
// is specific for cats
SomehowDrawAppropriateCat(...);
}
};
class Dog : public IRenderable {
public:
void Bark(...) {
// Same as for 'SeekForWhiskas(...)'
}
virtual void Render(...) {
// Here comes the rendering routine, that
// is specific for dogs
DrawMadDog(...);
}
};
And then somewhere else I can do drawing the way that an appropriate rendering routine is called:
IRenderable* dog = new Dog();
dog->Render(...);
My question is about logical wrapping of such kind of code.
I want to break apart the code, that corresponds to rendering of the current object and it's own methods (Render and Bark in this example), so that my class implementation doesn't turn into a mess (imagine that I have 10 methods like Bark and of course my Render method doesn't fit in their company and would be hard to find).
Two ways of making what I want to (as far as I know) are:
Making appropriate routines that look like RenderCat(Cat& cat, RenderInterface* ri), joining them to render namespace and then the functions inside a class would look like
virtual void Render(...) { RenderCat(*this, ...); }, but this is plain stupid, because I'll lose access to Cat's private members and friending these functions looks like a total design disaster.
Using visitor pattern, but this would also mean I have to rebuild my app's design and looks like an inadequate way to make my code complicated from the very beginning.
Any brilliant ideas? :)
| 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. Thus you won't know where to draw the squiggle.
You might be able to use a Rich Edit control (as WordPad does) and tweak the styling of the misspelled words. I've never used Rich Edit, so I can't help with the details.
|
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;
int popped = head->nodeNum;
delete temp;
Return numOut;
Question:
1) head should be a pointer or a LinkNode *?
2) Link * temp is created on the call stack and when pop finishes doesn't temp delete automatically?
3) My major confusion is on what is the value of temp->next? Does this point to node1.next which equals node2?
Appreciate your help?
My reference is C++ for Java Programmers by Weiss.
|
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 = (HGDIOBJ)CreateFontA(size, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,name);
SendMessage(hand, WM_SETFONT, (WPARAM)hfDefault, MAKELPARAM(FALSE, 0));
}
| 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 calling SetControlFont by calling RedrawWindow.
|
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 following error:
const1.cc:11: error:
invalid initialization of reference of type 'const std::string&'
from expression of type 'std::string*
It does make some sense because foo is not of type const Foo, but just Foo, so the compiler wants to use the non-const function. But still, why can't it recognize that I want to call the const GetString function, by looking at the (type of) variable I assign it to? I found this kind of surprising.
| 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;
temp = new Node;
temp->accnumber = a;
temp->balance = b;
temp->next = listpointer;
listpointer = temp;
}
in this here void AddNode(Node * & listpointer, int a, float b) { what does *& listpointer mean exactly.
| 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 must use
both the CreateFile() FILE_SHARE_READ
and FILE_SHARE_WRITE flags to gain
access to the drive.
Once the logical or physical drive has
been opened, you can then perform
direct I/O to the data on the entire
drive. When performing direct disk
I/O, you must seek, read, and write in
multiples of sector sizes of the
device and on sector boundaries. Call
DeviceIoControl() using
IOCTL_DISK_GET_DRIVE_GEOMETRY to get
the bytes per sector, number of
sectors, sectors per track, and so
forth, so that you can compute the
size of the buffer that you will need.
The documentation of CreateFile also offers some clues:
You can use the CreateFile function to open a physical disk drive or a volume,
which returns a direct access storage device (DASD) handle that can be
used with the DeviceIoControl function. This enables you to access the
disk or volume directly, for example such disk metadata as the partition
table. However, this type of access also exposes the disk drive or
volume to potential data loss, because an incorrect write to a disk
using this mechanism could make its contents inaccessible to the
operating system. To ensure data integrity, be sure to become
familiar with DeviceIoControl and how other APIs behave
differently with a direct access handle as opposed to a file system handle.
|
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 (killing the app if it's a SIGKILL or doing whatever else if it's some other signal) before the statement following kill() is run? Or is it possible - even probable - that whatever command follows kill() will run before the signal is processed by the parent thread?
| 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 particular thread, unless you have used sigprocmask to mask them from the threads you don't want to get them. Most multithreaded programs do this, as having process-level signals delivered to arbitrary threads is usually not what you want.
|
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 not getting it.
I have an examples ;
List A : 1, 3, 5, 7
List B : 2, 4, 6, 8
Find rank(i) = 4.
First Step : i/2 = 2;
List A now contains is A: 1, 3
List B now contains is B: 2, 4
compare A[i] to B[i] i.e
A[i] is less;
So the lists now become :
A: 3
B: 2,4
Second Step:
i/2 = 1
List A now contains A:3
List B now contains B:2
NoW I HAVE LOST THE VALUE 4 which is actually the result ...
I know I am missing some thing , but even after close to a day of thinking I cant just figure this one out...
| 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:
Assume i = 10; (zero-based indexing, we're looking for the 11th element overall).
On the first step, you know the answer is either in list1(0...10) or list2(0...10). Take a = list1(5) and b = list2(5).
If a > b, then there are 5 elements in list1 which come before a, and at least 6 elements in list2 which come before a. So a is an upper bound on the result. Likewise there are 5 elements in list2 which come before b and less than 6 elements in list1 which come before b. So b is an lower bound on the result. Now we know that the result is either in list1(0..5) or list2(5..10). If a < b, then the result is either in list1(5..10) or list2(0..5). And if a == b we have our answer (but the problem said the elements were distinct, therefore a != b).
We just repeat this process, cutting the size of the search space in half at each step. Bisection refers to the fact that we choose the middle element (bisector) out of the range we know includes the result.
So the only difference between this and binary search is that in binary search we compare to a value we're looking for, but here we compare to a value from the other list.
NOTE: this is actually O(log i) which is better (at least no worse than) than O(log n). Furthermore, for small i (perhaps i < 100), it would actually be fewer operations to merge the first i elements (linear search instead of bisection) because that is so much simpler. When you add in cache behavior and data locality, the linear search may well be faster for i up to several thousand.
Also, if i > n then rely on the fact that the result has to be toward the end of either list, your initial candidate range in each list is from ((i-n)..n)
|
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 addelements(int x);
int find(int x);
void setunion(int x, int y);
private:
vector<int> uptree;
};
#endif
My implementation is this:
void DisjointSets::addelements(int x){
for(int i=0; i<x; i++)
uptree.push_back(-1);
}
//Given an int this function finds the root associated with that node.
int DisjointSets::find(int x){
//need path compression
if(uptree.at(x) < 0)
return x;
else
return find(uptree.at(x));
}
//This function reorders the uptree in order to represent the union of two
//subtrees
void DisjointSets::setunion(int x, int y){
}
Upon compiling main.cpp (g++ main.cpp)
I'm getting these errors:
dsets.h: In function \u2018int main()\u2019:
dsets.h:25: error: \u2018std::vector > DisjointSets::uptree\u2019 is private
main.cpp:9: error: within this context
main.cpp:9: error: \u2018class std::vector >\u2019 has no member named \u2018addelements\u2019
dsets.h:25: error: \u2018std::vector > DisjointSets::uptree\u2019 is private
main.cpp:10: error: within this context
main.cpp:11: error: \u2018uptree\u2019 was not declared in this scope
I'm not sure exactly whats wrong.
Any help would be appreciated.
| 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(){
DisjointSets s;
s.uptree.addelements(4); // try s.addelements(4)
for(int i=0; i<s.uptree.size(); i++) // try making uptree public
cout <<uptree.at(i) << endl;
return 0;
}
#endif
|
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 thread, it blocks the overall process! Why this thing occurs?
boost::mutex nvtMutex;
boost::mutex strMutex;
boost::mutex quitMutex;
bool quit = false;
void *processServerOutput(void *arg)
{
NVT *nvt = (NVT*)arg;
while(1)
{
// Lock the quitMutex before trying to access to quit variable
quitMutex.lock();
if(quit)
{
quitMutex.unlock();
pthread_exit(NULL);
}
else
quitMutex.unlock();
// Receive output from server
nvtMutex.lock();
nvt->receive();
cout << Util::Instance()->iconv("koi8-r", "utf-8", nvt->getOutBuffer());
nvtMutex.unlock();
// Delay
sleep(1);
}
}
void *processUserInput(void *arg)
{
NVT *nvt = (NVT*)arg;
while(1)
{
// Get user's input
//cin.getline(str, 1023);
sleep(3);
strcpy(str, "hello");
// If we type 'quit', exit from thread
if(strcmp(str, "quit") == 0)
{
// Lock quit variable before trying to modify it
quitMutex.lock();
quit = true;
quitMutex.unlock();
// Exit from thread
pthread_exit(NULL);
}
// Send the input to server
nvtMutex.lock();
nvt->writeUserCommand(Util::Instance()->iconv("utf-8", "koi8-r", str));
nvt->send();
nvtMutex.unlock();
}
}
| 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::recv or if this class does not provide the proper thread safety you need.
|
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 code I would like to skip if one of the tokens doesn't exist, but this doesn't work:
#if defined MY_VAR(hello)
What I want it to expand to is this:
#ifdef prefix_hello
But I can't figure out how. I need to use the MY_VAR() macro to do the expansion, so I can't just hardcode the name. (It's actually for some testing code, the same code gets included with a different prefix each time to test a bunch of classes, and I want to skip a couple of tests for a handful of the classes.)
Is this possible with the C++ preprocessor?
Update:
Here is some semi-compilable code to demonstrate the problem further: (to avoid squishing it into the comments below)
#define PREFIX hello
#define DO_COMBINE(p, x) p ## _ ## x
#define COMBINE(p, x) DO_COMBINE(p, x)
#define MY_VAR(x) COMBINE(PREFIX, x)
// MY_VAR(test) should evaluate to hello_test
#define hello_test "blah blah"
// This doesn't work
#ifdef MY_VAR(test)
printf("%s\n", MY_VAR(test));
#endif
| 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 happening, you can't expect the preprocessor to remember what arguments have been passed into what macros over the course of the preceding source code.
You can do something like
#define prefix_test 1
#if MY_VAR(test) == 1
#undef prefix_test // optional, "be clean"
...
#endif
#undef prefix_test
to query whether the prefix currently has the particular value prefix_. (Undefined identifiers are replaced with zero.)
|
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 list of #pragma directives. Perhaps I should rephrase this question a bit more:
What code have you written with #pragma you found useful?
.
Answers at a glance:
Thanks to all who answered and/or commented. Here's a summary of some inputs I found useful:
Jason suggested that using #pragma once or #ifndef #define #endif would allow faster compiling on a large-scale system. Steve jumped in and supported this.
280Z28 stepped ahead and mentioned that #pragma once is preferred for MSVC, while GCC compiler is optimised for #ifndef #define #endif. Therefore one should use either, not both.
Jason also mentioned about #pragma pack for binary compatibility, and Clifford is against this, due to possible issues of portability and endianness. Evan provided an example code, and Dennis informed that most compilers will enforce padding for alignment.
sblom suggested using #pragma warning to isolate the real problems, and disable the warnings that have already been reviewed.
Evan suggested using #pragma comment(lib, header) for easy porting between projects without re-setting up your IDE again. Of course, this is not too portable.
sbi provided a nifty #pragma message trick for VC users to output messages with line number information. James took one step further and allows error or warning to match MSVC's messages, and will show up appropriately such as the Error List.
Chris provided #pragma region to be able to collapse code with custom message in MSVC.
Whoa, wait, what if I want to post about not using #pragmas unless necessary?
Clifford posted from another point of view about not to use #pragma. Kudos.
I will add more to this list if the SOers feel the urge to post an answer. Thanks everyone!
| 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 its contents.
edit: To answer the comments: imagine you have a 200kB header file. With "once", the compiler loads this once and then knows that it does not need to include the header at all the next time it sees it referenced. With #if it has to load and parse the entire file every time to determine that all of the code is disabled by the if, because the if must be evaluated each time. On a large codebase this could make a significant difference, although in practical terms (especially with precompiled headers) it may not.
pragma "pack" is invaluable when you need binary compatibility for structs.
Edit: For binary formats, the bytes you supply must exactly match the required format - if your compiler adds some padding, it will screw up the data alignment and corrupt the data. So for serialisation to a binary file format or an in-memory structure that you wish to pass to/from an OS call or a TCP packet, using a struct that maps directly to the binary format is much more efficient than 'memberwise serialisation' (writing the fields one by one) - it uses less code and runs much faster (essential in embedded applications, even today).
pragma "error" and "message" are very handy, especially inside conditional compliation blocks (e.g. "error: The 'Release for ePhone' build is unimplemented", message: "extra debugging and profiling code is enabled in this build")
pragma "warning" (especially with push & pop) is very useful for temporarily disabling annoying warnings, especially when including poorly written third-party headers (that are full of warnings) - especially if you build with warning level 4.
edit: Good practice is to achieve zero warnings in the build so that when a warning occurs you notice it and fix it immediately. You should of course fix all warnings in your own code. However, some warnings simply cannot be fixed, and do not tell you anything important. Additionally, when using third party libraries, where you cannot change their code to fix the warnings, you can remove the 'spam' from your builds by disabling the library's warnings. Using push/pop allows you to selectively disable the warnings only during the library includes, so that your own code is still checked by the compiler.
|
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 in correct order, correct me if I am wrong.
Is there a way to "dump" the memory containing the set into disk and then read it back later? That is, keep everything in binary format, thus avoiding the re-insertion.
Do the boost serialization tools do this?
Thanks!
EDIT: oh I should probably read, http://www.parashift.com/c++-faq-lite/serialization.html I will read it now... no it doesn't really help
| 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 bring the construction of the set back to linear complexity instead of n log n.
|
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 however you like, as long as you never declare two
pointers on the same line.
Works for me. I'm an Employee* pE kind of person, but I'm married to an Employee *pE kind of person - my advice would be not to get too worked up about it.
|
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 answer)
But, this still applies to C
|
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.
}
return 0;
}
But this code doesn't work.KeyHandler doesn't receive wm_mousewheel message.
I am testing this application on vista.
If my approach is wrong how to handle wm_mousewheel properly?
Do vista is responsible for failure in handling wm_mousewheel message?
| 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 processes it.
Change your test to if(uMsg == WM_MOUSEWHEEL).
Check that your window or one of it's children has focus.
If this is related to your previous wtl-child-window-event-handling question, I edited my answer to not forward WM_MOUSEWHEEL.
|
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, where moving if possible would give substantial speedup.
However, so far I was unable to devise any working scheme for this. My container is quite complicated, so I can't just duplicate insert() code several times: it is large. I want to keep all "real" code in some inner helper, say do_insert() (may be templated) and various insert()-like functions would just call that with different arguments.
My best bet code for this (a prototype, of course, without doing anything real):
#include <iostream>
#include <utility>
struct element
{
element () { };
element (element&&) { std::cerr << "moving\n"; }
};
struct container
{
void insert (const element& value)
{ do_insert (value); }
void insert (element&& value)
{ do_insert (std::move (value)); }
private:
template <typename Arg>
void do_insert (Arg arg)
{ element x (arg); }
};
int
main ()
{
{
// Shouldn't move.
container c;
element x;
c.insert (x);
}
{
// Should move.
container c;
c.insert (element ());
}
}
However, this doesn't work at least with GCC 4.4 and 4.5: it never prints "moving" on stderr. Or is what I want impossible to achieve and that's why emplace()-like functions exist in the first place?
| 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::cerr << "moving\n"; }
};
struct container
{
void insert (const element& value)
{ do_insert (value); }
void insert (element&& value)
{ do_insert (std::move(value)); }
private:
template <typename Arg>
void do_insert (Arg&& arg)
{ element x (std::forward<Arg>(arg)); }
};
int
main ()
{
{
// Shouldn't move.
container c;
element x;
c.insert (x);
}
{
// Should move.
container c;
c.insert (element ());
}
}
The keyword that you might look for is "perfect forwarding".
|
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
#define MAINWINDOW_H
#include <QtGui/QWidget>
namespace Ui
{
class MainWindow;
}
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void addContact();
void submitContact();
void cancel();
private:
Ui::MainWindow *ui;
QPushButton *addButton;
QPushButton *submitButton;
QPushButton *cancelButton;
QLineEdit *nameLine;
QTextEdit *addressText;
QMap<QString, QString> contacts;
QString oldName;
QString oldAddress;
};
#endif // MAINWINDOW_H
| 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 between the 2. Which one I should use? Which one able to guarantee thread safety?
Thanks.
| 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.