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,572,540 | 2,572,594 | Errors not printing correctly..Is this logic flow correct? c++ | Example user input:
PA1 9 //correct
PJ1 9 //wrong, error printed "Invalid row" because it is not between A and I
PA11 9 //wrong, error printer "Invalid column" because it is not between 1 and 9.
The problem I am having is that it should clear the remaining input and then ask for the user to enter the "move" again, and it is not.
Where did I go wrong? I've been at it for a while and still got no progress..
void clearInput()
{
cin.clear();
}
bool getCoords(int & x, int & y)
{
char row;
while(true){
cin>>row>>y;
row=toupper(row);
if(/*(id=='P' || id=='p' || id=='D' || id=='d') && */row>='A' && row<='I' && isalpha(row) && y>=1 && y<=9){
x=row-'A';
y=y-1;
return true;
}
else if(!(y>=1 && y<=9)){
cout<<"Invalid column\n"<< endl << endl;
cout<<y;
clearInput();
cout<<y;
//return false;
}
else{
cout<<"Invalid row\n"<< endl << endl;
clearInput();
//cout<<x<<y;
//return false;
}
}
}
| cin's clear member function doesn't clear the remaining input, it resets the error flags on the stream (which could get set e.g. because you tried to read an integer but there were non-digit characters in the input). I guess you really want to discard the input up to the next newline; one way to do this would be to call cin.ignore with '\n' as the delimiter.
Another thing that could be an issue (but might just be code left out in the question ;)) is that the while(true) loop that you've written to repeatedly ask for input until there's no error doesn't contain the board-redrawing logic you talk about in your comment. So you won't see this until the getCoords function finds error-free input and returns.
|
2,572,678 | 2,574,408 | C++ STL Map vs Vector speed | In the interpreter for my experimental programming language I have a symbol table. Each symbol consists of a name and a value (the value can be e.g.: of type string, int, function, etc.).
At first I represented the table with a vector and iterated through the symbols checking if the given symbol name fitted.
Then I though using a map, in my case map<string,symbol>, would be better than iterating through the vector all the time but:
It's a bit hard to explain this part but I'll try.
If a variable is retrieved the first time in a program in my language, of course its position in the symbol table has to be found (using vector now). If I would iterate through the vector every time the line gets executed (think of a loop), it would be terribly slow (as it currently is, nearly as slow as microsoft's batch).
So I could use a map to retrieve the variable: SymbolTable[ myVar.Name ]
But think of the following: If the variable, still using vector, is found the first time, I can store its exact integer position in the vector with it. That means: The next time it is needed, my interpreter knows that it has been "cached" and doesn't search the symbol table for it but does something like SymbolTable.at( myVar.CachedPosition ).
Now my (rather hard?) question:
Should I use a vector for the symbol table together with caching the position of the variable in the vector?
Should I rather use a map? Why? How fast is the [] operator?
Should I use something completely different?
| You effectively have a number of alternatives.
Libraries exist:
Loki::AssocVector: the interface of a map implemented over a vector of pairs, faster than a map for small or frozen sets because of cache locality.
Boost.MultiIndex: provides both List with fast lookup and an example of implementing a MRU List (Most Recently Used) which caches the last accessed elements.
Critics
Map look up and retrieval take O(log N), but the items may be scattered throughout the memory, thus not playing well with caching strategies.
Vector are more cache friendly, however unless you sort it you'll have O(N) performance on find, is it acceptable ?
Why not using a unordered_map ? They provide O(1) lookup and retrieval (though the constant may be high) and are certainly suited to this task. If you have a look at Wikipedia's article on Hash Tables you'll realize that there are many strategies available and you can certainly pick one that will suit your particular usage pattern.
|
2,572,891 | 2,572,897 | How are FFTs different from DFTs and how would one go about implementing them in C++? | After some studying, I created a small app that calculates DFTs (Discrete Fourier Transformations) from some input. It works well enough, but it is quite slow.
I read that FFTs (Fast Fourier Transformations) allow quicker calculations, but how are they different? And more importantly, how would I go about implementing them in C++?
| If you don't need to manually implement the algorithm, you could take a look at the Fastest Fourier Transform in the West
Even thought it's developed in C, it officially works in C++ (from the FAQ)
Question 2.9. Can I call FFTW from
C++?
Most definitely. FFTW should compile
and/or link under any C++ compiler.
Moreover, it is likely that the C++
template class is
bit-compatible with FFTW's
complex-number format (see the FFTW
manual for more details).
|
2,572,985 | 2,573,156 | How can I use Qt to get html code of the redirected page? | I'm trying to use Qt to download the html code from the following url:
http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=nucleotide&cmd=search&term=AB100362
this url will re-direct to
www.ncbi.nlm.nih.gov/nuccore/27884304
I try to do it by following way, but I cannot get anything.
it works for some webpage such as www.google.com, but not for this NCBI page. is there any way to get this page??
QNetworkReply::NetworkError downloadURL(const QUrl &url, QByteArray &data)
{
QNetworkAccessManager manager;
QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
if (reply->error() != QNetworkReply::NoError)
{
return reply->error();
}
data = reply->readAll();
delete reply;
return QNetworkReply::NoError;
}
void GetGi()
{
int pos;
QString sGetFromURL = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi";
QUrl url(sGetFromURL);
url.addQueryItem("db", "nucleotide");
url.addQueryItem("cmd", "search");
url.addQueryItem("term", "AB100362");
QByteArray InfoNCBI;
int errorCode = downloadURL(url, InfoNCBI);
if (errorCode != 0 )
{
QMessageBox::about(0,tr("Internet Error "), tr("Internet Error %1: Failed to connect to NCBI.\t\nPlease check your internect connection.").arg(errorCode));
return "ERROR";
}
}
| That page appears to have a redirect.
From the Qt docs for 4.6:
Note: When the HTTP protocol returns a
redirect no error will be reported.
You can check if there is a redirect
with the
QNetworkRequest::RedirectionTargetAttribute
attribute.
|
2,572,994 | 2,573,049 | opengl color quadrangle | i have a programm that creates a black border an white corner (quadrangle).
now i want to make the corner of the quadrangle in an different color.
i don't know where exactly to write the code, and i don't know much a but color4f, i searcherd on google, but didn't get it.
(is there a good description somewhere?)
#include <iostream>
#include <GL/freeglut.h>
void Init()
{
glColor4f(100,0,0,0);
}
void RenderScene() //Zeichenfunktion
{
glLoadIdentity ();
glBegin( GL_POLYGON );
glVertex3f( -0.5, -0.5, -0.5 );
glVertex3f( 0.5, -0.5, -0.5 );
glVertex3f( 0.5, 0.5, -0.5 );
glVertex3f( -0.5, 0.5, -0.5 );
glEnd();
glFlush();
}
void Reshape(int width,int height)
{
}
void Animate (int value)
{
std::cout << "value=" << value << std::endl;
glutPostRedisplay();
glutTimerFunc(100, Animate, ++value);
}
int main(int argc, char **argv)
{
glutInit( &argc, argv ); // GLUT initialisieren
glutInitDisplayMode( GLUT_RGB ); // Fenster-Konfiguration
glutInitWindowSize( 600, 600 );
glutCreateWindow( "inkrement screen; visual screen" ); // Fenster-Erzeugung
glutDisplayFunc( RenderScene ); // Zeichenfunktion bekannt machen
glutReshapeFunc( Reshape );
glutTimerFunc( 10, Animate, 0);
Init();
glutMainLoop();
return 0;
}
| First of all, you probably want glColor3f. glColor4f also takes an alpha (transparency) value, which you probably don't care about yet. The range of parameters is 0 for no intensity and 1 for max intensity of red, green and blue. So you could do something like:
glColor3f( 1.0f, 0.0f, 0.0f ); // red
glVertex3f( -0.5, -0.5, -0.5 ); // this vertex is red
glColor3f( 0.0f, 1.0f, 0.0f ); // green
glVertex3f( 0.5, -0.5, -0.5 ); // this vertex is green
glColor3f( 0.0f, 0.0f, 1.0f ); // blue
glVertex3f( 0.5, 0.5, -0.5 ); // this vertex is blue
glVertex3f( -0.5, 0.5, -0.5 ); // since it wasn't changed, this one will be blue, too
|
2,573,142 | 2,573,168 | c++ shorthand operator-> operator() | Suppose I have:
Foo foo;
is there a shorthand for this?
foo.operator->().operator()(1, 2);
| Assuming you actually meant foo.operator->().operator()(1, 2), and that you have control over the class Foo, a simpler form would be (*foo)(1, 2). It requires the operator* to that defined though, but since we usually expect foo->bar to be equivalent to (*foo).bar, it seems reasonable.
If your Foo is a smart pointer class of some sort, which points to an object which defines an operator(), this would be the most concise way of calling the object's operator().
But without more detail (and without you providing an expression that's actually valid C++ -- there's no way in which operator(1, 2) as you wrote it can be valid), it's impossible to answer your question. I'm just guessing at what you're trying to do.
|
2,573,242 | 2,573,334 | How can I create objects based on dump file memory in a WinDbg extension? | I work on a large application, and frequently use WinDbg to diagnose issues based on a DMP file from a customer. I have written a few small extensions for WinDbg that have proved very useful for pulling bits of information out of DMP files. In my extension code I find myself dereferencing c++ class objects in the same way, over and over, by hand. For example:
Address = GetExpression("somemodule!somesymbol");
ReadMemory(Address, &addressOfPtr, sizeof(addressOfPtr), &cb);
// get the actual address
ReadMemory(addressOfObj, &addressOfObj, sizeof(addressOfObj), &cb);
ULONG offset;
ULONG addressOfField;
GetFieldOffset("somemodule!somesymbolclass", "somefield", &offset);
ReadMemory(addressOfObj+offset, &addressOfField, sizeof(addressOfField), &cb);
That works well, but as I have written more extensions, with greater functionality (and accessing more complicated objects in our applications DMP files), I have longed for a better solution. I have access to the source of our own application of course, so I figure there should be a way to copy an object out of a DMP file and use that memory to create an actual object in the debugger extension that I can call functions on (by linking in dlls from our application). This would save me the trouble of pulling things out of the DMP by hand.
Is this even possible? I tried obvious things like creating a new object in the extension, then overwriting it with a big ReadMemory directly from the DMP file. This seemed to put the data in the right fields, but freaked out when I tried to call a function. I figure I am missing something...maybe c++ pulls some vtable funky-ness that I don't know about? My code looks similar to this:
SomeClass* thisClass = SomeClass::New();
ReadMemory(addressOfObj, &(*thisClass), sizeof(*thisClass), &cb);
FOLLOWUP: It looks like POSSIBLY ExtRemoteTyped from EngExtCpp is what I want? Has anyone successfully used this? I need to google up some example code, but am not having much luck.
FOLLOWUP 2: I am pursuing two different routes of investigation on this.
1) I am looking into ExtRemoteTyped, but it appears this class is really just a helper for the ReadMemory/GetFieldOffset calls. Yes, it would help speed things up ALOT, but doesn't really help when it comes to recreating an object from a DMP file. Although documentation is slim, so I might be misunderstanding something.
2) I am also looking into trying to use ReadMemory to overwrite an object created in my extension with data from the DMP file. However, rather than using sizeof(*thisClass) as above, I was thinking I would only pick out the data elements, and leave the vtables untouched.
| Interesting idea, but this would have a hope of working only on the simplest of objects. For example, if the object contains pointers or references to other objects (or vtables), those won't copy very well over to a new address space.
However, you might be able to get a 'proxy' object to work that when you call the proxy methods they make the appropriate calls to ReadMemory() to get the information. This sounds to be a fair bit of work, and I'd think it would have to be more or less a custom set of code for each class you wanted to proxy. There's probably a better way to go about this, but that's what came to me off the top of my head.
|
2,573,325 | 2,573,387 | std::for_each on a member function with 1 argument | I'm wondering how to implement what is stated in the title. I've tried something like...
std::for_each( a.begin(), a.end(), std::mem_fun_ref( &myClass::someFunc ) )
but I get an error saying that the "term" (I"m assuming it means the 3rd argument) doesn't evaluate to a function with 1 argument, even though someFunc does take one argument - the type of the objects stored in a.
I'm wondering if what I'm trying to do is possible using the standard library (I know I can do it easily using boost).
P.S. Does using for_each and mem_fun_ref have any performance implications in comparison to just iterating through a manually and passing the object to someFunc?
| Even though someFunc is a member with one parameter, mem_fun_ref uses an implicit first argument of "myClass". You want to use the vector's items as the 2nd argument .
And there are probably no negative performance implications of using for_each and mem_fun_ref. The compiler will generate comparable code. But, the only way to be sure is to benchmark :)
std::for_each(a.begin(), a.end(),
std::bind1st(
std::mem_fun_ref( &MyClass::SomeFunc ),
my_class ));
|
2,573,433 | 2,573,441 | Vectors of Pointers, inheritance | Hi I am a C++ beginner just encountered a problem I don't know how to fix
I have two class, this is the header file:
class A
{
public:
int i;
A(int a);
};
class B: public A
{
public:
string str;
B(int a, string b);
};
then I want to create a vector in main which store either class A or class B
vector<A*> vec;
A objectOne(1);
B objectTwo(2, "hi");
vec.push_back(&objectOne);
vec.push_back(&objectTwo);
cout << vec.at(1)->i; //this is fine
cout << vec.at(1)->str; //ERROR here
I am really confused, I checked sites and stuff but I just don't know how to fix it, please help
thanks in advance
| The reason this won't work is because the objects in your vector are of (static) type A. In this context, static means compile-time. The compiler has no way to know that anything coming out of vec will be of any particular subclass of A. This isn't a legal thing to do, so there is no way to make it work as is. You can have a collection of B, and access the str member, or a collection of A and not.
This is in contrast to a language such as Python, where a member will be looked up in an object's dictionary at runtime. C++ is statically typed, so all of your type-checking has to work out when the code is compiled.
|
2,573,435 | 2,574,787 | Clearing cin input: is cin.ignore not a good way? | What's a better way to clear cin input? I thought cin.clear and cin.ignore was a good way?
Code:
void clearInput()
{
cin.clear();
cin.ignore(1000,'\n');
//cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );
}
My teacher gave me this reply:
this is basically saying that your
clearInput doesn't work FYI: ignore
is NEVER a good idea as a way of
getting rid of all that remains on a
line
and your failing this test is exactly
the reason why now go clear it the
correct way
She has also told me this following:
on ignore you need to guess at how
many characters you want to ignore If
you absolutely know your data and it
follows a strict format -- as in Excel
spreadsheets, ignore is really good.
If you are NOT in this type of file,
then you NEVER use ignore. Question,
is your data well-formed? If yes, use
ignore. If not, don't use ignore.
List ALL the way of getting data? 1)
there is extraction >>
and there is also??????
please list for me
| Your teacher’s reply are a bit unclear (at least to me).
Concerning ignore, your teacher is wrong in principle: ignore is the standard idiom of how to clear a stream (as shown by Potatocorn, this is even mentioned in the standard).
However, it’s important to notice that cin.ignore(1000) is indeed a bad way of doing this: this just presumes that there won’t be more than 1000 characters in the buffer. Never use such a magic number in ignore.
Instead, either use
cin.rdbuf()->in_avail() (i.e. the available number of chars in the read buffer)1), or use
numeric_limits<streamsize>::max().
1) Unfortunately, in_avail is broken on some recent VC (?) compilers so this method isn’t very portable.
|
2,573,653 | 2,574,095 | Given a 1 TB data set on disk with around 1 KB per data record, how can I find duplicates using 512 MB RAM and infinite disk space? | There is 1 TB data on a disk with around 1 KB per data record. How do I find duplicates using 512 MB RAM and infinite disk space?
| Use a Bloom filter: a table of simultaneous hashes. According to Wikipedia, the optimal number of hashes is ln(2) * 2^32 / 2^30 ≈ 2.77 ≈ 3. (Hmm, plugging in 4 gives fewer false positives but 3 is still better for this application.) This means that you have a table of 512 megabytes, or 4 gigabits, and processing each record sets three new bits in that vast sea. If all three bits were already set, it's a potential match. Record the three hash-values to a file. Otherwise, record them to another file. Note the record index along with each match.
(If a 5% error rate is tolerable, omit the large file and use the small file as your results.)
When finished, you should have a file of about 49M possible positive matches and a file of 975M negatives which yet may match positives. Read the former into a vector<pair<vector<uint32_t>,vector<uint32_t> > > (indexes in the latter vector, the former can be an array) and sort it. Put the indexes in another vector<uint32_t>; they're already sorted. Read the large file but instead of setting bits a table, find the hash values in the vector. (For example, use equal_range.) Use the list of positive-file indices to track the index of the current record in the negative file. If no match found, ignore. Otherwise, append the record's index match->second.push_back(current_negative_record_index).
Finally, iterate through the map and the vectors of record-indices. Any bucket with more than one entry is "almost" certain to contain a set of duplicates, but you've come this far, so look them up and compare them completely to be sure.
Total synchronous disk I/O: (one pass = 1 TiB) + (96 hash bits per record = 12 GiB) + (32 index bits per positive = ~200 MiB).
Final edit (seriously): On second thought, the Bloom Filter aspect might not really be helping here. The amount of hash data is more of a limiting factor than the number of false positives. With just one hash function, the total amount of hash data would be 4 GiB and the indexes of the 124 million expected false positives would be ~500 MiB. That should globally optimize this strategy.
Clarification (got a downvote): there's a distinction between a false positive from the Bloom filter and a hash collision. A hash collision can't be resolved except by returning to the original records and comparing, which is expensive. A Bloom false positive can be resolved by returning to the original hash values and comparing them, which is what the second pass of this algorithm does. So on second thought, the one-hash filter described in the "final" edit would unduly cause disk seeks. A two-hash Bloom filter would increase the number of false positives ending up in a single bucket of the match map, and would bring the number of false positives back down to the tens of millions.
|
2,573,701 | 2,591,117 | llvm clang struct creating functions on the fly | I'm using LLVM-clang on Linux.
Suppose in foo.cpp I have:
struct Foo {
int x, y;
};
How can I create a function "magic" such that:
typedef (Foo) SomeFunc(Foo a, Foo b);
SomeFunc func = magic("struct Foo { int x, y; };");
so that:
func(SomeFunc a, SomeFunc b); // returns a.x + b.y;
?
Note:
So basically, "magic" needs to take a char*, have LLVM parse it to get how C++ lays out the struct, then create a function on the fly that returns a.x + b.y;
| If you really want to do this kind of stuff, you have to link in the whole CLang, and learn how to use its complicated and constantly changing API. Are you so sure you actually need it?
|
2,573,726 | 2,573,749 | How to use boost::crc? | I want to use boost::crc so that it works exactly like PHP's crc32() function. I tried reading the horrible documentation and many headaches later I haven't made any progress.
Apparently I have to do something like:
int GetCrc32(const string& my_string) {
return crc_32 = boost::crc<bits, TruncPoly, InitRem, FinalXor,
ReflectIn, ReflectRem>(my_string.c_str(), my_string.length());
}
bits should be 32.. What the other things are is a mystery. A little help? ;)
| Dan Story and ergosys provided good answers (apparently I was looking in the wrong place, that's why the headaches) but while I'm at it I wanted to provide a copy&paste solution for the function in my question for future googlers:
#include <boost/crc.hpp>
uint32_t GetCrc32(const string& my_string) {
boost::crc_32_type result;
result.process_bytes(my_string.data(), my_string.length());
return result.checksum();
}
|
2,573,817 | 2,573,830 | Is a control tree cached after the first call to FindWindowEx/EnumChildWindows? | I noticed that if you call FindWindowEx or EnumChildWindows against a hWnd that belongs to a window that's not in the foreground, i.e. minimized, then they don't report any children. On the other hand if I first call SetForegroundWindow against the window I'm querying, and after that FindWindowEx or EnumChildWindows, they report all the children. Next calls report all the children even if the window I'm interested in is not in foreground. It's almost it does some sort of caching after the first call?
| Is this a window in your own application, or are you investigating what a third-party application does?
I would guess that the application only creates its child windows the first time it is brought into the foreground; this would explain the behaviour you are seeing. To my knowledge, EnumChildWindows does not perform any caching.
|
2,574,041 | 2,574,106 | Binary Search Tree node removal | I've been trying to implement a delete function for a Binary Search Tree but haven't been able to get it to work in all cases.
This is my latest attempt:
Node* RBT::BST_remove(int c)
{
Node* t = get_node(c);
Node* temp = t;
if(t->get_left() == empty)
*t = *t->get_left();
else if(t->get_right() == empty)
*t = *t->get_right();
else if((t->get_left() != empty) && (t->get_right() != empty))
{
Node* node = new Node(t->get_data(), t->get_parent(), t->get_colour(), t->get_left(), t->get_right());
*t = *node;
}
return temp;
}
Node* RBT::get_node(int c)
{
Node* pos = root;
while(pos != empty)
{
if(c < pos->get_data())
pos = pos->get_left();
else if(c == pos->get_data())
return pos;
else
pos = pos->get_right();
}
return NULL;
}
t is a node and empty is just a node with nothing in it.
I'm just trying to swap the values but I'm getting a runtime error. Any ideas?
edit: I'm returning temp to delete it afterwards.
Thanks
| First, your last else if conditional clause is redundant. Swap it with an else clause.
Secondly, I think it would make things easier for you if you'd take as parameter a pointer to the node to remove. You can write a find() function which would find a node given its key. I'm assuming of course that you can change the function signature. If you can take as parameter the node to remove you can focus on removing the node rather than add logic for finding the node. Otherwise, still write that find() function and use that for getting the pointer to the relevant node.
When you remove a node in a binary search tree you must maintain the ordering so the tree doesn't lose its integrity. Recall that there is a specific ordering in the tree that supports the fast retrieval of elements. So, enumerate the possible cases:
The node to delete has no children. That's easy: just release its resources and you're done.
The node has a single child node. That's fairly simple too. Release the node and replace it with its child, so the child holds the removed node's place in the tree.
The node has two children. Let's call the node D. Find the right-most child of D's left subtree. Let's call this node R. Assign the value of R to D, and delete R (as described in this algorithm). Notice that R can have zero or one children.
The third scenario, illustrated:
.
.
.
/
D
/ \
/\ .
/ \
/ \
+------+
\
R
/
?
|
2,574,060 | 2,574,065 | C++ min heap with user-defined type | I am trying to implement a min heap in c++ for a struct type that I created. I created a vector of the type, but it crashed when I used make_heap on it, which is understandable because it doesn't know how to compare the items in the heap. How do I create a min-heap (that is, the top element is always the smallest one in the heap) for a struct type?
The struct is below:
struct DOC{
int docid;
double rank;
};
I want to compare the DOC structures using the rank member. How would I do this?
I tried using a priority queue with a comparator class, but that also crashed, and it also seems silly to use a data structure which uses a heap as its underlying basis when what I really need is a heap anyway.
Thank you very much,
bsg
| Add a comparison operator:
struct DOC{
int docid;
double rank;
bool operator<( const DOC & d ) const {
return rank < d.rank;
}
};
Structures can almost always usefully have a constructor, so I would also add:
DOC( int i, double r ) : docid(i), rank(r) {]
to the struct as well.
|
2,574,183 | 2,581,497 | How can I load an MP3 or similar music file for display and analysis in wxWidgets? | I'm developing a GUI in wxPython which allows a user to generate sequences of colours for some toys I'm building. Part of the program needs to load an MP3 (and potentially other formats further down the line) and display it to the user. That should be sufficient to get started but later I'd like to add features like identifying beats and some crude frequency analysis.
Is there any simple way of loading / understanding an MP3's contents to display a plot of its amplitudes to the screen using wxWidgets?
I later intend to port to C++/wxWidgets for speed and to avoid having to distribute wxPython.
| After a little more googling, I think PyMedia might well be a good place to start at least as far as a Python implementation goes.
|
2,574,350 | 2,574,360 | gluLookAt doesn't work | i'm programming with opengl and i want to change the camera view:
...
void RenderScene() //Zeichenfunktion
{
glClearColor( 1.0, 0.5, 0.0, 0 );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity ();
//1.Form:
glBegin( GL_POLYGON ); //polygone
glColor3f( 1.0f, 0.0f, 0.0f ); //rot
glVertex3f( -0.5, -0.5, -0.5 ); //unten links 3 =3 koords, f=float
glColor3f( 0.0f, 0.0f, 1.0f ); //blau
glVertex3f( 0.5, -0.5, -0.5 ); //unten rechts
glVertex3f( 0.5, 0.5, -0.5 );//oben rechts
glVertex3f( -0.5, 0.5, -0.5 );//oben links
glEnd();
Wuerfel(0.7); //creates cube with length 0.7
gluLookAt ( 0., 0.3, 1.0, 0., 0.7, 0., 0., 1., 0.);
glFlush(); //Buffer leeren
}
...
when i change the parameter of gluLookAt, nothing happens, what do i wrong?
thanks
| gluLookAt modifies the current transform matrix, so it only has effect on things rendered after the call. Try putting gluLookAt before your rendering code.
|
2,574,358 | 2,574,365 | if i want to build logger class in c++ or java what should it be singletone or static | general question is i like to build logger class that writes to single log file
from different classes in my application what should the logger class be
singletone or static class
| In C++ you'll want a singleton rather than a static. C++ does not allow you to control the order static objects are constructed and destructed, and if you tried to log before the static was constructed behaviour would possibly be undefined.
I'm not sure about Java.
|
2,574,416 | 2,574,473 | Testing of coding and naming conventions of C/C++ code | I'm looking for a script/tool that can be customized to check and enforce coding/naming conventions on a C/C++ code.
It should check for example:
Code lines are wrapped at some length.
Private variables have prefix _
Code is indented properly.
All functions are documented.
Many of the projects I'm working on are outsourced by customers which tend to have various internal coding and naming conventions.
| The GNU indent tool can do some of what you're asking for. Not sure if it can check for documentation, but the rest sounds doable
|
2,574,458 | 2,574,471 | Parsing/executing C# code in C++ (on Linux)? | I want to be able to add scripting functionality to my application. One of the language bindings I am considering is C# (and possibly VB.Net).
The challenge is this:
My application is developed in C++
My application runs on Linux
I am aware of Mono, but I dont know (as yet), what is required to allow my C++ appliaction (running on linux), to be scriptable with .Net languages.
Is this feasible?
Am I crazy for even thinking of doing this?
If I'm not crazy, can anyone provide some guidelines on how to go about implementing this?
Help, tips, ideas, suggestions anyone?
| The Mono framework has an option specifically designed to allow embedding in C / C++ application. My suggestion would be to spend some time reading the documentation.
|
2,574,547 | 2,574,574 | C++ setting up "flags" | Example:
enum Flags
{
A,
B,
C,
D
};
class MyClass
{
std::string data;
int foo;
// Flags theFlags; (???)
}
How can I achieve that it is possible to set any number of the "flags" A,B,C and D in the enum above in an instance of MyClass?
My goal would be something like this:
if ( MyClassInst.IsFlagSet( A ) ) // ...
MyClassInst.SetFlag( A ); //...
Do I have to use some array or vector? If yes, how?
Are enums a good idea in this case?
| // Warning, brain-compiled code ahead!
const int A = 1;
const int B = A << 1;
const int C = B << 1;
const int D = C << 1;
class MyClass {
public:
bool IsFlagSet(Flags flag) const {return 0 != (theFlags & flag);}
void SetFlag(Flags flag) {theFlags |= flag;}
void UnsetFlag(Flags flag) {theFlags &= ~flag;}
private:
int theFlags;
}
|
2,574,549 | 2,575,145 | Forward declare HINSTANCE and friends | Is there a way to forward-declare the HINSTANCE type from the WinAPI without including the full (and big) windows.h header?
For example, if I have a class RenderWindow which owns an HINSTANCE mInstance, i will have to include windows.h in RenderWindow.h. So everything that needs RenderWindow also has to include windows.h.
I tried including windef.h but this seems to need some things from windows.h. :-( If I can't forward declare it, is there at least a portable way to use something like long mInstance in RenderWindow instead of HINSTANCE?
| HINSTANCE is declared in WinDef.h as typedef HINSTANCE__* HINSTANCE;
You may write in your headers:
#ifndef _WINDEF_
class HINSTANCE__; // Forward or never
typedef HINSTANCE__* HINSTANCE;
#endif
You will get compilation errors referencing a HINSTANCE when WinDef.h is not included.
|
2,574,904 | 2,574,932 | How to speed-up a simple method (preferably without changing interfaces or data structures)? | I have some data structures:
all_unordered_m is a big vector containing all the strings I need (all different)
ordered_m is a small vector containing the indexes of a subset of the strings (all different) in the former vector
position_m maps the indexes of objects from the first vector to their position in the second one.
The string_after(index, reverse) method returns the string referenced by ordered_m after all_unordered_m[index].
ordered_m is considered circular, and is explored in natural or reverse order depending on the second parameter.
The code is something like the following:
struct ordered_subset {
// [...]
std::vector<std::string>& all_unordered_m; // size = n >> 1
std::vector<size_t> ordered_m; // size << n
std::tr1::unordered_map<size_t, size_t> position_m;
const std::string&
string_after(size_t index, bool reverse) const
{
size_t pos = position_m.find(index)->second;
if(reverse)
pos = (pos == 0 ? orderd_m.size() - 1 : pos - 1);
else
pos = (pos == ordered.size() - 1 ? 0 : pos + 1);
return all_unordered_m[ordered_m[pos]];
}
};
Given that:
I do need all of the data-structures for other purposes;
I cannot change them because I need to access the strings:
by their id in the all_unordered_m;
by their index inside the various ordered_m;
I need to know the position of a string (identified by it's position in the first vector) inside ordered_m vector;
I cannot change the string_after interface without changing most of the program.
How can I speed up the string_after method that is called billions of times and is eating up about 10% of the execution time?
EDIT:
I've tried making position_m a vector instead of a unordered_map and using the following method to avoid jumps:
string_after(size_t index, int direction) const
{
return all_unordered_m[ordered_m[
(ordered_m.size()+position_m[index]+direction)%ordered_m.size()]];
}
The change in position_m seems to be the most effective (I'm not sure that eliminating the branches made any difference, I'm tempted to say that the code is more compact but equally efficient with that regard).
| vector lookups are blazing fast. size() calls and simple arithmetic are blazing fast. map lookups, in comparison, are as slow as a dead turtle with a block of concrete on his back. I have often seen those become a bottleneck in otherwise simple code like this.
You could try unordered_map from TR1 or C++0x (a drop-in hashtable replacement of map) instead and see if that makes a difference.
|
2,574,915 | 2,575,677 | Question on multi-probe Local Sensitive Hashing | sorry to be asking this kind noob question, but because I really need some guidance on how to use Multi probe LSH pretty urgently, so I did not do much research myself. I realize there is a lib call LSHKIT available that implemented that algorithm, but I have trouble trying to figure out how to use it.
Right now, I have a few thousand feature vector 296 dimension, each representing an image. The vector is used to query an user input image, to retrieve the most similar image. The method I used to derive the distance between vector is euclidean distance.
I know this might be a rather noob question, but do you guys have knowledge on how should i implement multi probe LSH? I am really very grateful to any answer or response.
-- update --
Tried to create a model for my data with the provided tool fitdata, however it doesn't seem to take in my file. The format I used for the input is in this format,float size : 4, number of data : 20, dimension : 297, and my array of 297 dimenison float array. However it give me this error
gsl: init_source.c:29: ERROR: matrix dimension n1 must be positive integer
Default GSL error handler invoked.
Aborted
Do you guys have any idea how to create a input for fitdata?
-- update --
Sorry for the late update, after trying out lsh. You can use the text2bin to format the data for fitdata. The text file contain the feature vector of the image or audio file, with each row representating an vector. After which, use mplsh-tune to get the M and W parameter.
To construct the index, you can use the scan tool to sample a set of required query and you can use mplsh-run to get the index.
Right now i trying to figure out how to use the index and how to link the library into my coding. Any body have any idea on this?
| Let me instead point you to spectral hashing which kicks LSH's butt big time. Bonus: They have matlab code on their website, which you can either use or verify your own implementation against. Also, it's much easier to implement.
|
2,575,002 | 2,575,045 | C++ Template Classes and Copy Construction | Is there any way I can construct an new object from the given object if the template parameters of both objects are identical at run-time? For example:
I have a template class with the declaration:
template<typename _Type1, typename _Type2> class Object;
Next, I have two instantiations of the template:
template class Object<char, int>;
template class Object<wchar_t, wint_t>;
Now, I want to write a member function such as:
template<typename _Type1, typename _Type2>
Object<char, int> Object<_Type1, _Type2>::toCharObject() {
if(__gnu_cxx::__are_same<_Type1, char>::__value)
return *this;
else {
//Perform some kind of conversion and return an Object<char, int>
}
}
I have tried a couple of techniques, such as using __gnu_cxx::__enable_if<__gnu_cxx::__are_same<_Type1, char>::__value, _Type1>::__type in a copy constructor for the Oject class, but I keep running into the error:
error: conversion from ‘Object<wchar_t, wint_t>’ to non-scalar type ‘Object<char, int>’ requested
Is there no way I can do this? Any help will be greatly appreciated!
| What you have should work, the problem is that the compiler is doing a type check on the return *this part, even if the types aren't equal (hence the compile error). Just use return (Object<char, int>)(*this); and you should be fine -- the only time that code will be executed is when the types are the same anyway, so the cast does nothing other than working around the compile error.
Alternatively, you can use template specialisation:
template <class _Type1, class _Type2>
Object<char, int> toCharObject(Object<_Type1, _Type2> obj)
{
// Do conversion and return
}
// Specialisation when types are equal
template <>
Object<char, int> toCharObject(Object<char, int> obj)
{
return obj;
}
This is a free function as you can see. You can do it as a member function, but it's more tricky because you can't specialise individual member function -- you have to specialise the whole class. You can get around that by factoring out the non-specialised code, but that's really ugly, and this works just as well.
|
2,575,059 | 2,575,076 | Book on C++ for understanding advanced concepts | What is good book for industry level C++ programming?
I am not looking for a beginners C++ book that talks about datatypes and control structures. I am looking for a more advanced book. For example, how to build system applications using C++.
Any kind of guidance will be very helpful.
| Modern C++ Design by Andrei Alexandrescu is probably the most advanced C++ book out there. It's more about very advanced design patterns rather than building software.
|
2,575,095 | 2,575,394 | Why aren't these shared_ptrs pointing to the same container? | I have a class Model:
class Model
{
...
boost::shared_ptr<Deck> _deck;
boost::shared_ptr<CardStack> _stack[22];
};
Deck inherits from CardStack.
I tried to make _stack[0] point to the same thing that _deck points to by going:
{
_deck = boost::shared_ptr<Deck>(new Deck());
_stack[0] = _deck;
}
It seems that the assignment to _deck of _stack[0] results in a copy of _deck being made. (I know this because modifications to _stack[0] do not result in modifications to _deck.) How can I get them to point to the same thing?
Ok - no copy constructor is being called. I have verified this by implementing it and seeing if it gets called - it doesn't.
However - I have a function that operates on CardStack objects:
void TransferSingleCard(CardStack & src, CardStack & dst, Face f)
{
if( !src._cards.empty() )
{
src._cards.back().SetFace(f);
dst.PushCard(src._cards.back());
src._cards.pop_back();
}
}
Now - when I call:
{
TransferSingleCard(*_stack[DECK], _someotherplace, FACEDOWN);
std::cout << *_stack[DECK];
std::cout << *_deck;
}
I get this output (where std::cout on a CardStack will print out the size of that stack):
Num(103) TOP
Num(104) TOP
... so I've concluded (incorrectly?) that _stack[DECK] points to something different.
The Deck
class Deck : public CardStack
{
public:
Deck(int numsuits=2, StackIndex index = NO_SUCH_STACK );
Deck::Deck( const Deck & d);
int DealsLeft() const;
void RecalcDealsLeft();
private:
int _dealsleft;
};
| This example - derives from @Neil's answer, tries to emulate what you say is happening. Could you check that it works as expected (A and B have the same count) on your system.
Then we could try and modify this code or your code until they match.
#include <boost/shared_ptr.hpp>
#include <iostream>
class A {
public:
virtual ~A()
{
std::cerr << "Delete A" << std::endl;
}
int _count;
void decrement()
{
_count --;
}
};
class B : public A {
public:
virtual ~B()
{
std::cerr << "Delete B" << std::endl;
}
};
int main()
{
boost::shared_ptr<B> b(new B);
b->_count = 104;
boost::shared_ptr<A> a;
a = b;
a->decrement();
std::cerr << "A:" << a->_count << std::endl;
std::cerr << "B:" << b->_count << std::endl;
return 0;
}
EDIT:
So from the comment, we know the original pointers are correct, so now we need to trace.
Either:
log pointers to see when they change.
Use watchpoints in a debugger to see when the pointer changes.
Use a third shared pointer to see which pointer is changed.
Introduce a function that changes both pointers at the same time.
|
2,575,128 | 2,575,134 | Calling a method of a constant object parameter | Here is my code that fails:
bool Table::win(const Card &card) {
for (int i = 0; i < cards.size(); i++)
if (card.getRank() == cards[i].getRank()) return true;
return false;
}
Error message is: passing 'const Card' as 'this' argument of 'int Card::getRank()' discards qualifiers.
When I get a copy of the card and change the code to this it works:
bool Table::win(const Card &card) {
Card copyCard = card;
for (int i = 0; i < cards.size(); i++)
if (copyCard.getRank() == cards[i].getRank()) return true;
return false;
}
Is there any other way to do this?
| Is getRank a const-method? It should be declared like this":
int getRank( ) const;
Assuming the return type is int.
|
2,575,265 | 2,575,490 | Distinct rand() sequences yielding the same results in an expression | Ok, this is a really weird one.
I have an MPI program, where each process has to generate random numbers in a fixed range (the range is read from file). What happens is that even though I seed each process with a different value, and the numbers generated by rand() are different in each process, the expression to generate the random numbers still yields the same sequence between them.
Here's all relevant code:
// 'rank' will be unique for each process
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// seed the RNG with a different value for each process
srand(time(NULL) + rank);
// print some random numbers to see if we get a unique sequence in each process
// 'log' is a uniquely named file, each process has its own
log << rand() << " " << rand() << " " << rand() << std::endl;
// do boring deterministic stuff
while (true)
{
// waitTimeMin and waitTimeMax are integers, Max is always greater than Min
waitSecs = waitTimeMin + rand() % (waitTimeMax - waitTimeMin);
log << "waiting " << waitSecs << " seconds" << std::endl;
sleep(waitSecs);
// do more boring deterministic stuff
}
Here's the output of each process, with 3 processes generating numbers in the range [1,9].
process 1:
15190 28284 3149
waiting 6 seconds
waiting 8 seconds
waiting 9 seconds
waiting 4 seconds
process 2:
286 6264 3153
waiting 6 seconds
waiting 8 seconds
waiting 9 seconds
waiting 4 seconds
process 3:
18151 17013 3156
waiting 6 seconds
waiting 8 seconds
waiting 9 seconds
waiting 4 seconds
So while rand() clearly generates different numbers, the expression to calculate waitSecs still evaluates to the same sequence on all processes. What's even weirder: if I run the program with the same parameteres again, only the first 3 random numbers will change, the rest of the "random" sequence will be exactly the same in each run! Changing the range of numbers will obviously produce a different result from this one, but the same parameters always yield the same sequence, between processes and between executions: except for the first 3 numbers.
Just what the hell is going on here?
EDIT: So just to see if it's the simplistic random generation and/or low range, I replaced the random generation with this line:
waitSecs = waitTimeMin + (int)((double)rand() / ((double)RAND_MAX + 1) * (waitTimeMax - waitTimeMin));
And started generating numbers in the range [1,99]. Here's the result:
process 1:
7833 3798 10977
waiting 1 seconds
waiting 20 seconds
waiting 58 seconds
waiting 35 seconds
waiting 82 seconds
waiting 18 seconds
process 2:
25697 14547 10980
waiting 1 seconds
waiting 20 seconds
waiting 58 seconds
waiting 35 seconds
waiting 82 seconds
waiting 18 seconds
process 3:
10794 25295 10984
waiting 1 seconds
waiting 20 seconds
waiting 58 seconds
waiting 35 seconds
waiting 82 seconds
waiting 18 seconds
Same thing. Can this still be just rand() being really bad?
EDIT2: Same thing when generating numbers from 1 to 10000.
| Ok, apparently I'm retarded. After initializing the RNG, I spawned a new thread and generated the random numbers there, without initialization. Calling srand() in the new thread fixed the problem. So yeah, the lesson here is that srand() and rand() work per thread, not per process. I also need to start posting more information about my program in my questions.
Ouch.
Sorry for wasting everyone's time.
|
2,575,293 | 2,575,316 | Other test cases for this openFile function? | I am trying to figure out why my function to open a file is failing this autograder I submit my homework into. What type of input would fail here, I can't think of anything else?
Code:
bool openFile(ifstream& ins)
{
char fileName[256];
cout << "Enter board filename: ";
cin.getline(fileName,256);
cout << endl << fileName << endl;
ins.open(fileName);
if(!ins) {
ins.clear();
cout<<"Error opening file"<<endl;
return false;
}
return true;
}
Here is output from the 'Autograder' of what my program's output is, and what the correct output is supposed to be (and I do not know what is in the file they use for the input)
Autograder output:
*******************************************
***** *****
***** Your output is: *****
***** *****
*******************************************
Testing function openFile
Enter board filename:
test.txt
1
Enter board filename:
not a fileName
Error opening file
0
*******************************************
***** *****
***** Correct Output *****
***** *****
*******************************************
Testing function openFile
Enter board filename:
1
Enter board filename:
Error opening file
0
| Well, you do know what the input is that they use. It appears in your program's output! The first input file name is test.txt, the second is not a fileName.
Anyway, it seems that you're printing the filename after you receive it. But no printed filename appears in the correct output. Just stop printing it might help.
(Does anyone else think that the design of this autograder is stupid? When I was being graded by those things, they wouldn't show our own program's output. At least we'd have to set up an SMTP session to have the test input e-mailed to us...)
|
2,575,296 | 2,575,309 | C++ polymorphism and slicing | The following code, prints out
Derived
Base
Base
But I need every Derived object put into User::items, call its own print function, but not the base class one. Can I achieve that without using pointers? If it is not possible, how should I write the function that deletes User::items one by one and frees memory, so that there should not be any memory leaks?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Base{
public:
virtual void print(){ cout << "Base" << endl;}
};
class Derived: public Base{
public:
void print(){ cout << "Derived" << endl;}
};
class User{
public:
vector<Base> items;
void add_item( Base& item ){
item.print();
items.push_back( item );
items.back().print();
}
};
void fill_items( User& u ){
Derived d;
u.add_item( d );
}
int main(){
User u;
fill_items( u );
u.items[0].print();
}
| You need to use pointers, and you need to give your base class a virtual destructor. The destructor does not have to do anything, but it must exist. Your add function then looks like:
void add_item( Base * item ){
item->print();
items.push_back( item );
}
where items is a vector<Base *>. To destroy the items (assuming a virtual destructor):
for( int i = 0; i < items.size(); i++ ) {
delete items[i];
}
items.clear();
|
2,575,373 | 2,575,431 | Codechef practice question help needed - find trailing zeros in a factorial | I have been working on this for 24 hours now, trying to optimize it. The question is how to find the number of trailing zeroes in factorial of a number in range of 10000000 and 10 million test cases in about 8 secs.
The code is as follows:
#include<iostream>
using namespace std;
int count5(int a){
int b=0;
for(int i=a;i>0;i=i/5){
if(i%15625==0){
b=b+6;
i=i/15625;
}
if(i%3125==0){
b=b+5;
i=i/3125;
}
if(i%625==0){
b=b+4;
i=i/625;
}
if(i%125==0){
b=b+3;
i=i/125;
}
if(i%25==0){
b=b+2;
i=i/25;
}
if(i%5==0){
b++;
}
else
break;
}
return b;
}
int main(){
int l;
int n=0;
cin>>l; //no of test cases taken as input
int *T = new int[l];
for(int i=0;i<l;i++)
cin>>T[i]; //nos taken as input for the same no of test cases
for(int i=0;i<l;i++){
n=0;
for(int j=5;j<=T[i];j=j+5){
n+=count5(j); //no of trailing zeroes calculted
}
cout<<n<<endl; //no for each trialing zero printed
}
delete []T;
}
Please help me by suggesting a new approach, or suggesting some modifications to this one.
| Use the following theorem:
If p is a prime, then the highest
power of p which divides n! (n
factorial) is [n/p] + [n/p^2] +
[n/p^3] + ... + [n/p^k], where k is
the largest power of p <= n, and [x] is the integral part of x.
Reference: PlanetMath
|
2,575,468 | 2,575,483 | string to byte array | How do I input DEADBEEF and output DE AD BE EF as four byte arrays?
| void hexconvert( char *text, unsigned char bytes[] )
{
int i;
int temp;
for( i = 0; i < 4; ++i ) {
sscanf( text + 2 * i, "%2x", &temp );
bytes[i] = temp;
}
}
|
2,575,510 | 2,575,648 | GUI options for emulator c++ | I want to create a Gameboy emulator which runs directly from the exe file, in a similar fashion to visualboy advance. I was wondering in terms of creating a GUI interface for the emulator what would be the best option to accomplish this ?
| Do you just want a way to do 2D rendering? If so there are numerous ways. wxWidgets (as suggested), QT or SDL provide easy cross platform options.
Otherwise you could do it in any number of platform specific ways from using Windows GDI to using D3D11 or whatever platform rendering choices you have available.
|
2,575,581 | 2,575,598 | Visual Studio CLR project | so I wanted to try my first CLR project in Visual C++. So I created console project, but since every tutorial I found about CLR programming was using C#, or windows forms, I just tried writing standart c++ Hello Word app using iostream (I think code isnt needed in this case) but I though it will give me some compile error, since iostream uses precompiled functions, and CLR app compiles into MSIL. I assumed that CLR programming using C++ means just using C++ syntax, but different functions for I/O and so. So, basicly, what I want to ask is, can any native console C++ app be compiled into MSIL and run by .NET framework?
| can any native console C++ app be compiled into MSIL and run by .NET?
Most code can see http://msdn.microsoft.com/en-us/library/aa712815.aspx for the exceptions.
Your application will still use native code thought. There's also /clr:pure if you want to ensure only CLR code is used.
|
2,575,684 | 2,575,703 | Interpreter in C++: Function table storage problem | In my interpreter I have built-in functions available in the language like print exit input, etc.
These functions can obviously be accessed from inside the language. The interpreter then looks for the corresponding function with the right name in a vector and calls it via a pointer stored with its name.
So I gather all these functions in files like io.cpp, string.cpp, arithmetic.cpp. But I have to add every function to the function list in the interpreter in order for it to be found.
So in these function files I have things like:
void print( arg )
{
cout << arg.ToString;
}
I'd add this print function to the interpreter function list with:
interpreter.AddFunc( "print", print );
But where should I call the interpreter.AddFunc?
I can't just put it there below the print function as it has to be in a function according to the C++ syntax.
Where and how should all the functions be added to the list?
| In each module (io, string, etc.), define a method that registers the module with the interpreter, e.g.:
void IOModule::Register(Interpreter &interpreter) {
interpreter.AddFunc( "print", print );
//...
}
This can also be a normal function if your module is not implemented in a class.
Then in your application's main initialization, call the register method of all modules.
This approach helps keep things modular: The main application initialization needs to know which modules exist, but the details of which functions are exported are left to the module itself.
|
2,575,745 | 2,575,753 | c++ link temporary allocations in function to custom allocator? | I am currently working on some simple custom allocators in c++ which generally works allready. I also overloaded the new/delete operators to allocate memory from my own allocator. Anyways I came across some scenarios where I don't really know where the memory comes from like this:
void myFunc(){
myObj testObj();
....do something with it
}
In this case testObj would only be valid inside the function, but where would its memory come from? Is there anyway I could link it to my allocator? Would I have to create to object using new and delete or is there another way?
Thanks
| (myObj testObj(); declares a function named testObj which returns a myObj. Use myObj testObj; instead.)
The memory comes from the stack. It will be auto-matically destroyed when leaving the scope.
To use your new and delete you must of course call new and delete:
myObj* p_testObj = new myObj;
...
delete p_testObj;
But allocation on stack is the most efficient since it just involves 1 instruction sub esp, ??. I don't see a reason to use custom allocation unless myObj is huge.
|
2,575,748 | 2,575,792 | Applying policy based design question | I've not read the Modern C++ Design book but have found the idea of behavior injection through templates interesting. I am now trying to apply it myself.
I have a class that has a logger that I thought could be injected as a policy. The logger has a log() method which takes an std::string or std::wstring depending on its policy:
// basic_logger.hpp
template<class String>
class basic_logger
{
public:
typedef String string_type;
void log(const string_type & s) { ... }
};
typedef basic_logger<std::string> logger;
typedef basic_logger<std::wstring> wlogger;
// reader.hpp
template<class Logger = logger>
class reader
{
public:
typedef Logger logger_type;
void read()
{
_logger.log("Reading...");
}
private:
logger_type _logger;
};
Now the questing is, should the reader take a Logger as an argument, like above, or should it take a String and then instantiate a basic_logger as an instance variable? Like so:
template<class String>
class reader
{
public:
typedef String string_type;
typedef basic_logger<string_type> logger_type;
// ...
private:
logger_type _logger;
};
What is the right way to go?
| To actually be using a policy class, the policy needs to be a template parameter. One example is the char_traits parameter to basic_string, even though that's implemented differently than MC++D's policies, which use inheritance to make use of the empty base class optimization and to allow easy addition to a class's public interface (in a much better way than wrapping each possible method; again, read MC++D). You can still provide a default:
template<class String, class Logger=basic_logger<String> >
struct reader : Logger {
void read() {
this->log("Reading...");
}
};
|
2,575,866 | 2,575,901 | Dynamic creation of a pointer function in c++ | I was working on my advanced calculus homework today and we're doing some iteration methods along the lines of newton's method to find solutions to things like x^2=2. It got me thinking that I could write a function that would take two function pointers, one to the function itself and one to the derivative and automate the process. This wouldn't be too challenging, then I started thinking could I have the user input a function and parse that input (yes I can do that). But can I then dynamically create a pointer to a one-variable function in c++. For instance if x^2+x, can I make a function double function(double x){ return x*x+x;} during run-time. Is this remotely feasible, or is it along the lines of self-modifying code?
Edit:
So I suppose how this could be done if you stored the information in an array and that had a function that evaluated the information stored in this array with a given input. Then you could create a class and initialize the array inside of that class and then use the function from there. Is there a better way?
| You can't dynamically create a function in the sense that you can generate raw machine code for it, but you can quite easily create mathematical expressions using polymorphism:
struct Expr
{
virtual double eval(double x) = 0;
};
struct Sum : Expr
{
Sum(Expr* a, Expr* b):a(a), b(b) {}
virtual double eval(double x) {return a->eval(x) + b->eval(x);}
private:
Expr *a, *b;
};
struct Product : Expr
{
Product(Expr* a, Expr* b):a(a), b(b) {}
virtual double eval(double x) {return a->eval(x) * b->eval(x);}
private:
Expr *a, *b;
};
struct VarX : Expr
{
virtual double eval(double x) {return x;}
};
struct Constant : Expr
{
Constant(double c):c(c) {}
virtual double eval(double x) {return c;}
private:
double c;
};
You can then parse your expression into an Expr object at runtime. For example, x^2+x would be Expr* e = new Sum(new Product(new VarX(), new VarX()), new VarX()). You can then evaluate that for a given value of x by using e->eval(x).
Note: in the above code, I have ignored const-correctness for clarity -- you should not :)
|
2,575,973 | 2,575,977 | Overload assignment operator for assigning sql::ResultSet to struct tm | Are there exceptions for types which can't have thier assignment operator overloaded?
Specifically, I'm wanting to overload the assignment operator of a struct tm (from time.h) so I can assign a sql::ResultSet to it.
I already have the conversion logic:
sscanf(sqlresult->getString("StoredAt").c_str(), "%d-%d-%d %d:%d:%d",
&TempTimeStruct->tm_year, &TempTimeStruct->tm_mon, &TempTimeStruct->tm_mday,
&TempTimeStruct->tm_hour, &TempTimeStruct->tm_min, &TempTimeStruct->tm_sec);
I tried the overload with this:
tm& tm::operator=(sql::ResultSet & results)
{
/*CODE*/
return *this;
}
However VS08 reports:
error C2511: 'tm &tm::operator =(sql::ResultSet &)' : overloaded member function not found in 'tm'
| The assignment operator must be a member function (of struct tm in this case), so the only way of doing this would be to modify the standard library itself, something you should definitely not do. You can of course write a named free function to do whatever you want.
|
2,576,004 | 2,576,025 | Any C/C++ to non-native bytecode compiler/interpreters? | As the title indicates, are there any C/C++ bytecode compilers/interpreters? I'm writing an application in an interpreted language that depends on certain libraries that are fully cross-compilable (there are no special flags to indicate code changes during compilation for a certain platform) but are written in C and C++. Rather than shipping n-platform-specific-libs with each platform, it would be nice to ship one set of libs which are interpreted by one platform specific interpreter.
Possible and/or available?
EDIT1:
The interpreted language in question is Python, though I may also use Ruby.
| Which interpreted language are you using? If it has a .NET based implementation (e.g. IronPython) you could possibly use it with the C++/CLI compiler to produce byte code for the .NET CLR and Mono.
This is only likely to be feasible if you have full control over your C++ libraries.
|
2,576,022 | 2,576,207 | efficient thread-safe singleton in C++ | The usual pattern for a singleton class is something like
static Foo &getInst()
{
static Foo *inst = NULL;
if(inst == NULL)
inst = new Foo(...);
return *inst;
}
However, it's my understanding that this solution is not thread-safe, since 1) Foo's constructor might be called more than once (which may or may not matter) and 2) inst may not be fully constructed before it is returned to a different thread.
One solution is to wrap a mutex around the whole method, but then I'm paying for synchronization overhead long after I actually need it. An alternative is something like
static Foo &getInst()
{
static Foo *inst = NULL;
if(inst == NULL)
{
pthread_mutex_lock(&mutex);
if(inst == NULL)
inst = new Foo(...);
pthread_mutex_unlock(&mutex);
}
return *inst;
}
Is this the right way to do it, or are there any pitfalls I should be aware of? For instance, are there any static initialization order problems that might occur, i.e. is inst always guaranteed to be NULL the first time getInst is called?
| Your solution is called 'double checked locking' and the way you've written it is not threadsafe.
This Meyers/Alexandrescu paper explains why - but that paper is also widely misunderstood. It started the 'double checked locking is unsafe in C++' meme - but its actual conclusion is that double checked locking in C++ can be implemented safely, it just requires the use of memory barriers in a non-obvious place.
The paper contains pseudocode demonstrating how to use memory barriers to safely implement the DLCP, so it shouldn't be difficult for you to correct your implementation.
|
2,576,117 | 2,640,405 | How to set QNetworkReply properties to get correct NCBI pages? | I try to get this following url using the downloadURL function as follows:
http://www.ncbi.nlm.nih.gov/nuccore/27884304
But the data is not as what we can see through the browser, now I know it's because some correct information (such as browser type) is needed. How can I know what kind of information I need to set, and how can I set it? (By setHeader function or some other way??)
In VC++, we can use CInternetSession and CHttpConnection Object to get the correct data without setting any other detail information, is there any similar way in Qt or other cross-platform C++ network lib?? (Yes, I need the the cross-platform property.)
QNetworkReply::NetworkError downloadURL(const QUrl &url, QByteArray &data) {
QNetworkAccessManager manager;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader ,"Mozilla/5.0 (Windows; U; Windows NT
6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)");
QNetworkReply *reply = manager.get(request);
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QVariant statusCodeV = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
QUrl redirectTo = statusCodeV.toUrl();
if (!redirectTo.isEmpty())
{
if (redirectTo.host().isEmpty())
{
const QByteArray newaddr = ("http://"+url.host()+redirectTo.encodedPath()).toAscii();
redirectTo.setEncodedUrl(newaddr);
redirectTo.setHost(url.host());
}
return (downloadURL(redirectTo, data));
}
if (reply->error() != QNetworkReply::NoError)
{
return reply->error();
}
data = reply->readAll();
delete reply;
return QNetworkReply::NoError; }
By VC, we can just do this, then the correct data is in the CHttpFile.
CString downloadURL (CString sGetFromURL)
{
// create an internet session
CInternetSession csiSession;
int pos;
BOOL neof;
// parse URL to get server/object/port
DWORD dwServiceType;
CString sServerName;
CString sObject;
INTERNET_PORT nPort;
CHttpConnection* pHTTPServer = NULL;
CHttpFile* pFile = NULL;
AfxParseURL ( sGetFromURL, dwServiceType, sServerName, sObject, nPort );
// open HTTP connection
pHTTPServer = csiSession.GetHttpConnection ( sServerName, nPort );
// get HTTP object
pFile = pHTTPServer->OpenRequest ( CHttpConnection::HTTP_VERB_GET, sObject, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD );
pFile->SendRequest();
}
| Close, but you aren't setting the correct header. You need to do:
request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)" );
|
2,576,121 | 2,576,133 | Shift from Java to c++ | I have been developing applications based on C# (.net) and Java (J2EE) for the last 3 years.
But now I feel, Java, C# makes you lame (from learning point of view) and you can develop your apps quickly but you fail to understand the basic underlying concepts of programming.
So, I am trying to learn C++, but I find it a little "confusing" due to pointer, multiple inheritance, some conventions and other concepts of C++ which don't exist in Java. So, what do you guys suggest? How should I feel about it?
Thanks
PS: I am a student, so have all the time in the world and actually shift.
| In my opinion, you should learn C first in order to properly understand the base upon which C++ is built. Pick up a copy of "The C Programming Language" by Kernighan and Ritchie, widely considered the best reference on the language, and start reading through it. Once you fully understand C, you'll have the low-level base you need.
|
2,576,122 | 2,576,155 | Advice for keeping large C++ project modular? | Our team is moving into much larger projects in size, many of which use several open source projects within them.
Any advice or best practices to keep libraries and dependancies relatively modular and easily upgradable when new releases for them are out?
To put it another way, lets say you make a program that is a fork of an open source project. As both projects grow, what is the easiest way to maintain and share updates to the core?
Advice regarding what I'm asking only please...I don't need "well you should do this instead" or "why are you"..thanks.
| With clones of open source projects one of your biggest headaches will be keeping in sync/patched according to the upstream sources. You might not care about new features, but you will sure need critical bug fixes applied.
My suggestion would be to carefully wrap such inner projects into shared libraries, so you can more or less painlessly upgrade just those parts if the ABI is not broken by the changes.
One more thing - if you find and fix bugs in an open source project - don't keep the fixes to yourself. Push the patches upstream. That will make the project better and will save you days of merging with a new version.
|
2,576,251 | 2,576,280 | Algorithm for count-down timer that can add on time | I'm making a general timer that has functionality to count up from 0 or count down from a certain number. I also want it to allow the user to add and subtract time. Everything is simple to implement except for the case in which the timer is counting down from some number, and the user adds or subtracts time from it.
For example: (m_clock is an instance of SFML's Clock)
float Timer::GetElapsedTime() {
if ( m_forward ) {
m_elapsedTime += m_clock.GetElapsedTime() - m_elapsedTime;
} else {
m_elapsedTime -=
m_elapsedTime - m_startingTime + m_clock.GetElapsedTime();
}
return m_elapsedTime;
}
To be a bit more clear, imagine that the timer starts at 100 counting down. After 10 seconds, the above function would look like 100 -= 100 - 100 + 10 which equals 90. If it was called after 20 more seconds it would look like 90 -= 90 - 100 + 30 which equals 70.
This works for normal counting, but if the user calls AddTime() ( just m_elapsedTime += arg ) then the algorithm for backwards counting fails miserably.
I know that I can do this using more members and keeping track of previous times, etc. but I'm wondering whether I'm missing some implementation that is extremely obvious. I'd prefer to keep it as simple as possible in that single operation.
| Your code is unnecessarily complex. The following is equivalent:
float Timer::GetElapsedTime() {
if ( m_forward ) {
m_elapsedTime = m_clock.GetElapsedTime();
} else {
m_elapsedTime = m_startingTime - m_clock.GetElapsedTime();
}
return m_elapsedTime;
}
and hopefully illustrates why AddTime() doesn't work: m_elapsedTime is being replaced on every call to GetElapsedTime(). The simplest solution is track added/subtracted time separately and rework GetElapsedTime() thus:
float Timer::GetElapsedTime() {
float elapsedTime = m_forward
? m_clock.GetElapsedTime()
: m_startingTime - m_clock.GetElapsedTime();
return elapsedTime + m_addedTime;
}
|
2,576,368 | 2,576,395 | Use abstract within base expecting it to be a derived class? | take this simple code:
class A{
public:
virtual void foo() = 0;
void x(){ foo(); }
};
class B: public A{ foo(){ ... } };
main(){
B b;
b.x();
}
What I want is to build an abstract class that will have a function that will call a function expecting it to be implemented in the derived class
The question is that I can't seem to make that work, the compiler says it can't compile because it can't find the reference(or something like that) to the foo() to be executed in x() of the base class. Can this work? Can anyone give me an example of this?
EDIT: It seems that it just doesn't work when the "foo();" is inside the destructor of class A(the base one)...
It just got me confused. =[
EDIT2: how interesting this got. I just created a callfoo(){ foo(); } and now it compiles ok, but if I try to call the pure abstract function directly from within the destructor of Base class A, it gives me errors... weird. Anyone has any idea of this? O_o
any help on this please?
Thanks,
Jonathan
Update
It worked outside the destructor. Now I just got confused.
Try putting the "foo()" inside the destructor of the A(base) class, at least for me is not compiling...
any help plz?
| There is nothing preventing you from doing that:
struct A {
virtual ~A() {}
virtual void f() = 0;
virtual void g() { f(); }
};
struct B : A {
void f() { std::cout << "B::f()" << std::endl; }
};
// ...
A* a = new B;
a->g(); // prints "B::f()"
As for calling a pure virtual function from the destructor (or constructor): Don't! It invokes undefined behaviour.
§10.4/6:
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.
|
2,576,620 | 2,576,627 | Const unsigned char* to char* | So, I have two types at the moment:
const unsigned char* unencrypted_data_char;
string unencrypted_data;
I'm attempting to perform a simple conversion of data from one to the other (string -> const unsigned char*)
As a result, I have the following:
strcpy((unencrypted_data_char),(unencrypted_data.c_str()));
However, I'm receiving the error:
error C2664: 'strcpy' : cannot convert parameter 1 from 'const unsigned char *' to 'char *'
Any advice? I thought using reinterpret_cast would help, but it doesn't seem to make a difference.
| You can't write to a const char *, because each char pointed to is const.
strcpy writes to the first argument. Hence the error.
Don't make unencrypted_data_char const, if you plan on writing to it (and make sure you've allocated enough space for it!)
And beware of strcpy's limitations. Make sure you know how big your buffer needs to be in advance, because strcpy doesn't stop 'til it gets enough :)
|
2,576,688 | 2,576,701 | What's the future of std::valarray look like? | Up until fairly recently I hadn't been keeping up with the C++11 deliberations. As I try to become more familiar with it and the issues being worked, I came across this site which seems to be advocating for deprecating or removing std::valarray since most people are using Blitz++ instead. I guess I'm probably one of the few people out there who still uses std::valarray (and yes I know the class has a sordid past, a tarnished present, and a questionable future). But, it does what I need, and perhaps more important, it's part of the standard (for now any way).
Aside from the one site above, I've been able to find very little on what is actually happening with std::valarray in the new standard, and was hoping that somebody on SO might be able to provide some insight and / or references where Google, Wikipedia and even the C++ Standards Committee Web Site have so far failed me. Thanks.
| std::valarray is included in C++11. It has not been deprecated or removed. It has been updated to include move operations
std::valarray is defined in §26.6[numarray] of the C++11 language standard.
|
2,576,766 | 2,576,775 | should std::auto_ptr<>::operator = reset / deallocate its existing pointee? | I read here about std::auto_ptr<>::operator=
Notice however that the left-hand side
object is not automatically
deallocated when it already points to
some object. You can explicitly do
this by calling member function reset
before assigning it a new value.
However, when I read the source code for header file C:\Program Files\Microsoft Visual Studio 8\VC\ce\include\memory
template<class _Other>
auto_ptr<_Ty>& operator=(auto_ptr<_Other>& _Right) _THROW0()
{ // assign compatible _Right (assume pointer)
reset(_Right.release());
return (*this);
}
auto_ptr<_Ty>& operator=(auto_ptr<_Ty>& _Right) _THROW0()
{ // assign compatible _Right (assume pointer)
reset(_Right.release());
return (*this);
}
auto_ptr<_Ty>& operator=(auto_ptr_ref<_Ty> _Right) _THROW0()
{ // assign compatible _Right._Ref (assume pointer)
_Ty **_Pptr = (_Ty **)_Right._Ref;
_Ty *_Ptr = *_Pptr;
*_Pptr = 0; // release old
reset(_Ptr); // set new
return (*this);
}
What is the correct/standard behavior? How do other STL implementations behave? If the website cited above has wrong/outdated information, which website do you recommend as a reference?
| If the auto_ptr being assigned to already holds a pointer, that pointer must be deleted first.
From the 2003 standard (§20.4.5.1):
auto_ptr& operator=(auto_ptr& a) throw();
7 Requires: The expression delete get() is well formed.
8 Effects: reset(a.release()).
9 Returns: *this.
So, assigning to an auto_ptr has the same effect as calling reset on it with the pointer released from the right hand side auto_ptr.
The website you cite is wrong.
|
2,576,812 | 2,587,322 | How to see the contents of std::map in Visual C++ .NET (Visual Studio 2003) while debugging? | I need to see the contents of a std::map variable while debugging. However, if i click on it in the Autos/Locals Tab, I see implementation specific stuff, instead of the keys and its contents which I want to look at. Is there a work-around i'm missing ?
| I have no VS2003 nearby at the moment. But you could try to add in "autoexp.dat" the following section (I was sure that in VS2003 there are already included sections for all standard types):
;------------------------------------------------------------------------------
; std::map
;------------------------------------------------------------------------------
std::map<*>{
children
(
#tree
(
head : $c._Myhead->_Parent,
skip : $c._Myhead,
size : $c._Mysize,
left : _Left,
right : _Right
) : $e._Myval
)
preview
(
#(
"[",
$e._Mysize,
"](",
#tree
(
head : $c._Myhead->_Parent,
skip : $c._Myhead,
size : $c._Mysize,
left : _Left,
right : _Right
) : $e._Myval,
")"
)
)
}
The structure of this file and the syntax of autoexp rules may change from one release of Visual Studio to the next. Read here more about custom visualizers for Visual Studio.
|
2,576,868 | 2,576,914 | Detect when multiple enum items map to same value | Is there a compile-time way to detect / prevent duplicate values within a C/C++ enumeration?
The catch is that there are multiple items which are initialized to explicit values.
Background:
I've inherited some C code such as the following:
#define BASE1_VAL (5)
#define BASE2_VAL (7)
typedef enum
{
MsgFoo1A = BASE1_VAL, // 5
MsgFoo1B, // 6
MsgFoo1C, // 7
MsgFoo1D, // 8
MsgFoo1E, // 9
MsgFoo2A = BASE2_VAL, // Uh oh! 7 again...
MsgFoo2B // Uh oh! 8 again...
} FOO;
The problem is that as the code grows & as developers add more messages to the MsgFoo1x group, eventually it overruns BASE2_VAL.
This code will eventually be migrated to C++, so if there is a C++-only solution (template magic?), that's OK -- but a solution that works with C and C++ is better.
| There are a couple ways to check this compile time, but they might not always work for you. Start by inserting a "marker" enum value right before MsgFoo2A.
typedef enum
{
MsgFoo1A = BASE1_VAL,
MsgFoo1B,
MsgFoo1C,
MsgFoo1D,
MsgFoo1E,
MARKER_1_DONT_USE, /* Don't use this value, but leave it here. */
MsgFoo2A = BASE2_VAL,
MsgFoo2B
} FOO;
Now we need a way to ensure that MARKER_1_DONT_USE < BASE2_VAL at compile-time. There are two common techiques.
Negative size arrays
It is an error to declare an array with negative size. This looks a little ugly, but it works.
extern int IGNORE_ENUM_CHECK[MARKER_1_DONT_USE > BASE2_VAL ? -1 : 1];
Almost every compiler ever written will generate an error if MARKER_1_DONT_USE is greater than BASE_2_VAL. GCC spits out:
test.c:16: error: size of array ‘IGNORE_ENUM_CHECK’ is negative
Static assertions
If your compiler supports C11, you can use _Static_assert. Support for C11 is not ubiquitous, but your compiler may support _Static_assert anyway, especially since the corresponding feature in C++ is widely supported.
_Static_assert(MARKER_1_DONT_USE < BASE2_VAL, "Enum values overlap.");
GCC spits out the following message:
test.c:16:1: error: static assertion failed: "Enum values overlap."
_Static_assert(MARKER_1_DONT_USE < BASE2_VAL, "Enum values overlap.");
^
|
2,576,919 | 2,584,309 | c++ sdl: can i have an sdl-opengl window inside a menu and buttons i created with glade? | I used glade to create some gtk buttons.
is it possible to add an sdl-opengl window to a glade application ? if so, how ?
how can I interact between the gtk events and the sdl events inside the gtk window ?
thanks
| There are at least two extensions to GTK that might help you: GtkGLExt and Gtksdl.
Gtksdl appears to be abandoned, but may contian some useful code. GtkGLExt is great if you're not relying on much SDL functionality beyond core OpenGL and events handling.
|
2,576,983 | 2,576,988 | An array of LPWSTR pointers, not working right | Declare:
LPWSTR** lines= new LPWSTR*[totalLines];
then i set using:
lines[totalLines]=&totalText;
SetWindowText(totalChat,(LPWSTR)lines[totalLines]);
totalLines++;
Now I know totalText is right, cause if i SetWindowText using totalText it works fine. I need the text in totalLines too.
I'm also doing:
//accolating more memory.
int orgSize=size;
LPWSTR** tempArray;
if (totalLines == size) {
size *= 2;
tempArray = new LPWSTR*[size];
memcpy(tempArray, lines,sizeof(LPWSTR)*orgSize);
delete [] lines;
lines = tempArray;
}
to allocate more memory when needed.
My problem is that the lines is not getting the right data. It works for the first time around then it get corrupted. I thought at first i was overwriting but totalLines is increase. Hopefully this is enough information.
| LPWSTR is already a pointer, so you're creating a 2D array of pointers - is that what you wanted? I think not, because this:
SetWindowText(totalChat,(LPWSTR)lines[totalLines]);
Casts LPWSTR* to LPWSTR. Isn't your compiler complaining?
|
2,577,402 | 2,577,670 | g++/clang ultra fast parse but not compile mode? | Is there some ultra fast "syntax check my code, but don't compile mode" for g++/clang? Where the only goal is to just check if the code I have is valid C++ code?
| -fsyntax-only for GCC, this should probably work for Clang as well since they emulate GCC's command line options. Whether or not it's significantly faster, you'll have to time.
|
2,577,437 | 2,577,457 | Exposing boost::scoped_ptr in boost::python | I am getting a compile error, saying that the copy constructor of the scoped_ptr is private with the following code snippet:
class a {};
struct s
{
boost::scoped_ptr<a> p;
};
BOOST_PYTHON_MODULE( module )
{
class_<s>( "s" );
}
This example works with a shared_ptr though. It would be nice, if anyone knows the answer. Thanks
| The semantics of boost::scoped_ptr prohibit taking copies, while shared_ptr is intended to be copied. The error you are getting is the compiler telling you that some of the code (macro expansion?) is trying to copy the scoped_ptr but that the library does not allow the copy to be made.
|
2,577,473 | 2,577,548 | Use Ribbon Interface in Open Source Applications | Are there any open source implementations of the Ribbon interface available? I need to use them in a GPL licensed software, so the library should be compatible with GPL. The software is in VC++ 2005.
| wxWidgets supports ribbon interfaces as well.
|
2,577,557 | 2,577,890 | Restricting `using` directives to the current file | Sorry for this silly question, but is there any way to restrict using directives to the current file so that they don't propagate to the files that #include this file?
| Perhaps wrapping the code to be included inside its own namespace could achieve the behavior
you want, since name spaces have scope affect.
// FILENAME is the file to be included
namespace FILENAME_NS {
using namespace std;
namespace INNER_NS {
[wrapped code]
}
}
using namespace FILENAME_NS::INNER_NS;
and in some other file
#include <FILENAME>
// std namespace is not visible, only INNER_NS definitions and declarations
...
|
2,577,702 | 2,577,751 | Better variant of getting the output dynamically-allocated array from the function? | Here is two variants. First:
int n = 42;
int* some_function(int* input)
{
int* result = new int[n];
// some code
return result;
}
int main()
{
int* input = new int[n];
int* output = some_function(input);
delete[] input;
delete[] output;
return 0;
}
Here the function returns the memory, allocated inside the function.
Second variant:
int n = 42;
void some_function(int* input, int* output)
{
// some code
}
int main()
{
int* input = new int[n];
int* output = new int[n];
some_function(input, output);
delete[] input;
delete[] output;
return 0;
}
Here the memory is allocated outside the function.
Now I use the first variant. But I know that many built-in c++ functions use the second variant.
The first variant is more comfortable (in my opinion). But the second one also has some advantages (you allocate and delete memory in the same block).
Maybe it's a silly question but what variant is better and why?
| I think second variant is better, because you have "balanced responsibility over pointer". That makes code more readable, because you see where you allocate and where you free your memory.
If you want to use first variant, I'd suggest you to make dual funnction some_function_free(). As for malloc/free, new/delete, new[]/delete[], etc. Even that it will do simple delete[], by using this you'll save time when you'll want to change the way you allocate memory.
|
2,577,822 | 2,577,851 | I am looking for an actual functional web browser control for .NET, maybe a C++ library | I am trying to emulate a web browser in order to execute JavaScript code and then parse the DOM. The System.Windows.Forms.WebBrowser object does not give me the functionality I need. It let's me set the headers, but you cannot set the proxy or clear cookies. Well you can, but it is not ideal and messes with IE's settings.
I've been extending the WebBrowser control pinvoking native windows functions so far, but it is really one hack on top of another. I can mess with the proxy and also clear cookies and such, but this control has its issues as I mentioned.
I found something called WebKit .NET (http://webkitdotnet.sourceforge.net/), but I don't see support for setting proxies or cookie manipulation.
Can someone recommend a c++/.NET/whatever library to do this:
Basically tell me what I need to do to get an interface to similar this in .NET:
// this should probably pause the current thread for the max timeout,
// throw an exception on failure or return null w/e, VAGUELY similar to this
string WebBrowserEmu::FetchBrowserParsedHtml(Uri url,
WebProxy p,
int timeoutSeconds,
byte[] headers,
byte[] postdata);
void WebBrowserEmu::ClearCookies();
I am not responsible for my actions.
| Have you seen Watin?
|
2,577,911 | 2,577,926 | C++ vector pointer/reference problem | Please take a look at this example:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class mySubContainer
{
public:
string val;
};
class myMainContainer
{
public:
mySubContainer sub;
};
void doSomethingWith( myMainContainer &container )
{
container.sub.val = "I was modified";
}
int main( )
{
vector<myMainContainer> vec;
/**
* Add test data
*/
myMainContainer tempInst;
tempInst.sub.val = "foo";
vec.push_back( tempInst );
tempInst.sub.val = "bar";
vec.push_back( tempInst );
// 1000 lines of random code here
int i;
int size = vec.size( );
myMainContainer current;
for( i = 0; i < size; i ++ )
{
cout << i << ": Value before='" << vec.at( i ).sub.val << "'" << endl;
current = vec.at( i );
doSomethingWith( current );
cout << i << ": Value after='" << vec.at( i ).sub.val << "'" << endl;
}
system("pause");//i suck
}
A hell lot of code for an example, I know.
Now so you don't have to spend years thinking about what this [should] do[es]: I have a class myMainContainer which has as its only member an instance of mySubContainer. mySubContainer only has a string val as member.
So I create a vector and fill it with some sample data.
Now, what I want to do is: Iterate through the vector and make a separate function able to modify the current myMainContainer in the vector. However, the vector remains unchanged as the output tells:
0: Value before='foo'
0: Value after='foo'
1: Value before='bar'
1: Value after='bar'
What am I doing wrong?
doSomethingWith has to return void, I can't let it return the modified myMainContainer and then just overwrite it in the vector, that's why I tried to pass it by reference as seen in the doSomethingWith definition above.
| You're making a copy of the vector here:
current = vec.at( i );
and modifying current, but printing the original, vec.at(i).
Instead, modify the object directly, e.g.
doSomethingWith(vec[i]); // or vec.at(i) for checked access.
|
2,577,934 | 2,577,947 | Bitwise setting in C++ | enum AccessSource
{
AccessSourceNull = 0x00000001,
AccessSourceSec = 0x00000002,
AccessSourceIpo = 0x00000004,
AccessSourceSSA = 0x00000008,
AccessSourceUpgrade = 0x00000010,
AccessSourceDelta = 0x00000020,
AccessSourcePhoneM = 0x00000040,
AccessSourceSoft = 0x00000080,
AccessSourceCR = 0x00000100,
AccessSourceA = 0x00000200,
AccessSourceE = 0x00000400,
AccessSourceAll = 0xFFFFFFFF
};
What is the value of AccessSourceAll ?? is it -1? or is it maximum value?
I have a parameter ULONG x , whose default value is AccessSourceAll(that means access to all). How do i remove the access right of AccessSourceE only?
How to add the access right of AccessSourceE again?
If i have a particular value in x, then how do i know whether AccessSourceE is set or not?
| The value of AccessSourceAll is (int)0xFFFFFFFF since enum is of type int in C.
The unset just AccessSourceE use:
x & ~AccessSourceE // to assign: x &= ~AccessSourceE;
To add, use
x | AccessSourceE // to assign: x |= AccessSourceE;
To test,
if (x & AccessSourceE) { ... }
|
2,578,079 | 2,578,088 | Index strings by other strings | I need to index specific strings with other strings and I can't really find a good way to do so. I tried to use tr1::unordered_map, but I'm having some difficulties using it.
If someone could tell me what is the best way to do that I'd be really grateful :)
I also need to index objects by a number (numbers are not in order so I can't use a vector)
| What about std::map?
std::map<std::string, std::string> foo;
Then you can add elements,
foo["bar"] = "baz";
cout << foo["bar"] << std::endl; // baz
|
2,578,365 | 2,578,388 | c++ signatures, pointers | what's the difference between these signatures?
T * f(T & identifier);
T & f(T & identifier);
T f(T & identifier);
void f(T * identifier);
void f(T & identifier);
void f(T identifier);
I met pointers in c, but the amperstand in function signature is new for me. Can Anyone explain this?
| An ampersand in a type declaration indicates a reference type.
int i = 4;
int& refi = i; // reference to i
int* ptri = &i; // pointer to i
refi = 6; // modifies original 'i', no explicit dereferencing necessary
*ptri = 6; // modifies through the pointer
References have many similarities with pointers, but they're easier to use and less error-prone if address arithmetic is not needed. Also, unlike pointers, references can't be rebound to 'point' to another object after their initialization. Just ask google for references vs. pointers in C++.
|
2,578,387 | 2,578,398 | Where to Declare Structures, etc? | Should all structs and classes be declared in the header file? If I declare a struct/class in a source file, what do I need to put in the header file so that it can be used in other files? Also, are there any resources that show some standard practices of C++ out there?
| Should all structs and classes be declared in the header file?
Yes. EDIT: But their implementations should be in cpp files. Sometimes users coming from C# or Java don't realize that the implementation in C++ can be completely separate from the class declaration.
If I declare a struct/class in a source file, what do I need to put in the header file so that it can be used in other files?
You can't. The compiler needs the full declaration of a class available in any translation unit that uses that class.
Also, are there any resources that show some standard practices of C++ out there?
You could just download source for any number of open source applications to see. Though the only completely consistent thing you're likely to see is use of header guards, and keeping all declarations in header files.
|
2,578,638 | 2,578,662 | C++ Vector at/[] operator speed | In order to give functions the option to modify the vector I can't do
curr = myvec.at( i );
doThis( curr );
doThat( curr );
doStuffWith( curr );
But I have to do:
doThis( myvec.at( i ) );
doThat( myvec.at( i ) );
doStuffWith( myvec.at( i ) );
(as the answers of my other question pointed out)
I'm going to make a hell lot of calls to myvec.at() then. How fast is it, compared to the first example using a variable to store the result?
Is there a different option for me? Can I somehow use pointers?
When it's getting serious there will be thousands of calls to myvec.at() per second. So every little performance-eater is important.
| You can use a reference:
int &curr = myvec.at(i);
// do stuff with curr
The at member function does bounds checking to make sure the argument is within the size of the vector. Profiling is only way to know exactly how much slower it is compared to operator[]. Using a reference here allows you to do the lookup once and then use the result in other places. And you can make it a reference-to-const if you want to protect yourself from accidentally changing the value.
|
2,578,866 | 2,578,899 | strftime doesnt display year correctly | i have the following code below:
const char* timeformat = "%Y-%m-%d %H:%M:%S";
const int timelength = 20;
char timecstring[timelength];
strftime(timecstring, timelength, timeformat, currentstruct);
cout << "timecstring is: " << timecstring << "\n";
currentstruct is a tm*. The cout is giving me the date in the correct format, but the year is not 2010, but 3910. I know there is something to do with the year cound starting at 1900, but im not sure how to get strftime to recognise this and not add 1900 to the value of 2010 that is there, can anyone help.
Regards
Paul
| When you put the year into your currentstruct, you're apparently putting in 2010, but you need to put in 2010-1900.
If you retrieve the time from the system and convert to a struct tm with something like localtime, you don't need to do any subtraction though, because what it puts into the struct tm is already the year - 1900. You do need to subtract 1900 when you fill in the year "manually".
|
2,578,944 | 2,578,995 | python challenge, but for C++ | Does anyone know any site or book that presents problems like python challenge, but for C++?
When I think python challenge, I do not mean only a set of problems to be solved with C++ (for that I could probably use the same problems of python challenge), but rather problems that will probably be best solved using C++ STL, special features of the language, etc.
For example, there is one python challenge that is specifically designed to teach you how to use pickle, a serializing library for python.
Until now, I only know programming contests problems, but they could also be solved with C, java or other languages.
| Google Code Jam problems frequently have analyses with snippets of C++ code, probably because C++ is by far the most popular language used for solving code-jam problems. The latter also allows you to see many C++ constructs cleverly employed, as code-jam allows you to download the solutions by all the competitors. As most code is C++, you'll get to learn a lot of nice C++ tricks for efficient code.
|
2,578,994 | 2,579,003 | Value get changed even though I'm not using reference | In code:
struct Rep
{
const char* my_data_;
Rep* my_left_;
Rep* my_right_;
Rep(const char*);
};
typedef Rep& list;
ostream& operator<<(ostream& out, const list& a_list)
{
int count = 0;
list tmp = a_list;//----->HERE I'M CREATING A LOCAL COPY
for (;tmp.my_right_;tmp = *tmp.my_right_)
{
out << "Object no: " << ++count << " has name: " << tmp.my_data_;
//tmp = *tmp.my_right_;
}
return out;//------>HERE a_list is changed
}
I've thought that if I'll create local copy to a_list object I'll be operating on completely separate object. Why isn't so?
Thanks.
| I assume list is meant to be the same as Rep.
You are only copying the the pointer to the first node in the list. You are not copying the data, nor the rest of the nodes of the list. You are doing a shallow copy of the first node of the list. If you would also copy the objects themselves it would be deep copy.
|
2,579,020 | 2,579,044 | GDB skips over my code! | So, I've defined a class like
DataLoggingSystemStateReceiver
{
DataLoggingSystemStateReceiver()
: // initializer list
{
// stuff
}
// ... other functions here
};
In main, I instantiate DataLoggingSystemStateReceiver like so:
int main()
{
// ... run stuff
Sensor sensor(port, timer);
DataLoggingSystemStateReceiver dlss();
Log::notice("started");
return 0;
}
However, when I step through this code in gdb, it runs:
Sensor sensor(port, timer);
skips
DataLoggingSystemStateReceiver dlss();
and continues with
Log::notice("started");
What gives?
EDIT: By changing
DataLoggingSystemStateReceiver dlss();
to
DataLoggingSystemStateReceiver dlss;
in main(), the line executes. Can someone explain why?
| This:
DataLoggingSystemStateReceiver dlss();
does not declare an automatic variable. It declares a function named dlss that takes no arguments and returns a DataLoggingSystemStateReceiver.
You want:
DataLoggingSystemStateReceiver dlss;
The object will be default initialized, so for your class type, the default constructor will be called.
|
2,579,230 | 2,579,250 | Signedness of enum in C/C99/C++/C++x/GNU C/GNU C99 | Is the enum type signed or unsigned? Does the signedness of enums differ between: C/C99/ANSI C/C++/C++x/GNU C/ GNU C99?
Thanks
| An enum is guaranteed to be represented by an integer, but the actual type (and its signedness) is implementation-dependent.
You can force an enumeration to be represented by a signed type by giving one of the enumerators a negative value:
enum SignedEnum { a = -1 };
In C++0x, the underlying type of an enumeration can be explicitly specified:
enum ShortEnum : short { a };
(C++0x also adds support for scoped enumerations)
For completeness, I'll add that in The C Programming Language, 2nd ed., enumerators are specified as having type int (p. 215). K&R is not the C standard, so that's not normative for ISO C compilers, but it does predate the ISO C standard, so it's at least interesting from a historical standpoint.
|
2,579,511 | 2,579,749 | Incorrect logic flow? function that gets coordinates for a sudoku game | This function of mine keeps on failing an autograder, I am trying to figure out if there is a problem with its logic flow? Any thoughts?
Basically, if the row is wrong, "invalid row" should be printed, and clearInput(); called, and return false. When y is wrong, "invalid column" printed, and clearInput(); called and return false.
When both are wrong, only "invalid row" is to be printed (and still clearInput and return false.
Obviously when row and y are correct, print no error and return true.
My function gets through most of the test cases, but fails towards the end, I'm a little lost as to why.
bool getCoords(int & x, int & y)
{
char row;
bool noError=true;
cin>>row>>y;
row=toupper(row);
if(row>='A' && row<='I' && isalpha(row) && y>=1 && y<=9)
{
x=row-'A';
y=y-1;
return true;
}
else if(!(row>='A' && row<='I'))
{
cout<<"Invalid row"<<endl;
noError=false;
clearInput();
return false;
}
else
{
if(noError)
{
cout<<"Invalid column"<<endl;
}
clearInput();
return false;
}
}
| It's hard to know without seeing the input, but here's a couple of possible issues:
(1) The way you detect that the column read failed is by examining the value of y - but are you sure that it's set to a value outside the range 1-9 by the calling code? Otherwise even if the read fails you might think it succeeds. You could fix this by adding a y=0; to the beginning of the function.
Some more explanation: when you use cin >> y to read an integer into y but there isn't an integer to read (could be because there's a non-digit in the stream, or EOF is reached, or whatever) the value of y won't be touched. So, imagine your input looks like "CB". Then after you cin >> row >> y, row contains 'C' and y still contains whatever value it had before the function was called (remember y is a reference to a variable outside this function!) This is the problem: you check to see if the read succeeded by looking at the value of y, but it's quite possible that it is between 1 and 9 even if the read failed (especially if you're calling this function in a loop and reusing the same y). So your code thinks everything went OK, even though it didn't and the stream has now got its failbit set... it's not surprising if everything goes a bit crazy after this point.
(2) The way you're reading data using extraction from cin could misbehave if a line is incomplete. That's because the reading of an integer will skip leading whitespace - including newlines. So if the (invalid) input line is just "B", for example, you'd read the "B" correctly by extracting a char, and then the integer extraction would swallow the newline and fail (assuming the next input line doesn't start with an integer). Then your ignore would completely skip the next line (unless you don't pick up on the failure because of point (1)!).
|
2,579,588 | 2,582,888 | Incorrect emacs indentation in a C++ class with DLL export specification | I often write classes with a DLL export/import specification, but this seems to confuse emacs' syntax parser. I end up with something like:
class myDllSpec Foo {
public:
Foo( void );
};
Notice that the "public:" access spec is indented incorrectly, as well as everything that follows it.
When I ask emacs to describe the syntax at the beginning of the line containing public, I get a return of:
((label 352))
If I remove the myDllSpec, the indentation is correct, and emacs tells me that the syntax there is:
((inclass 352) (access-label 352))
Which seems correct and reasonable. So I conclude that the syntax parser is not able to handle the DLL export spec, and that this is what's causing my indentation trouble.
Unfortunately, I don't know how to teach the parser about my labels. Seems that this is pretty common practice, so I'm hoping there's a way around it.
| From http://www.emacswiki.org/emacs/IndentingC#toc13 you can set up a "microsoft" style.
Drop this into your .emacs:
(c-add-style "microsoft"
'("stroustrup"
(c-offsets-alist
(innamespace . -)
(inline-open . 0)
(inher-cont . c-lineup-multi-inher)
(arglist-cont-nonempty . +)
(template-args-cont . +))))
(setq c-default-style "microsoft")
or leave the default and set it manually via M-x c-set-style to microsoft.
Your example renders this indentation:
class myDllSpec Foo {
public:
Foo( void );
};
|
2,579,642 | 2,579,660 | How to free memory from a list of classes | Say I have two classes created work and workItem.
CWorker *work = new CWorker();
CWorkItem *workItem = new CWorkItem();
The work class has a public list m_WorkList and I add the work item to it.
work->m_WorkList.push_back(workItem);
If I just delete work
if(work != NULL)
delete work;
Do I need to loop through the list in the destructor like the following? Any better way to do this? Could I use clear instead?
while(m_WorkList.size())
{
CWorkItem *workItem = m_WorkList.front();
m_WorkList.pop_front();
if(workItem)
delete workItem;
}
| Yes you need to delete each item. If you call new N times, then you need to call delete exactly N times as well. There is no shortcut for bulk deleting items.
Also when you're done with it you need to call delete on work.
You can use new[] and delete[] if you want to create an array of items on the heap and release the items on the heap respectively at once. But in your case this isn't what you're looking for.
You can look to boost::shared_ptr if you don't want to manually do these delete calls.
|
2,579,657 | 2,579,665 | Ctor not allowed return type | Having code:
struct B
{
int* a;
B(int value):a(new int(value))
{ }
B():a(nullptr){}
B(const B&);
}
B::B(const B& pattern)
{
}
I'm getting err msg:
'Error 1 error C2533: 'B::{ctor}' : constructors not allowed a return type'
Any idea why?
P.S. I'm using VS 2010RC
| You're missing a semicolon after your struct definition.
The error is correct, constructors have no return type. Because you're missing a semicolon, that entire struct definition is seen as a return type for a function, as in:
// vvv return type vvv
struct { /* stuff */ } foo(void)
{
}
Add your semicolon:
struct B
{
int* a;
B(int value):a(new int(value))
{ }
B():a(nullptr){}
B(const B&);
}; // end class definition
// ah, no return type
B::B(const B& pattern)
{
}
|
2,579,702 | 2,580,782 | graphics programming | I would like to program some graphic figures such as line, circle,etc. I have used turboc++ 3.0 for
dos graphics. I would like to do the same with the compilers dev c++ or code blocks or vc++.
I would like to implement dda and bresenhems line and circle drawing algorithm.
how should I go about implementing these programs through these compilers (not the command line tools).
I have a really vague picture of graphics programming.please help..
please note : I have a nvidia graphics card 1gb.. so I cannot use dos graphics (I think the card is the reason).
| If you're wanting to play around with graphics code to draw objects and do things with them may I suggest that you skip the whole Windows/GDI/DirectX/ thing completely and take a look at Processing?
It's basically Java, so you won't have to jump too far for the language, but more specifically it's designed for playing around and experimenting with graphics, so may suit you perfectly.
|
2,579,874 | 2,579,909 | Lifetime of a string literal returned by a function | Consider this code:
const char* someFun() {
// ... some stuff
return "Some text!!"
}
int main()
{
{ // Block: A
const char* retStr = someFun();
// use retStr
}
}
In the function someFun(), where is "Some text!!" stored (I think it may be in some static area of ROM) and what is its scope lifetime?
Will the memory pointed by retStr be occupied throughout the program or be released once the block A exits?
| The C++ Standard does not say where string literals should be stored. It does however guarantee that their lifetime is the lifetime of the program. Your code is therefore valid.
|
2,580,123 | 2,580,261 | Possible to have C++ anonymous functions with boost? | I'm trying to solve a problem that anonymous functions make much, much easier, and was wondering if this was possible in c++.
What I would like to do is (essentially)
template<typename T>
T DoSomething(T one, function<T(T)> dosomething)
{
return one + dosomething(5);
}
void GetMyVal(...)
{
DoSomething<int>(1, /*anonymous func here*/)
}
This example is very, very simplified for what I have to do. In C# I would do p => p*5. I know this is easy with C++0x, but I can't use that. I feel that I should be able to do it with either boost::lambda, or a compination of boost::bind and boost::function with placeholders, but I can't seem to get it to work. This may not be possible and thats also fine, but please answer if its not possible. Thanks.
EDIT:
Ok, it seems the simple case of an int works fine, what about a more complicated structure? So, lets try
struct NumHolder
{
int x;
}
template<typename T>
T DoSomething(T one, function<T(NumHolder)> dosomething)
{
NumHolder temp;
temp = 5
return one + dosomething(temp);
}
void GetMyVal(...)
{
DoSomething<int>(1, /*anonymous func here*/)
}
Here my C# expression would be along the lines of p => p.temp * 5. Is this possible to do in C++ with boost?
EDIT 2: OK, now I'm just curious :D How would I call a function within the lambda expression? So, if we have
int ChangeVal(int mult)
{
return mult*5;
}
struct NumHolder
{
int x;
}
template<typename T>
T DoSomething(T one, function<T(NumHolder)> dosomething)
{
NumHolder temp;
temp = 5
return one + dosomething(temp);
}
void GetMyVal(...)
{
DoSomething<int>(1, /*anonymous func here*/)
}
In C# I could call p => ChangeVal(p). What would the syntax be for this with the C++ lambda expressions?
| As Anders notes in his answer, boost::lambda can be useful, but the code can become hard to read in some cases. It thus depends on what you want to do in your anonymous function.
For simple case like the p => p * 5 you mention in your question, it seems to me that using Lambda or Bind would be reasonable, though:
DoSomething(1, _1 * 5);
Edit:
Your second example hits one area where the syntax gets quickly verbose: Member (data or function) access. Because the "dot" operator can't be overloaded in C++, you have to use a bind expression to get the "x" from the argument:
DoSomething(1, bind(&NumHolder::x, _1) * 5);
or, with Boost.Lambda, use the overloaded ->* operator:
DoSomething(1, &_1->* &NumHolder::x * 5);
Edit 2:
OK, one last time :)
In your last question, you write that in C#, you'd write p => ChangeVal(p), but the code above shows a ChangeVal taking an int, not a NumHolder, so it's not clear what you mean.
Assuming that ChangeVal takes an int and that you want the anonymous function to do the equivalent of ChangeVal(the_arg.x), you'd write this with Boost.Lambda:
DoSomething(1, bind(&ChangeVal, &_1->*&NumHolder::x));
or this with Boost.Bind (works with Lambda too):
DoSomething(1, bind(&ChangeVal, bind(&NumHolder::x, _1));
|
2,580,189 | 2,581,671 | How to initialise a STL vector/list with a class without invoking the copy constructor | I have a C++ program that uses a std::list containing instances of a class. If I call e.g. myList.push_back(MyClass(variable)); it goes through the process of creating a temporary variable, and then immediately copies it to the vector, and afterwards deletes the temporary variable. This is not nearly as efficient as I want, and sucks when you need a deep copy.
I would love to have the constructor of my class new something and not have to implement a copy constructor just to allocate my memory for the second time and waste runtime. I'd also rather not have to immediately find the class instance from the vector/list and then manually allocate the memory (or do something horrible like allocate the memory in the copy constructor itself).
Is there any way around this (I'm not using Visual Studio BTW)?
| C++0x move constructors are a partial workaround: instead of the copy constructor being invoked, the move constructor would be. The move constructor is like the copy constructor except it's allowed to invalidate the source argument.
C++0x adds another feature which would do exactly what you want: emplace_back. (N3092 §23.2.3) You pass it the arguments to the constructor, then it calls the constructor with those arguments (by ... and forwarding) so no other constructor can ever be invoked.
As for C++03, your only option is to add an uninitialized state to your class. Perform actual construction in another function called immediately after push_back. boost::optional might help you avoid initializing members of the class, but it in turn requires they be copy-constructible. Or, as Fred says, accomplish the same thing with initially-empty smart pointers.
|
2,580,680 | 2,580,700 | Does a c/c++ compiler optimize constant divisions by power-of-two value into shifts? | Question says it all. Does anyone know if the following...
size_t div(size_t value) {
const size_t x = 64;
return value / x;
}
...is optimized into?
size_t div(size_t value) {
return value >> 6;
}
Do compilers do this? (My interest lies in GCC). Are there situations where it does and others where it doesn't?
I would really like to know, because every time I write a division that could be optimized like this I spend some mental energy wondering about whether precious nothings of a second is wasted doing a division where a shift would suffice.
| Even with g++ -O0 (yes, -O0!), this happens. Your function compiles down to:
_Z3divm:
.LFB952:
pushq %rbp
.LCFI0:
movq %rsp, %rbp
.LCFI1:
movq %rdi, -24(%rbp)
movq $64, -8(%rbp)
movq -24(%rbp), %rax
shrq $6, %rax
leave
ret
Note the shrq $6, which is a right shift by 6 places.
With -O1, the unnecessary junk is removed:
_Z3divm:
.LFB1023:
movq %rdi, %rax
shrq $6, %rax
ret
Results on g++ 4.3.3, x64.
|
2,580,729 | 2,580,749 | C++ Return by reference | Say, i have a function which returns a reference and i want to make sure that the caller only gets it as a reference and should not receive it as a copy.
Is this possible in C++?
In order to be more clear. I have a class like this.
class A
{
private:
std::vector<int> m_value;
A(A& a){ m_value = a.m_value; }
public:
A() {}
std::vector<int>& get_value() { return m_value; }
};
int main()
{
A a;
std::vector<int> x = a.get_value();
x.push_back(-1);
std::vector<int>& y = a.get_value();
std::cout << y.size();
return 0;
}
Thanks,
Gokul.
| You can do what you want for your own classes by making the class non copyable.
You can make an class non copyable by putting the copy constructor and operator= as private or protected members.
class C
{
private:
C(const C& other);
const C& operator=(const C&);
};
There is a good example of making a NonCopyable class here that you can derive from for your own types.
If you are using boost you can also use boost::noncopyable.
Alt solution:
Another solution is to have a void return type and make the caller pass their variable by reference. That way no copy will be made as you're getting a reference to the caller's object.
|
2,580,916 | 2,648,170 | Intellisense fails for boost::shared_ptr with Boost 1.40.0 in Visual Studio 2008 | I'm having trouble getting intellisense to auto-complete shared pointers for boost 1.40.0. (It works fine for Boost 1.33.1.) Here's a simple sample project file where auto-complete does not work:
#include <boost/shared_ptr.hpp>
struct foo
{ bool func() { return true; }; };
void bar() {
boost::shared_ptr<foo> pfoo;
pfoo.get(); // <-- intellisense does not autocomplete after "pfoo."
pfoo->func(); // <-- intellisense does not autocomplete after "pfoo->"
}
When I right-click on shared_ptr and do "Go to Definition," it brings me to a forward-declaration of the shared_ptr class in <boost/exception/exception.hpp>. It does not bring me to the actual definition, which is in <boost/smart_ptr/shared_ptr.hpp>. However, it compiles fine, and auto-completion works fine for "boost::." Also, auto-completion works fine for boost::scoped_ptr and for boost::shared_array.
Any ideas?
| I also recently ran into this and went searching for an answer. All I found was people saying Intellisense is going to be improved in VC10 or that I should improve it now using Visual Assist. I didn't like these answer so I experimented a bit. Here's the solution that fixes most of the issues (at the very least it fixes the issues shared_ptr had that scoped_ptr doesn't).
SOLUTION:
Change the forward declaration that Intellisense jumps to in exception.hpp to include the template parameter name T.
Change
template <class>
class shared_ptr;
To
template <class T>
class shared_ptr;
It seems that Intellisense considers the definition without a template parameter name to be a separate class and this is the root of the difference between shared_ptr and scoped_ptr.
Now, I mentioned that this hasn't solved all of my problems. Sometimes templated objects declared in header files don't retain there template type in the cpp files.
Ex.
// file.h
#include <boost/shared_ptr.hpp>
struct foo
{
void funcA() {}
};
struct bar
{
void funcB();
boost::shared_ptr<foo> pfoo;
};
and then in the cpp file
// file.cpp
#include "file.h"
void bar::funcB()
{
pfoo.get(); // <-- intellisense does autocomplete after "pfoo."
pfoo->func(); // <-- intellisense does not autocomplete after "pfoo->"
}
Anyways, that's a non tested trimmed down example of an issue we still have but that's far less common so we can live with it until Intellisense improves.
|
2,581,025 | 2,581,339 | How are VST Plugins made? | I would like to make (or learn how to make) VST plugins. Is there a special SDK for this? how does one yield a .vst instead of a .exe? Also, if one is looking to make Audio Units for Logic Pro, how is that done?
Thanks
| Start with this link to the wiki, explains what they are and gives links to the sdk.
Here is some information regarding the deve
How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).
The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:
EXPORTS main=_main
Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.
This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:
Include float.h.
In the constructor of your effect class, write
_control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
That should do the trick.
Here are some more useful sites:
http://www.steinberg.net/en/company/developer.html
how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial
|
2,581,250 | 2,581,306 | Precision of cos(atan2(y,x)) versus using complex <double>, C++ | I'm writing some coordinate transformations (more specifically the Joukoswky Transform, Wikipedia Joukowsky Transform), and I'm interested in performance, but of course precision. I'm trying to do the coordinate transformations in two ways:
1) Calculating the real and complex parts in separate, using double precision, as below:
double r2 = chi.x*chi.x + chi.y*chi.y;
//double sq = pow(r2,-0.5*n) + pow(r2,0.5*n); //slow!!!
double sq = sqrt(r2); //way faster!
double co = cos(atan2(chi.y,chi.x));
double si = sin(atan2(chi.y,chi.x));
Z.x = 0.5*(co*sq + co/sq);
Z.y = 0.5*si*sq;
where chi and Z are simple structures with double x and y as members.
2) Using complex :
Z = 0.5 * (chi + (1.0 / chi));
Where Z and chi are complex . There interesting part is that indeed the case 1) is faster (about 20%), but the precision is bad, giving error in the third decimal number after the comma after the inverse transform, while the complex gives back the exact number.
So, the problem is on the cos(atan2), sin(atan2)? But if it is, how the complex handles that?
EDIT: Just figured out that this was not exactly the question that I had in mind. I have to do the general transformation, as
Z = 1/2*(chi^n + (1/chi)^n), and so far the code above was the way I've figured to do it. More precisely,
double sq = pow(sqrt(r2),n); //way faster!
double co = cos(n*atan2(chi.y,chi.x));
double si = sin(n*atan2(chi.y,chi.x));
Z.x = 0.5*(co*sq + co/sq);
Z.y = 0.5*(si*sq - sq/si);
Also correcting the bug on Z.y.
| I think that in 1) it should be
Z.y = 0.5*(si*sq - si/sq);
If you want really good performance you may want to go back to first principles and observe that
1/(a+ib) = (a-ib)/(a*a+b*b)
No sqrt(), atan2() or cos() or sin().
|
2,581,377 | 2,581,708 | Pass C++ object to Lua function | I have a C++ project, where 1 method of a 1 class changes very often. So I want to take that code from C++ to Lua. Note, I'm novice to Lua.
The whole task:
Bind some class methods to Lua state machine;
Pass reference to class object to a function, written in Lua;
Operate with passed C++ object in Lua function.
I've found how to make first step with Lunar, and can't cope with second and third.
I can't use SWIG and boost.
| //This has a large number of steps, but I'm gonna post them all. This is all using native Lua 5 and the lua CAPI.
int CreateInstanceOfT(lua_State* L) {
new (lua_newuserdata(L, sizeof(T))) T(constructor args);
return 1;
}
int CallSomeFuncOnT(lua_State* L) {
if (lua_istable(L, 1)) { // If we're passed a table, get CData
lua_getfield(L, 1, "CData");
lua_replace(L, 1);
}
if (!lua_touserdata(L, 1))
lua_error(L); // longjmp out.
T& ref = *(T*)lua_touserdata(L, 1);
ref.SomeFunc(); // If you want args, I'll assume that you can pass them yourself
return 0;
}
int main() {
lua_State* L = luaL_newstate();
lua_pushcfunction(L, CreateInstanceOfT);
lua_setglobal(L, "CreateInstanceOfT");
lua_pushcfunction(L, CallSomeFuncOnT);
lua_setglobal(L, "CallSomeFuncOnT");
luaL_dofile(L, "something.lua");
lua_close(L);
}
-- Accompanying Lua code: semicolons are optional but I do out of habit. In something.lua
function CreateCInstance()
local Instance = {
CData = CreateInstanceOfT();
SomeFunc = CallSomeFuncOnT;
}
return Instance;
end
local object = CreateCInstance();
object:SomeFunc(); // Calls somefunc.
I could post a great quantity of detail about how to make exposure easier, and how to make inheritance, and suchlike - and it'll need altering if you want to expose more than one T (I think the most common solution is a simple struct { std::auto_ptr<void>, int type } deal). But, it should be a starting point if you don't understand anything about this process.
Bascally, first, we ask Lua to allocate some space (the userdata), then put T in it. When CallSomeFuncOnT comes up, first we ask it if we have a table (many Lua classes are based around tables, as they support object orientation, metatables, and such), and get the userdata out, which we then convert into a pointer to our object, and then convert into a reference. Remember that lua_touserdata gives you a void*, so you'd better be damn sure about what's on the other end. Then we call somefunc and return.
In Main, we just register the functions as globals.
Now, in Lua, when you call CreateInstanceOfT, it effectively just calls the T constructor, transparently to the Lua user. Then we ditch it in a table, which is simpler for Lua novices, and call SomeFunc by passing it this table.
|
2,581,416 | 2,581,430 | recognise @param in Eclipse for c++? | I am using Eclipse (3.5.1), on Ubuntu 9.10 to write some C++ code.
I was searching through endless settings but didnt find what I as looking for...
How can I force eclipse to make @param,(@see, @return etc) to be bold in the comments?
All the documentation will be generated with the doxygen so I dont really need anything else.
Just a small thing to make work easier.
Thanks :)
| When I do
/**
* @param foo
...
In Eclipse (Version: 3.5.1) I get
comment http://ploader.net/files/b39ff20600cf04990b80d3ef2f6e6592.png
With the doxygen plugin enabled for the project. Note the double asterisks.
|
2,581,424 | 2,581,462 | How to check for C++ copy ellision | I ran across this article on copy ellision in C++ and I've seen comments about it in the boost library. This is appealing, as I prefer my functions to look like
verylargereturntype DoSomething(...)
rather than
void DoSomething(..., verylargereturntype& retval)
So, I have two questions about this
Google has virtually no documentation on this at all, how real is this?
How can I check that this optimization is actually occuring? I assume it involves looking at the assembly, but lets just say that isn't my strong suit. If anyone can give a very basic example as to what successful ellision looks like, that would be very useful
I won't be using copy ellision just to prettify things, but if I can be guaranteed that it works, it sounds pretty useful.
| I think this is a very commonly applied optimization because:
it's not difficult for the compiler to do
it can be a huge gain
it's an area of C++ that was a commonly critiqued before the optimization became common
If you're just curious, put a debug printf() in your copy constructor:
class foo {
public:
foo(): x(0) {};
foo(int x_) : x( x_) {};
foo( foo const& other) : x( other.x) {
printf( "copied a foo\n");
};
static foo foobar() {
foo tmp( 2);
return tmp;
}
private:
int x;
};
int main()
{
foo myFoo;
myFoo = foo::foobar();
return 0;
}
Prints out "copied a foo" when I run an unoptimmized build, but nothing when I build optimized.
|
2,581,485 | 2,583,659 | Is there an alternative to libusb-win32 for 64bit windows? | I've been developing some software which uses the libusb-win32 library to interact with some USB hardware I've been developing. Now I'm trying to run the same software on windows 64 but the drivers don't seem to work (understandably).
Are there any alternatives for 64 bit Windows I've overlooked?
| Looks like there may be some 64-bit pre-compiled version available here and here.
[Edit] Oops. Looks like this is already provided for in libusb-win32 in the latest release. 64bit and 32bit are both provided in the device driver package.
|
2,581,493 | 2,581,509 | C++ Newbie: Passing an fstream to a function to read data | I have a text file named num.txt who's only contents is the line 123. Then I have the following:
void alt_reader(ifstream &file, char* line){
file.read(line, 3);
cout << "First Time: " << line << endl;
}
int main() {
ifstream inFile;
int num;
inFile.open("num.txt");
alt_reader(inFile, (char*)&num);
cout << "Second Time: " << num << endl;
}
The output is:
First Time: 123
Second Time: 3355185
Can you help me figure out how to get an fstream that is read in a function still assign the variable in main? I'm doing this because alt_reader really has a lot more to it, but this is the part I'm stuck on. Thanks a lot for the help.
UPDATE:
Using Bill Oneal's comments, I've written
void alt_reader(ifstream &file, stringstream &str, int n){
char buffer[n+1];
file.read(buffer, n);
buffer[n] = 0;
str << buffer;
cout << "First Time: " << buffer << endl; //First Time: 123
}
int main() {
ifstream inFile;
stringstream strm;
int num;
inFile.open("num.txt");
alt_reader(inFile, strm, 3);
cout << "Second Time: " << num << endl; //Second Time: 123
}
Thanks. Any critiques with what's there now?
| The first time you printed the variable, you printed it as a char *, printing treating the file as a text file (And you're lucky you didn't crash). The second time you printed it, you reinterpreted it as an int, making the representation completely different.
Whenever you cast pointers from one type to another type you are usually invoking undefined behavior. Since char has no standard relation to int, you have it here.
EDIT: To answer your comment question:
#include <sstream>
void foo(std::stream &str) {
str << "42\n";
};
int main() {
int aNumber;
std::stringstream aStringStream;
foo(aStringStream); //Pass our stream to the function. It contains
//"42\n" when the function returns.
aStringStream >> aNumber; //aNumber == 42
aNumber += 10; //aNumber == 52;
std::cout << aNumber; //Print "52"
}
|
2,581,578 | 2,581,602 | If statement not effective | void spriteput(int x,int y, int stype)
{
char sprite1[5]="OOOO";
char sprite2[5]="OOOO";
char sprite3[5]="OOOO";
char sprite4[5]="OOOO";
if (stype == 1)
{
char sprite1[5] = " OO ";
char sprite2[5] = "OOOO";
char sprite3[5] = "OOOO";
char sprite4[5] = " OO ";
mvprintw(2,y,"%s \n",sprite1);
}
mvprintw(x+1,y,"%s \n",sprite2);
mvprintw(x+2,y,"%s \n",sprite3);
mvprintw(x+3,y,"%s \n",sprite4);
}
If I'm correct that block of code should print out on a NCURSES screen
OO
OOOO
OOOO
OO
Instead however, it prints out the default text (the first char statements). Can anyone tell me why this is? The printw statement inside the If-block prints out the proper text, so it's being assigned correctly. Thank you in advance.
| Your declarations inside the if statement are shadowing the declarations outside it; once the if-statement exits, those shadowed declarations are out of scope and gone forever.
To work around this, you could do something like
if (stype == 1)
{
sprite1[0] = ' ';
sprite1[3] = ' ';
// ...
Or you could use a function like strcpy to accomplish the same thing.
This is a situation where compiling with full warnings turned on would have shown you the error without needing to post here, by the way.
|
2,581,752 | 2,581,775 | How do I compile for windows XP under windows 7 / visual studio 2008 | I'm running Windows 7 and Visual Studio 2008 Pro and trying to get my application to work on Windows XP SP3.
It's a really minimal command line program so should have any ridiculous dependencies:
// XPBuild.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
printf("Hello world");
getchar();
return 0;
}
I read somewhere that defining several constants such as WINVER should allow me to compile for other platforms. I've tried the added the following to my /D compiler options:
;WINVER=0x0501;_WIN32_WINNT 0x0501;NTDDI_VERSION=NTDDI_WINXP
But that made no difference. When I run it on my Windows XP machine (actually running in a virtualbox) I get the following error:
This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
So what have I missed? Is there something else required to run MSVC compiled programs or a different compiler option or something else?
| What you have missed is most likely that VC++ programs require a runtime to be installed (unless you link statically, which is not the default) - the error message you show is exactly the one you get if they're not in order.
Try installing the Microsoft Visual C++ 2008 SP1 Redistributable Pack on the XP machine - you will most likely see that your program works with no changes whatsoever.
|
2,581,761 | 2,581,766 | How to read a file line by line to a string type variable? | I'm trying to read a file line by line to a string type variable using the following code:
#include <iostream>
#include <fstream>
ifstream file(file_name);
if (!file) {
cout << "unable to open file";
exit(1);
}
string line;
while (!file.eof()) {
file.getline(line,256);
cout<<line;
}
file.close();
it won't compile when I try to use String class, only when I use char file[256] instead.
how can I get line by line into a string class?
| Use std::getline:
std::string s;
while (std::getline(file, s))
{
// ...
}
|
2,581,794 | 2,581,805 | Skip lines in std::istream | I'm using std::getline() to read lines from an std::istream-derived class, how can I move forward a few lines?
Do I have to just read and discard them?
| Edit: You can also use std::istream::ignore, see https://stackoverflow.com/a/25012566/492336
Do I have to use getline the number of lines I want to skip?
No, but it's probably going to be the clearest solution to those reading your code. If the number of lines you're skipping is large, you can improve performance by reading large blocks and counting newlines in each block, stopping and repositioning the file to the last newline's location. But unless you are having performance problems, I'd just put getline in a loop for the number of lines you want to skip.
|
2,581,869 | 2,581,874 | for_each but for setting each element to a value in C++ | I have the following code to assign a value to all the elements of a vector:
x = 100;
for (int i=0;i<vect.size();i++)
{
vect[i] = x;
}
It's straightforward enough, but I'm wondering if there is a function in the STL that does the same thing; something like for_each, but for assignment.
| Use std::fill:
std::fill(vect.begin(), vect.end(), 100);
Note if you want to initialize a vector to have all the same value, you can use the appropriate constructor:
std::vector<int> v(5, 100); // 5 elements set to 100
assign can be used to "reset the vector", but if you're just making the vector, use the constructor.
|
2,581,898 | 2,581,919 | PHP to C/C++ through CGI script | I realize it's probably something strange, but here is what I have.
I have an application (handwriting recognition engine) written in C/C++. This application has Perl wrapper which was made by application's authors using SWIG. My website is written in PHP, so I'm looking for some ways to make PHP work with C/C++ application.
The only way I can think of now is to create a CGI script (perl script) which accepts POST request from my website (AJAX request), sends it to the recognition engine through it's Perl wrapper, gets the required data and returns the required data as a response to AJAX request.
Do you think it could be done this way? Are there any better solutions?
Thank you!
|
Do you think it could be done this way?
Yes, no reason it can't be done.
Are there any better solutions?
May be. If you intend to execute the perl wrapper as a system call to a separate Perl script, you don't need a separate CGI perl script. You can just do system calls from PHP in your site directly. Not a big difference but might help if PHP is more of your comfort zone for web stuff than Perl's CGI
OTOH, if the Perl script wrapper is a fairly obvious and simple set of API calls, and you feel comfortable with Perl CGI, a better soltrion is to port that command line Perl script into the Perl CGI script which uses the API internally, bypassing system calls.
For high-volume stuff, removing system calls is a Big Win performance wise, plus allows for much better and easier error handling.
|
2,581,993 | 2,582,015 | What the reasons for/against returning 0 from main in ISO C++? | I know that the C++ standard says that return 0 is inserted at the end of main() if no return statement is given; however, I often see recently-written, standard-conforming C++ code that explicitly returns 0 at the end of main(). For what reasons would somebody want to explicitly return 0 if it's automatically done by the compiler?
| Because it just looks weird to not "return" something from a function having a non-void return type (even if the standard says it's not strictly necessary).
|
2,582,001 | 2,582,016 | GDB not breaking on breakpoints set on object creation in C++ | I've got a c++ app, with the following main.cpp:
1: #include <stdio.h>
2: #include "HeatMap.h"
3: #include <iostream>
4:
5: int main (int argc, char * const argv[])
6: {
7: HeatMap heatMap();
8: printf("message");
9: return 0;
10: }
Everything compiles without errors, I'm using gdb (GNU gdb 6.3.50-20050815 (Apple version gdb-1346) (Fri Sep 18 20:40:51 UTC 2009)), and compiled the app with gcc (gcc version 4.2.1 (Apple Inc. build 5646) (dot 1)) with the commands "-c -g".
When I add breakpoints to lines 7, 8, and 9, and run gdb, I get the following...
(gdb) break main.cpp:7
Breakpoint 1 at 0x10000177f: file src/main.cpp, line 8.
(gdb) break main.cpp:8
Note: breakpoint 1 also set at pc 0x10000177f.
Breakpoint 2 at 0x10000177f: file src/main.cpp, line 8.
(gdb) break main.cpp:9
Breakpoint 3 at 0x100001790: file src/main.cpp, line 9.
(gdb) run
Starting program: /DevProjects/DataManager/build/DataManager
Reading symbols for shared libraries ++. done
Breakpoint 1, main (argc=1, argv=0x7fff5fbff960) at src/main.cpp:8
8 printf("message");
(gdb)
So, why of why, does anyone know, why my app does not break on the breakpoints for the object creation, but does break on the printf line?
Drew J. Sonne.
EDIT: Answer - GDB skips over my code!
| You need to instantiate HeatMap as:
HeatMap heatMap;
HeatMap heatMap(); declares a function that returns HeatMap.
|
2,582,032 | 2,582,087 | Find max integer size that a floating point type can handle without loss of precision | Double has range more than a 64-bit integer, but its precision is less dues to its representation (since double is 64-bit as well, it can't fit more actual values). So, when representing larger integers, you start to lose precision in the integer part.
#include <boost/cstdint.hpp>
#include <limits>
template<typename T, typename TFloat>
void
maxint_to_double()
{
T i = std::numeric_limits<T>::max();
TFloat d = i;
std::cout
<< std::fixed
<< i << std::endl
<< d << std::endl;
}
int
main()
{
maxint_to_double<int, double>();
maxint_to_double<boost::intmax_t, double>();
maxint_to_double<int, float>();
return 0;
}
This prints:
2147483647
2147483647.000000
9223372036854775807
9223372036854775800.000000
2147483647
2147483648.000000
Note how max int can fit into a double without loss of precision and boost::intmax_t (64-bit in this case) cannot. float can't even hold an int.
Now, the question: is there a way in C++ to check if the entire range of a given integer type can fit into a loating point type without loss of precision?
Preferably,
it would be a compile-time check that can be used in a static assertion,
and would not involve enumerating the constants the compiler should know or can compute.
| Just a little predicate:
#include <limits>
template <typename T, typename U>
struct can_fit
{
static const bool value = std::numeric_limits<T>::digits
<= std::numeric_limits<U>::digits;
};
#include <iostream>
int main(void)
{
std::cout << std::boolalpha;
std::cout << can_fit<short, float>::value << std::endl;
std::cout << can_fit<int, float>::value << std::endl;
std::cout << can_fit<int, double>::value << std::endl;
std::cout << can_fit<long long, double>::value << std::endl;
std::cout << can_fit<short, int>::value << std::endl;
std::cout << can_fit<int, short>::value << std::endl;
}
Tests if the binary precision available in a T exists in a U. Works on all types.
"Boostified":
// this is just stuff I use
#include <boost/type_traits/integral_constant.hpp>
template <bool B>
struct bool_type : boost::integral_constant<bool, B>
{
static const bool value = B;
};
typedef const boost::true_type& true_tag;
typedef const boost::false_type& false_tag;
// can_fit type traits
#include <limits>
namespace detail
{
template <typename T, typename U>
struct can_fit
{
static const bool value = std::numeric_limits<T>::digits
<= std::numeric_limits<U>::digits;
};
}
template <typename T, typename U>
struct can_fit : bool_type<detail::can_fit<T, U>::value>
{
typedef T type1;
typedef U type2;
static const bool value = detail::can_fit<T, U>::value;
};
// test
#include <iostream>
namespace detail
{
void foo(true_tag)
{
std::cout << "T fits in U" << std::endl;
}
void foo(false_tag)
{
std::cout << "T does not fit in U" << std::endl;
}
}
// just an example
template <typename T, typename U>
void foo(void)
{
detail::foo(can_fit<T, U>());
}
int main(void)
{
foo<int, double>();
}
|
2,582,103 | 2,582,318 | Smoothing Small Data Set With Second Order Quadratic Curve | I'm doing some specific signal analysis, and I am in need of a method that would smooth out a given bell-shaped distribution curve. A running average approach isn't producing the results I desire. I want to keep the min/max, and general shape of my fitted curve intact, but resolve the inconsistencies in sampling.
In short: if given a set of data that models a simple quadratic curve, what statistical smoothing method would you recommend?
If possible, please reference an implementation, library, or framework.
Thanks SO!
Edit: Some helpful data
(A possible signal graph)
The dark colored quadratic is my "fitted" curve of the light colored connected data points.
The sample @ -44 (approx.), is a problem in my graph (i.e. a potential sample inconsistency). I need this curve to "fit" the distribution better, and overcome the values that do not trend accordingly. Hope this helps!
| A "quadratic" curve is one thing; "bell-shaped" usually means a Gaussian normal distribution. Getting a best-estimate Gaussian couldn't be easier: you compute the sample mean and variance and your smooth approximation is
y = exp(-squared(x-mean)/variance)
If, on the other hand, you want to approximate a smooth curve with a quadradatic, I'd recommend computing a quadratic polynomial with minimum square error. I can nenver remember the formulas for this, but if you've had differential calculus, write the formula for the total square error (pointwise) and differentiate with respect to the coefficients of your quadratic. Set the first derivatives to zero and solve for the best approximation. Or you could look it up.
Finally, if you just want a smooth-looking curve to approximate a set of points, cubic splines are your best bet. The curves won't necessarily mean anything, but you'll get a nice smooth approximation.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.