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,609,229 | 2,609,283 | Basic Custom String Class for C++ | EDIT: I don't want to delete the post because I have learned a lot very quickly from it and it might do someone else good, but there is no need for anyone else to spend time answering or viewing this question. The problems were in my programming fundamentals, and that is something that just can't be fixed in a quick ... | Here's just the mistakes from the first constructor.
MyString1()
{
//no arg constructor
char *string; //defines local variable that hides the member by that name
string = new char[0]; //sort of meaningless
string[0] ='\0'; //not enough room for that (out-of-bounds)
... |
2,609,299 | 2,609,404 | Use-cases of pure virtual functions with body? | I recently came to know that in C++ pure virtual functions can optionally have a body.
What are the real-world use cases for such functions?
| The classic is a pure virtual destructor:
class abstract {
public:
virtual ~abstract() = 0;
};
abstract::~abstract() {}
You make it pure because there's nothing else to make so, and you want the class to be abstract, but you have to provide an implementation nevertheless, because the derived classes' destruct... |
2,609,539 | 2,609,574 | Any difference in compiler behavior for each of these snippets? | Please consider following code:
1.
uint16 a = 0x0001;
if(a < 0x0002)
{
// do something
}
2.
uint16 a = 0x0001;
if(a < uint16(0x0002))
{
// do something
}
3.
uint16 a = 0x0001;
if(a < static_cast<uint16>(0x0002))
{
// do something
}
4.
uint16 a = 0x0001;
uint16 b = 0x0002;
if(a < b)
{
// do someth... | The last example is the best code-wise, as you shouldn't use "magic constants" in your code.
In fact, the best way would be to make b const, (edit) and use meaningful names:
uint16 currentSpeed = 0x0001;
const uint16 cMaxSpeed = 0x0002;
if (currentSpeed < cMaxSpeed)
{
// do something
}
Other than that, ther... |
2,609,642 | 2,609,667 | C++ argv path specifier | In the interpreter for my programming languages I have to correctly handle the parts in case the import function is called. I then need to check if such a file is in the /libs folder (located at the same place as my executeable!) and if it doesn't exist I have to check in the directory of the current script.
How can I... |
There is no guaranteed way to do that. You can try looking in argv[0] but whether that has the full path or just the name of the binary depends on the platform and how your process was invoked.
You can use strrchr to find the last slash and replace the character after it with '\0'
Code example:
// Duplicate the stri... |
2,609,706 | 2,610,081 | Is there an equivalent to BCEL (Java .class manipulation) but in C or C++ | Is there a C or C++ compatible library for reading and writing Java class files?
I.e. something like Apache BCEL.
| None that I'm aware of. However, you can call Java from C++. That will let you use BCEL from C++. If you're on one of gcj's supported platforms, you could try using it to compile BCEL to native code.
|
2,609,723 | 2,609,800 | C++ and Dependency Injection in unit testing | Suppose I have a C++ class like so:
class A
{
public:
A()
{
}
void SetNewB( const B& _b ) { m_B = _b; }
private:
B m_B;
}
In order to unit test something like this, I would have to break A's dependency on B. Since class A holds onto an actual object and not a pointer,... | I think you're taking the idea of Unit Testing too far. In this case, A and B are one unit, i.e., A can't exist without B. First, test B and make sure it passes all of the B-specific unit tests, then once that passes, test A and make sure it behave how it's supposed to.
|
2,610,449 | 2,610,465 | Why does C++ allow variable length arrays that aren't dynamically allocated? | I'm relatively new to C++, and from the beginning it's been drilled into me that you can't do something like
int x;
cin >> x;
int array[x];
Instead, you must use dynamic memory. However, I recently discovered that the above will compile (though I get a -pedantic warning saying it's forbidden by ISO C++). I know that i... | Support for variable length arrays (VLAs) was added to the C language in C99.
It's likely that since support for them exists in gcc (to support C99), it was relatively straightforward to add support for them to g++.
That said, it's an implementation-specific language extension, and it's not a good idea to use impleme... |
2,610,744 | 2,610,772 | Problem Making C++ script | I am not sure if I can post this sort of question (apologies in advance) but I am trying to build something from this blog post.
# mkdir wkthumb
# cat > wkthumb.cpp
# qmake -project
# qmake && make
# ./wkthumb
I have no experience with this, but I download all the files needed in the directory wkthumb using git. I ha... | The command
cat > wkthumb.cpp
reads from stdin and writes to the file wkthumb.cpp. When you run that it's not hanging, but rather it's waiting for you to type some source code. Copy and paste the source code in that blog post, followed by CtrlD Enter to create the wkthumb.cpp file.
Or, if you've already downloaded wk... |
2,610,890 | 2,610,919 | Convert templated parameter type to string | I've got a small bit of DRY going on in code I and others have written that I'd like to reduce but I'm failing to figure out how to get it done. This is legacy COM code but it's interfering with the readability. I'd like to do the following:
bool queryInterface<class T, class V>(T &_input, V &_output, Logger &_logger... | You can use RTTI to get the variable name:
#include <typeinfo>
template <typename T>
const char* type_name(void)
{
// this, unfortunately, is implementation defined
// and is allowed to be an empty string (useless!)
return typeid(T).name();
}
_logger.error() << "Failed to Query Interface between " << typ... |
2,610,934 | 2,611,094 | Make Errors: Missing Includes in C++ Script? | I just got help in how to compile this script a few mintues ago on SO but I have managed to get errors. I am only a beginner in C++ and have no idea what the below erros means or how to fix it.
This is the script in question. I have read the comments from some users suggesting they changed the #include parts but it see... | The error message indicates that the compiler cannot find what you're trying to include, i.e. <QWebView>. The way to tell the compiler where to look is with the -I flag, to specify include directories (these are not recursive).
Currently, you set the following include dirs:
-I/usr/lib/qt4/mkspecs/linux-g++
-I.
-I/usr... |
2,611,081 | 2,611,223 | Combine two numbers into one. Example: 123 and 456 become 123456 | In C++, how do I combine (note: not add) two integers into one big integer?
For example:
int1 = 123;
int2 = 456;
Is there a function to take the two numbers and turn intCombined into 123456?
EDIT:
My bad for not explaining clearly. If int2 is 0, then the answer should be 123, not 1230. In actuality though, int1 (the... | The power of ten, that you need to multiply the first number with, is the smallest one, that is bigger than the second number:
int combine(int a, int b) {
int times = 1;
while (times <= b)
times *= 10;
return a*times + b;
}
|
2,611,246 | 2,611,256 | Is "for(;;)" faster than "while (true)"? If not, why do people use it? | for (;;) {
//Something to be done repeatedly
}
I have seen this sort of thing used a lot, but I think it is rather strange...
Wouldn't it be much clearer to say while(true), or something along those lines?
I'm guessing that (as is the reason for many-a-programmer to resort to cryptic code) this is a tiny margin fa... |
It's not faster.
If you really care, compile with assembler output for your platform and look to see.
It doesn't matter. This never matters. Write your infinite loops however you like.
|
2,611,357 | 2,611,616 | lambda traits inconsistency across C++0x compilers | I observed some inconsistency between two compilers (g++ 4.5, VS2010 RC) in the way they match lambdas with partial specializations of class templates. I was trying to implement something like boost::function_types for lambdas to extract type traits. Check this for more details.
In g++ 4.5, the type of the operator() o... | I believe that GCC is noncompliant. N3092 §5.1.2/5 says
The closure type for a
lambda-expression has a public inline
function call operator (13.5.4) whose
param- eters and return type are
described by the lambda-expression’s
parameter-declaration-clause and
trailing- return-type respectively.
This functi... |
2,611,359 | 2,611,425 | Learning to read GCC assembler output | I'm considering picking up some very rudimentary understanding of assembly. My current goal is simple: VERY BASIC understanding of GCC assembler output when compiling C/C++ with the -S switch for x86/x86-64.
Just enough to do simple things such as looking at a single function and verifying whether GCC optimizes away th... | If you're using gcc or clang, the -masm=intel argument tells the compiler to generate assembly with Intel syntax rather than AT&T syntax, and the --save-temps argument tells the compiler to save temporary files (preprocessed source, assembly output, unlinked object file) in the directory GCC is called from.
Getting a... |
2,611,556 | 2,611,605 | Containers of reference_wrappers (comparison operators required?) | If you use stl containers together with reference_wrappers of POD types, code such as the following works just fine:
int i = 0;
std::vector< boost::reference_wrapper<int> > is;
is.push_back(boost::ref(i));
std::cout << (std::find(is.begin(),is.end(),i)!=is.end()) << std::endl;
However, if you use non-POD types like (c... | Does the example above work when you declare the original comparison routines as such:
friend bool operator==(const Integer& lhs, const Integer& rhs)
{
return lhs.value == rhs.value;
}
friend bool operator!=(const Integer& lhs, const Integer& rhs)
{
return !(lhs == rhs);
}
Note that declaring a friend compari... |
2,611,690 | 2,611,814 | Returning C++ objects from Windows DLL | Due to how Microsoft implements the heap in their non-DLL versions of the runtime, returning a C++ object from a DLL can cause problems:
// dll.h
DLL_EXPORT std::string somefunc();
and:
// app.c - not part of DLL but in the main executable
void doit()
{
std::string str(somefunc());
}
The above code runs fine prov... | There is a way to deal with this, but it's somewhat non-trivial. Like most of the rest of the library, std::string doesn't allocate memory directly with new -- instead, it uses an allocator (std::allocator<char>, by default).
You can provide your own allocator that uses your own heap allocation routines that are common... |
2,611,764 | 2,611,883 | Can I use a binary literal in C or C++? | I need to work with a binary number.
I tried writing:
const char x = 00010000;
But it didn't work.
I know that I can use a hexadecimal number that has the same value as 00010000, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?
| You can use BOOST_BINARY while waiting for C++0x. :) BOOST_BINARY arguably has an advantage over template implementation insofar as it can be used in C programs as well (it is 100% preprocessor-driven.)
To do the converse (i.e. print out a number in binary form), you can use the non-portable itoa function, or implemen... |
2,611,803 | 2,611,809 | Compiler issues on VC++ 2008 Express, Seemingly correct code throws errors | I've been trying to get back into coding for a while, so I figured I'd start with some simple SDL, now, without the file i/o, this compiles fine, but when I throw in the stdio code, it starts throwing errors. This I'm not sure about, I don't see any problem with the code itself, however, like I said, I might as well be... | #include "SDL/SDL.h"
#include "stdio.h"
int main(int argc, char *argv[])
{
FILE *stderr; //Invalid names. These are already defined by stdio.h.
FILE *stdout; //You can't use them (portably anyway).
stderr = fopen("stderr", "wb"); //I'm assuming you actually want files
stdout = fopen("stdout", "wb"); /... |
2,611,871 | 2,611,884 | class header+ implementation | what am I doing wrong here? I keep on getting a compilation error when I try to run this in codelab (turings craft)
Instructions:
Write the implementation (.cpp file) of the GasTank class of the previous exercise. The full specification of the class is:
A data member named amount of type double.
A constructor that ... | You listed both the class declaration and its function implementations. What part of code is in the header file, and what part of it is in the implementation file?
Also, recall that for a class the default visibility is private. Therefore, all your functions are private -- including the constructor! -- so you can't ins... |
2,611,977 | 2,612,308 | Refactor Pro versus Visual Assist X for C++ Development | There are two major refactoring tools which can be installed for Visual Studio that provide C++ support. The full versions of both tools are $250, and they seem to offer similar functionality. They are:
Developer Express' Refactor Pro + CodeRush
Whole Tomato's Visual Assist X
Which tool is better?
EDIT: My initial ev... | I have used Visual Assist for years and I think it makes VS heaps more convenient for C++ development. The searchable file list, Go to Declaration and Rename functions in particular have been indispensable. VS2010 probably makes some of Visual Assist features obsolete but I imagine it will continue to be useful.
There ... |
2,612,063 | 2,612,067 | Operator Overloading in C | In C++, I can change the operator on a specific class by doing something like this:
MyClass::operator==/*Or some other operator such as =, >, etc.*/(Const MyClass rhs) {
/* Do Stuff*/;
}
But with there being no classes (built in by default) in C. So, how could I do operator overloading for just general functions?... | Plain old C does not have operator overloading in any form. The -> "operator" to access a member of a pointer is standard C and is not introduced by any header file.
|
2,612,116 | 2,612,136 | operator<< cannot output std::endl -- Fix? | The following code gives an error when it's supposed to output just std::endl:
#include <iostream>
#include <sstream>
struct MyStream {
std::ostream* out_;
MyStream(std::ostream* out) : out_(out) {}
std::ostream& operator<<(const std::string& s) {
(*out_) << s;
return *out_;
}
};
template<class Output... | You need to add this to your struct MyStream:
std::ostream& operator<<( std::ostream& (*f)(std::ostream&) )
{
return f(*out_);
}
std::endl is a function that appends a newline and flushes the underlying stream; this function signature accepts that function and applies it to the ostream member.
Then, as a t... |
2,612,323 | 2,612,455 | C++ design: container of instances and pointers | I'm wondering something.
I have class Polygon, which composes a vector of Line (another class here)
class Polygon
{
std::vector<Line> lines;
public:
const_iterator begin() const;
const_iterator end() const;
}
On the other hand, I have a function, that calculates a vector of pointers to lines, and based on tho... | You can transform() the container:
struct deref { // NO! I don't want to derive, LEAVE ME ALONE!
template<typename P>
const P& operator()(const P* const p) const { return *p; }
};
// ...
vector<Line*> orig; // assume full ...
vector<Line> cp(orig.size());
transform(orig.begin(), orig.end(), cp.begi... |
2,612,343 | 2,612,508 | basic boost date_time input format question | I've got a pointer to a string, (char *) as input. The date/time looks like this:
Sat, 10 Apr 2010 19:30:00
I'm only interested in the date, not the time.
I created an "input_facet" with the format I want:
boost::date_time::date_input_facet inFmt("%a %d %b %Y");
but I'm not sure what to do with it. Ultimately I'd like... | You can't always dismiss the time part of a string due to time zone differences a date can change.
to parse date/time you could use time_input_facet<>
to extract a date part from it you could use .date() method
Example:
// $ g++ *.cc -lboost_date_time && ./a.out
#include <iostream>
#include <locale>
#include <sstrea... |
2,612,447 | 2,612,524 | pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message | So I've been getting some mysterious uninitialized values message from valgrind and it's been quite the mystery as of where the bad value originated from.
Seems that valgrind shows the place where the unitialised value ends up being used, but not the origin of the uninitialised value.
==11366== Conditional jump or move... | Use the valgrind option --track-origins=yes to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind ... |
2,612,547 | 2,612,620 | Which file is the COM++ object and how do I import it to .NET? | I'm trying to write a COM++ object wrapper around a Qt widget (control) I wrote so I can use it in future .NET projects. e.g.:
public __gc class comWidget;
In the compile directory are the .exe, an exe.intermediate.manifest, and the comWidget.obj, and also some other crap files (.pdb, etc). So what/how do I import i... | Your question is worded so strangely, this can only be a guess, but I going to assume you want to write a user interface component for use in .NET projects. The host program will therefore usually be written in C# or VB.NET, and will be using either the Windows Forms or WPF as its user interface framework. You have som... |
2,612,598 | 2,612,612 | Returning a reference in C++ | Consider the following code where I am returning double& and a string&. It works fine in the case of a double but not in the case of a string. Why does the behavior differ?
In both cases the compiler does not even throw the Warning: returning address of local variable or temporary as I am returning a reference.
#includ... | You should never return a reference to a local variable no matter what the compiler does or does not do. The compiler may be fooled easily. you should not base the correctness of your code on some warning which may not have fired.
The reason it didn't fire here is probably that you're not literally returning a referenc... |
2,612,652 | 2,612,760 | Refcounted pointers on iPhone | 1) Refcounted pointers need stack variables to have constructors / destructors called at predictable places.
2) Objective-C, afaik, does not support the above.
3) The cocoa libraries are bound in Objective-C, not C++.
Thus, my question: is there a easy way to use the Cocoa libraries, yet still have most of my app in C+... | Yes, you can use Cocoa with C++. The gcc compiler will compile code that contains both C++ and Objective C constructs; the resulting language is called (somewhat predictably) Objective C++.
|
2,612,709 | 2,612,727 | Why does this Object wonk out & get deleted? | Stepping through the debugger, the BBox object is okay at the entry of the function, but as soon as it enters the function, the vfptr object points to 0xccccc. I don't get it.
What is causing this ?
Why is there a virtual table reference in there when the object is not derived from other class. (Though, it resides i... | const BoundingBox& Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
Here, you're returning a reference to a temporary BoundingBox object. That object goes out of scope as soon as the return statement ends.
Return a BoundingBox instead of a BoundingBox& instead.
Also:
BoundingSphere& l... |
2,612,766 | 2,612,785 | Making use of C++ to speed up PHP | I saw this post on Sitepoint quoting a statement by Rasmus Lerdorf which goes (according to Sitepoint) as follows:
How can you make PHP fast? Well, you can’t" was his quick answer. PHP is simply not fast enough to scale to Yahoo levels. PHP was never meant for those sorts of tasks. "Any script based language is simply... | Don't even bother. PHP is slow... You may create a mixture of C++ and PHP but you'll need to do lots of profiling to understand what is slow. And this is mostly... PHP.
See following:
C++ vs PHP Benchmarks for real web software
Is Data Base the Bottle Neck of Web Service? (not really... or why wikimedia has so many se... |
2,612,938 | 2,625,280 | Simplest way to get current time in current timezone using boost::date_time? | If I do date +%H-%M-%S on the commandline (Debian/Lenny), I get a user-friendly (not UTC, not DST-less, the time a normal person has on their wristwatch) time printed.
What's the simplest way to obtain the same thing with boost::date_time ?
If I do this:
std::ostringstream msg;
boost::local_time::local_date_time t =
... | This does what I want:
namespace pt = boost::posix_time;
std::ostringstream msg;
const pt::ptime now = pt::second_clock::local_time();
pt::time_facet*const f = new pt::time_facet("%H-%M-%S");
msg.imbue(std::locale(msg.getloc(),f));
msg << now;
|
2,612,961 | 2,612,979 | Template deduction for function based on its return type? | I'd like to be able to use template deduction to achieve the following:
GCPtr<A> ptr1 = GC::Allocate();
GCPtr<B> ptr2 = GC::Allocate();
instead of (what I currently have):
GCPtr<A> ptr1 = GC::Allocate<A>();
GCPtr<B> ptr2 = GC::Allocate<B>();
My current Allocate function looks like this:
class GC
{
public:
templat... | That cannot be done. The return type does not take part in type deduction, it is rather a result of having already matched the appropriate template signature. You can, nevertheless, hide it from most uses as:
// helper
template <typename T>
void Allocate( GCPtr<T>& p ) {
p = GC::Allocate<T>();
}
int main()
{
GCP... |
2,613,009 | 2,613,022 | All Audio frequencies | How can I get(Is it possible?) all audio frequencies are now playing in the system for writing some sound visualizer? Is there any library c++ or c#?
Thanks in advance
| Basic steps are:
apply window function to block of samples (e.g. 1024 samples, Hanning window)
perform real-to-complex FFT on windowed samples
take magnitude of each FFT output bin (sqrt(re * re + im * im))
identify peaks in resulting power spectrum estimate
the bin index of each peak corresponds to the frequency of t... |
2,613,249 | 2,613,302 | How to integrate ANTLR (2.7) in Visual Studio 2005 (C++) build? | I have a project containing files generated from a .g file (antlr 2.7.x). The guy who wrote the whole thing has left me with it. Until now, I did not need to modify the grammar and all was fine. But now, I cannot continue without modifying the grammar (i.e. the .g-file).
I have the source code of the used antlr and the... | The ANTLR wiki has a few entries about Visual Studio integration:
VisualStudio C# Projects & C/C++ .rules Files for Visual Studio
How do I make ANTLRWorks and Visual Studio work together?
|
2,613,261 | 2,613,273 | Using library files in Linux | I'm trying to use some of the functions that are in the /lib/libproc-3.2.6.so library in my Ubuntu distribution.
I have downloaded and installed the header files and they are defined in my source files.
Currently, this is all I'm trying to do, just for starters...
proc_t **read_proc = readproctab(0);
But I get the f... | You are not linking your executable against libproc (that is a linker error message).
Try adding -lproc to the linker command.
|
2,613,387 | 2,613,393 | Casting pointer to object to void * in C++ | I've been reading StackOverflow too much and started doubting all the code I've ever written, I keep thinking "Is that undefined behavour?" even in code that has been working for ages.
So my question - Is it safe and well defined behavour to cast a pointer to an object (In this case abstract interface classes) to a voi... | You are safe.
From C++(0x) draft,
§5.2.9/13 (for static_cast):
A value of type pointer to object converted to “pointer to cv void” and back, possibly with different cv-qualification, shall have its original value.
§5.2.10/7 (for reinterpret_cast):
Converting an rvalue of type “pointer to T1” to the type “pointer to ... |
2,613,507 | 2,613,571 | what does this C++ line of code mean "sol<?=f((1<<n)-1,i,0)+abs(P[i])*price;" | Could anyone help me to understand following line of code:
sol< ?=f((1<< n)-1,i,0)+abs(P[i])*price;
I am studying an algorithm written using c++ and it has following operator < ?= . My problem is with understanding < ?= operator. Also when I compile this code using g++ compiler , it gives error message for above line ... | It's a GNU extension. It's basically a "lower than" operator.
int a = 3;
a <?= 2;
cout << a << endl; // prints 2, because 2 < 3
a <?= 10;
cout << a << endl; // prints 2 as well, because 10 > 2
Read more here.
|
2,613,537 | 2,613,566 | std::map keys in C++ | I have a requirement to create two different maps in C++. The Key is of type CHAR* and the Value is a pointer to a struct. I am filling 2 maps with these pairs, in separate iterations. After creating both maps I need find all such instances in which the value of the string referenced by the CHAR* are same.
For this I ... |
My understanding is that the equals operator for CHAR* just equates the memory address of the pointers.
Your understanding is correct.
The easiest thing to do would be to use std::string as the key. That way you get comparisons for the actual string value working without much effort:
std::map<std::string, PSTRUCTTYPE... |
2,613,562 | 2,613,578 | Is this list-initialization of an array of unknown size valid in C++0x? | Is this list-initialization of an array of unknown size valid in C++0x?
int main() { int x[]{0, 1,2,3,4}; return x[0]; }
I believe it is valid, but would appreciate some confirmation.
If anyone could quote from the C++0x-FCD to support their case, it would be greatly appreciated.
Thanks!
| This goes from 8.5/16 first bullet to 8.5.4 list-initialization and from 8.5.4/3 third bullet to 8.5.1 aggregate initialization and then 8.5.1/4 says
An array of unknown size initialized with a brace-enclosed initializer-list containing n initializer-clauses, where shall be greater than zero, is defined as having eleme... |
2,613,645 | 2,614,085 | C++ addition overload ambiguity | I am coming up against a vexing conundrum in my code base. I can't quite tell why my code generates this error, but (for example) std::string does not.
class String {
public:
String(const char*str);
friend String operator+ ( const String& lval, const char *rval );
friend String operator+ ( const char *lval... | The reason for the ambiguity is that one candidate function is better than another candidate function only if none of its parameters are a worse match than the parameters of the other. Consider your two functions:
friend String operator+(const String&, const char*); // (a)
String operator+(const String&); ... |
2,613,708 | 2,614,064 | Extracting public key from private key in OpenSSL | I need to extract the RSA public key from a RSA private key using OpenSSL.
I'm currently using RSAPublicKey_dup() passing the RSA* private key to get the public key. However, while the call seems to work, I cannot load (or use) this public key using the openssl command-line tool.
If I generate the public key using the ... | I managed to make this work using PEM_write_bio_RSA_PUBKEY() to write the PEM data to a in-memory buffer, then using PEM_read_bio_RSA_PUBKEY() to get a new RSA*.
Now the generated public key can be used ;)
|
2,613,891 | 2,613,925 | Priority queue structure used? | While searching for some functions in C++ standard library documentation I read that push and pop for priority queues needs constant time.
http://www.cplusplus.com/reference/stl/priority_queue/push/
Constant (in the priority_queue). Although notice that push_heap operates in logarithmic time.
My question is what k... | I assume you are referring to cplusplus.com's page.
Earlier on the page it says:
This member function effectively calls the member function push_back of the underlying container object, and then calls the push_heap algorithm to keep the heap property of priority_queues.
So, after the O(1) push, the data structure ha... |
2,613,970 | 2,614,157 | calling std::cout.rdbuf() produces syntax error | Maybe I missed something, but I cant figure out why Visual Studio 2008 isn't seeing the rdbuf() procedure. Here is my code:
16. #include "DebugBuffer/BufferedStringBuf.h"
17.
18. BufferedStringBuf debug_buffer(256);
19. std::cout.rdbuf(&debug_buffer);
The BufferedStringBuf class is from this page: http://www.devmaster... | You're not allowed to have executable statements at file-level scope. You can declare variables, but you can't call functions as standalone statements. Move your code into a function (such as gf's answer demonstrates), and you should have no problem.
|
2,614,113 | 2,614,290 | Return a dynamic string from std::exception's `what` | I'm convinced at this point that I should be creating subclasses of std::exception for all my exception throwing needs. Now I'm looking at how to override the what method.
The situation that I'm facing, it would be really handy if the string what returns be dynamic. Some pieces of code parse an XML file for example, an... | My exception classes generally don't have anything but the constructor and look along these lines:
class MyEx: public std::runtime_error
{
public:
MyEx(const std::string& msg, int line):
std::runtime_error(msg + " on line " + boost::lexical_cast<string>(line))
{}
};
An arbitrary example, but it ... |
2,614,306 | 2,614,366 | Modifying text files and executing programs with command line parameters in c# or c++ on Linux | I have a need to create a utility in Suze Linux. The utility will make modifications to some text files, and then use the information in those text files to program a device in the computer using a different executable which accepts command line parameters.
I am fluent in c#, but have never worked with Linux. Should ... | Is there a reason you want to restrict yourself to only C++ or C#? There are many options you could consider, for example:
For very simple tasks:
Bash: In some cases a simple Bash script will be able to solve the task. Piping information from one process to another is a breeze, and you have the power of sed, awk, etc.... |
2,614,314 | 2,614,373 | When to use a namespace or a struct? | I was just reading a little bit on them from http://www.cplusplus.com/doc/tutorial/namespaces/
and it seems like a struct is capable of the same things? Or even a class for that matter. Maybe someone here can better define what a namespace is, and how it differs from a struct/class?
| Namespaces and class-types are not capable of the same things. Namespaces are mainly used to group types and functions together to avoid name collisions, while class-types hold data and operations that work on that data.
To just group functions and objects by using a class-types you'd have to make them static:
struct X... |
2,614,428 | 2,614,451 | How to effectively measure difference in a run-time | One of the exercises in TC++PL asks:
Write a function that either returns a value or that throws that value based on an argument. Measure the difference in run-time between the two ways.
Great pity he never explaines how to measure such things. I'm not sure if I'm suppose to write simple "time start, time end" coun... | For each of the functions,
Get the start time
Call the function a million times (or more... a million isn't that many, really)
Get the end time and subtract from it the start time
and compare the results. That's about as practical as performance measuring gets.
|
2,614,527 | 2,614,535 | How do I get the next token in a Cstring if I want to use it as an int? (c++) | My objective is to take directions from a user and eventually a text file to move a robot. The catch is that I must use Cstrings(such as char word[];) rather than the std::string and tokenize them for use.
the code looks like this:
void Navigator::manualDrive()
{
char uinput[1];
char delim[] = " ";
char *... |
To convert to lower, you can use tolower. It operates one character at a time, so you need a simple loop.
To parse a string into an integer, you can use strtoll.
Move to the next token just means call strtok again (in this case inside an if statement).
|
2,614,809 | 2,614,902 | What is the default value for C++ class members | What is the default values for members of a struct and members of a class in c++, and how do these rules differ (e.g. between classes/structs/primitives/etc) ? Are there circumstances where the rules about the default values differs ?
| There are no differences between structs and classes in this regard in C++. They all are called just class types.
Members of class types have no default values in general case. In order to for a class member to get a deterministic value it has to be initialized, which can be done by
Default constructor of the member i... |
2,614,836 | 2,614,916 | how to instantiate template of template | I have template that looks like this:
100 template<size_t A0, size_t A1, size_t A2, size_t A3>
101 struct mask {
103 template<size_t B0, size_t B1, size_t B2, size_t B3>
104 struct compare {
105 static const bool value = (A0 == B0 && A1 == B1 && A2 == B2 && A3 == B3);
106 };
107 };
...
120 const typ... | You probably need template before compare:
120 const typename boost::enable_if_c<
121 mask<a,b,c,d>::template compare<2,3,0,1>::value || ...>::type
|
2,614,895 | 2,615,023 | What library can I use to do simple, lightweight message passing? | I will be starting a project which requires communication between distributed nodes(the project is in C++). I need a lightweight message passing library to pass very simple messages(basically just strings of text) between nodes. The library must have the following characteristics:
No external setup required. I need to... | Take a look at ØMQ, i.e. ZeroMQ.
|
2,615,012 | 2,615,035 | retrieve multiple display information using win32/C++ | Is there any way to retrieve information about how many extra displays there are besides the main one, how they are numbered, what the dimensions are, etc? I know this is pretty easy in .net land.
| EnumDisplayMonitors should get you started.
|
2,615,032 | 2,615,166 | How can I check the network connection type using the Windows API? | How can I programmatically retrieve the current connection type (eg. LAN or Direct connection)?
InternetGetConnectedState() isn't very reliable.
For instance, I'm connected to a wireless network, but ConTypeRet is 18, which is INTERNET_CONNECTION_LAN & INTERNET_RAS_INSTALLED. Isn't there any way to make sure that ConTy... | I'm confused by your "It is unreliable" statement. You can just check for both:
bool IsLanOrModem() {
DWORD result;
if (!InternetGetConnectedState(&result, 0))
throw GetLastError();
return result & INTERNET_CONNECTION_LAN || result & INTERNET_CONNECTION_MODEM;
}
|
2,615,071 | 2,615,245 | C++ How do you set an array of pointers to null in an initialiser list like way? | I am aware you cannot use an initialiser list for an array. However I have heard of ways that you can set an array of pointers to NULL in a way that is similar to an initialiser list.
I am not certain how this is done. I have heard that a pointer is set to NULL by default, though I do not know if this is guaranteed/ i... | In order to set an array of pointers to nulls in constructor initializer list, you can use the () initializer
struct S {
int *a[100];
S() : a() {
// `a` contains null pointers
}
};
Unfortunately, in the current version of the language the () initializer is the only initializer that you can use with an arra... |
2,615,078 | 2,615,092 | How to read in a double from a file in c++ | How do you read in a double from a file in C++?
For ints I know you can use the getline() and then atoi, but I am not finding an array to double function. What is available for reading in doubles, or converting a char array to a double?
| You can use stream extraction:
std::ifstream ifs(...);
double d;
ifs >> d;
This work provided that other then whitespace, the next data in the stream should be a double in textual representation.
After the extraction, you can check the state of the stream to see if there were errors:
ifs >> d;
if (!ifs)
{
// the... |
2,615,162 | 2,615,199 | How is its lifetime of a return value extended to the scope of the calling function when it is bound to a const reference in the calling function? | "If you return a value (not a reference) from the function, then bind it to a const reference in the calling function, its lifetime would be extended to the scope of the calling function."
So: CASE A
const BoundingBox Player::GetBoundingBox(void)
{
return BoundingBox( &GetBoundingSphere() );
}
Returns a value of t... | Normally a temporary object (such as one returned by a function call) has a lifetime that extends to the end of the "enclosing expression". However, a temporary bound to a reference generally has it's lifetime 'promoted' to the lifetime of the reference (which may or may not be the lifetime of the calling function), b... |
2,615,203 | 2,615,205 | Is sizeof in C++ evaluated at compilation time or run time? | For example result of this code snippet depends on which machine: the compiler machine or the machine executable file works?
sizeof(short int)
| sizeof is a compile time operator.
|
2,615,281 | 2,615,296 | What is the ISO C++ way to directly define a conversion function to reference to array? | According to the standard, a conversion function has a function-id operator conversion-type-id, which would look like, say, operator char(&)[4] I believe. But I cannot figure out where to put the function parameter list. gcc does not accept either of operator char(&())[4] or operator char(&)[4]() or anything I can thin... | You can use identity
template<typename T>
struct identity { typedef T type; };
struct sample {
operator identity<char[4]>::type &() {
...
}
};
You are correct that function and array declarators won't work in conversion functions. This is also known and discussed in this issue report. However i think that C++... |
2,615,435 | 2,615,445 | No Matching Function Error for inserting into a list in c++ | I am getting an error when I try to insert an item into a list (in C++). The error is that there is no matching function for call to the insert(). I also tried push_front() but got the same error.
Here is the error message:
main.cpp:38: error: no matching function for call to ‘std::list<Salesperson, std::allocator<Sa... | insert needs both a position and an element - did you mean push_front or push_back?
|
2,615,905 | 2,616,076 | C++ template nontype parameter arithmetic | I am trying to specialize template the following way:
template<size_t _1,size_t _2> // workaround: bool consecutive = (_1 == _2 - 1)>
struct integral_index_ {};
...
template<size_t _1>
struct integral_index_<_1, _1 + 1> { // cannot do arithmetic?
//struct integral_index_<_1, _2, true> { workaround
};
however I get com... | I am posting my solution is suggested by GMan
130 template<size_t _1,size_t _2, bool consecutive = (_1 == _2 - 1)>
131 struct integral_index_ {
132 template<typename T, typename U>
133 __device__
134 static T eval(const T (&N)[4], const U &index) {
135 T j = index/N[_1];
136 return ((index -... |
2,616,011 | 2,616,633 | Easy way to parse a url in C++ cross platform? | I need to parse a URL to get the protocol, host, path, and query in an application I am writing in C++. The application is intended to be cross-platform. I'm surprised I can't find anything that does this in the boost or POCO libraries. Is it somewhere obvious I'm not looking? Any suggestions on appropriate open source... | There is a library that's proposed for Boost inclusion and allows you to parse HTTP URI's easily. It uses Boost.Spirit and is also released under the Boost Software License. The library is cpp-netlib which you can find the documentation for at http://cpp-netlib.github.com/ -- you can download the latest release from ht... |
2,616,082 | 2,616,147 | How to properly use references with variadic templates | I have something like the following code:
template<typename T1, typename T2, typename T3, typename T4>
void inc(T1& t1, T2& t2, T3& t3, T4& t4) { ++t1; ++t2; ++t3; ++t4; }
template<typename T1, typename T2, typename T3>
void inc(T1& t1, T2& t2, T3& t3) { ++t1; ++t2; ++t3; }
template<typename T1, typena... | I would not use rvalue references here, because that will allow you to bind to rvalues which can allow such nonsensical code as:
inc(1);
So, I would stick with regular references:
template<typename T>
void inc(T& t) { ++t; }
template<typename T,typename ... Args>
void inc(T& t, Args& ... args) { ++t; inc(args...); }
... |
2,616,107 | 2,616,180 | Returning object from function | I am really confused now on how and which method to use to return object from a function. I want some feedback on the solutions for the given requirements.
Scenario A:
The returned object is to be stored in a variable which need not be modified during its lifetime. Thus,
const Foo SomeClass::GetFoo() {
return Foo();
... | First, let's look into the things that come into play here:
(a) Extending lifetime of a temporary when it's used to initialize a reference - I learnt about it in this publication by Andrei Anexandrescu. Again, it feels weird but useful:
class Foo { ... }
Foo GetFoo() { return Foo(); } // returning temporary
void ... |
2,616,155 | 2,616,182 | C++ Class Access Specifier Verbosity | A "traditional" C++ class (just some random declarations) might resemble the following:
class Foo
{
public:
Foo();
explicit Foo(const std::string&);
~Foo();
enum FooState
{
Idle, Busy, Unknown
};
FooState GetState() const;
bool GetBar() const;
void SetBaz(int);
private:
struct FooPartialImpl;... | "When in Rome, do as the Romans do."
I, having spent a lot of time with Java, like the style of specifying access specifiers for every field and method separately. However when I am programming in C++, I always use the style shown in your first code snippet.
|
2,616,272 | 2,831,611 | What is the best way to make a schedule in MFC | I have a list of items that are each associated with a start and end time and date. What I want to do is, given a time and date range, display only the items that fall within that window, even partially.
What I'm doing is creating a CListCtrl with all the items in it and the CListCtrl is sorted by start time by defaul... | You're asking for some very specific functionality. It sounds like you are either building a scheduling app or are trying to display a log of things that have happened in the past. This is called a Gantt Chart. You can buy Gannt Chart controls for MFC on the web. Google for some.
There's more to your question than... |
2,616,643 | 2,617,049 | Is there a standard cyclic iterator in C++ | Based on the following question: Check if one string is a rotation of other string
I was thinking of making a cyclic iterator type that takes a range, and would be able to solve the above problem like so:
std::string s1 = "abc" ;
std::string s2 = "bca" ;
std::size_t n = 2; // number of cycles
cyclic_iterator it(s2.begi... | There is nothing like this in the standard. Cycles don't play well with C++ iterators because a sequence representing the entire cycle would have first == last and hence be the empty sequence.
Possibly you could introduce some state into the iterator, a Boolean flag to represent "not done yet." The flag participates in... |
2,616,709 | 2,616,760 | Launch a QWidget from a QMain window | I'm doing my first C++ - Qt4 application and I'm having some trouble "connecting" my different uis.
I have a main window with several buttons and when I click on one, I want another window to open.
The MyMainWindowClass inherits from QMainWindow and the other from QWidget.
Here is the code I have written so far :
#in... | Try this instead of your SomeBtnClicked method:
MyWidgetClass *mwc;
void MyMainWindowClass::SomeBtnClicked()
{
std::cout << "Some Btn has been clicked" << std::endl;
this->setEnabled(false);
if (!mwc)
mwc = new MyWidgetClass(this);
mwc->show();
mwc->raise();
mwc->setActiveWindow(); //... |
2,616,786 | 2,616,793 | Using stack defined in C++ stl | #include <stack>
using namespace std;
int main() {
stack<int> s;
int i;
for (i = 0; i <= 10; i++) {
s.push(i);
}
for (i = 0; i <= 10; i++) {
printf("%d", s.pop());
}
}
Whats wrong with the code above?
Error:
In function int main(): aggregate value used where an integer was exp... | stack::pop is a void function which just discards the top element on the stack, in order to get the value you want to use stack::top.
The reason this is so is for exception safety reasons (what happens if the object returned throws an exception in its copy constructor?).
|
2,616,804 | 2,616,823 | Accessing elements of an array defined in a class (C++) | Assume that int array arrayName is a member of class className, How can I access its element in my main program?? className.arrayName[0] doesn't seem to work
| If arrayName is static inside class className, then you can access it like that:
//Declaration
class className{
public:
static int arrayName[5];
};
//Access
className::arrayName[index];
If it is not static, you must create an instance of your class first.
//Declaration
class className{
public:
int arrayName[5];... |
2,616,832 | 2,616,835 | Does this mimic perfectly a function template specialization? | Since the function template in the following code is a member of a class template, it can't be specialized without specializing the enclosing class.
But if the compiler's full optimizations are on (assume Visual Studio 2010), will the if-else-statement in the following code get optimized out? And if it does, wouldn't... | Chances are it will be optimized. But if you want to be sure you can use a compile-time if by using templates, e.g. Boost’s MPL if_ implementation.
Or you can use SFINAE (Boost.enable_if).
|
2,616,906 | 2,616,912 | How do I output coloured text to a Linux terminal? | How do I print coloured characters to a Linux terminal that supports it?
How do I tell whether the terminal supports colour codes?
| You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.
Example:
cout << "\033[1;31mbold red text\033[0m\n";
Here, \033 is the ESC character, ASCII 27. It is followed by [, then zero or more numbers separated by ;, and finally the le... |
2,616,968 | 2,616,977 | How to read and write a STL C++ string? | #include<string>
...
string in;
//How do I store a string from stdin to in?
//
//gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to
//char* gets (char*)'
//
//scanf("%s",in) also gives some weird error
Similarly, how do I write out in to stdout or to a file??
| You are trying to mix C style I/O with C++ types. When using C++ you should use the std::cin and std::cout streams for console input and output.
#include <string>
#include <iostream>
...
std::string in;
std::string out("hello world");
std::cin >> in;
std::cout << out;
But when reading a string std::cin stops reading ... |
2,617,123 | 2,617,462 | Library to analyse sound | I need in analyzing system output sound runtime. OS: Linux. The first thing I need is get different frequency values. Programming language: c++.
| One semi-portable* way that comes to mind for grabbing all the sound from multiple sources is PulseAudio. (In this case, semi-portable means working with many sound cards, not working with different OSes, though there is a WinXP version of PulseAudio). One of the PulseAudio modules provides a pipe sink. Hopefully all y... |
2,617,142 | 2,617,219 | Should it be in a namespace? | Do I have to put code from .cpp in a namespace from corresponding .h or it's enough to just write using declaration?
//file .h
namespace a
{
/*interface*/
class my
{
};
}
//file .cpp
using a::my; // Can I just write in this file this declaration and
// after that start to write implementation, or
... | I consider more appropriate to surround all the code that is meant to be in the namespace within a namespace a { ... } block, as that is semantically what you are doing: you are defining elements within the a namespace. But if you are only defining members then both things will work.
When the compiler finds void my::fo... |
2,617,247 | 2,617,259 | C++ compile time polymorphism doubt? | Below program contains two show() functions in parent and child classes, but first show() function takes FLOAT argument and second show() function takes INT argument.
.If I call show(10.1234) function by passing float argument, it should call class A's show(float a) function , but it calls class B's show(int b).
#inclu... | If you have a function in a derived class that has the same name as a function in the base class, it hides all of the functions in the base class. You either need to rename your function, or use a using declaration in your derived class:
using A::show;
or, you can explicitly call the base class function:
Bobject.A::s... |
2,617,313 | 2,617,446 | How to call Java method from C++ | I am using JNI to call my C++ function from Java. One of the C++ function's arguments is jobject thiz (as far as I know, all JNI native functions have this argument). The function takes quite long to complete and I want to report progress back to the jobject thiz Java object, so that I can show the progress to the user... | You need to look at the JNI functions GetMethodID and Call<type>Method*.
The details of the various variants and how to call them are documented the JNI specification.
|
2,617,359 | 8,537,887 | cross platform keyboard/mouse input recommendation | Does anyone have any suggestions for a good cross platform input library?
I'd like to get:
* at least keyboard and mouse input
* on at least the big three operating systems
* Small/fast
* C or C++
* permissive licensing gpl2/mit/free/etc.
So far I've seen:
* OIS (used in Ogre) http://sourceforge.net/projects/wgois/
* ... | I ended up using the Qt framework for this.
It's very complete, well supported, has a lot of features, and has better licensing now. It was possible to use it with the Ogre3d library so it worked out well for me. I also found that it's being used by the City of Heroes MMO for their user interface.
|
2,617,453 | 2,617,512 | Controlling shell command line wildcard expansion in C or C++ | I'm writing a program, foo, in C++. It's typically invoked on the command line like this:
foo *.txt
My main() receives the arguments in the normal way. On many systems, argv[1] is literally *.txt, and I have to call system routines to do the wildcard expansion. On Unix systems, however, the shell expands the wildca... | You program has no influence over the shell's command line expansion. Which program will be called is determined after all the expansion is done, so it's already too late to change anything about the expansion programmatically.
The user calling your program, on the other hand, has the possibility to create whatever com... |
2,617,455 | 2,617,473 | error with io stream | What is the problem with the last two statements in the code?
#include <iostream>
using namespace std;
int main()
{
cout << "2 + 4 = " << 2 + 4 << endl;
cout << "2 * 4 = " << 2 * 4 << endl;
cout << "2 | 4 = " << 2 | 4 << endl;
cout << "2 & 4 = " << 2 & 4 << endl;
What should I do to fix this?
|
What is the problem with the last two statements in the code?
Operator precedence. | and & have lower precedence than <<, so cout << "2 & 4 = " << 2 & 4 << endl; gets parsed as (cout << "2 & 4 = " << 2) & (4 << endl;).
What should I do to fix this?
Put parens around 2 | 4 and 2 & 4.
|
2,617,468 | 2,617,558 | Are there any way to link my program with Wine-compiled part? | I am trying to use windows dll functionality in Linux.
My current solution is a compilation of a separate wine application, that uses dll and transfer requests/responses between dll and main application over IPC.
This works, but is a real overhead comparing to a simple dll calls.
I see that wine-compiled program usuall... | You may be able to use Winelib to write a Linux app that can use Windows DLLs.
EDIT:
For future reference:
libtest.c:
#include <stdio.h>
#include <windows.h>
int main(int argc, char* argv[])
{
HMODULE h;
h = LoadLibrary("cards.dll");
printf("%d\n", h);
}
Execution:
$ winegcc -m32 libtest.c
$ ./a.out
536936448
... |
2,617,515 | 2,618,789 | Recommendation for a HTTP parsing library in C/C++ | I am looking for HTTP parsing library for C/C++.
I have looked curl library, but it seems it is a http client library.
I am looking for a library which parses HTTP header (e.g. a way to
get the query string, get cookie, get request url, get Post Data)?
Thank you.
| Check out libebb, it has a parser generated with Ragel using the easy yet powerful PEG (it's based on Zed Shaw's mongrel parser)
libebb is a lightweight HTTP server library for C. It lays the
foundation for writing a web server by providing the socket juggling
and request parsing. By implementing the HTTP/1.1 g... |
2,617,570 | 2,617,729 | How to use SAPI's SetNotifyCallbackFunction() in a CLR project with Windows Form as the interface window? | I'm trying to write a dll plugin for Winamp. I'm using Microsoft Visual Studio 2008 and Microsoft SAPI 5.1. I created the interface window using Windows Form (System::Windows::Forms::Form).
I tried to use SetNotifyWIndowMessage(), but the method is never called when I speak to the microphone. So I tried using SetNotify... | Well, as indicated, you need to create a delegate instance to wrap your callback. But don't go there, SAPI 5.1 is quite outdated. Updates are no longer shipped because the .NET framework has a very nice wrapper for it. Check out the System.Speech.Recognition namespace and the SpeechRecognitionEngine class. You'll w... |
2,617,868 | 2,661,032 | Warning: System.Web.dll built without parts that depend on: System.Web.Services.dll Mono.Web.dll | I am building mono (2.6.3) on Ubuntu 9.10
I am getting the following error:
Warning: System.Web.dll built without parts that depend on: System.Web.Services.dll Mono.Web.dll
Does anyone know what is causing this, and how I may resolve this?
| System.Web.dll contains a cyclic dependency on System.Web.Services.dll.
So what happens is Mono builds a version of System.Web that does not depend on S.W.S, then uses that to build S.W.S, and finally builds the final System.Web which replaces the first one.
This probably should not use the word warning. It is just th... |
2,617,884 | 2,618,221 | Is there a c++ library that provides functionality to execute an external program and read its output? | Basically, I'm looking for something that will allow me to replicate the following Perl code:
my $fh = new FileHandle;
$fh->open("foo |");
while (<$fh>) {
# Do something with this line of data.
}
This is in the context of Linux, so a library that is specific to Windows will not help. I know how to write a program... | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
char c;
FILE* p;
p = popen("echo hello, world!", "r");
if( p == NULL ) {
fprintf(stderr, "Failed to execute shell with \"echo hello, world!\"");
exit(1);
}
while( (c = fgetc(p)) != EOF ... |
2,617,887 | 2,618,698 | Qt Graphics Scene mouse event propagation | hello i'm learning qt and i'm doing the folowing to add some widgets to a graphics scene
void MainWindow::addWidgets(QList<QWidget *> &list, int code)
{
if(code == CODE_INFO)
{
QWidget *layoutWidget = new QWidget();
QVBoxLayout *layout = new QVBoxLayout();
foreach(QWidget *w, list)
... | I believe you should be able to get mouseReleaseEvent sent to your widget by QGraphicsScene if would add mousePressEvent event handler and call accept() for the event object there. Smth. like this:
void ProductInfo::mousePressEvent(QMouseEvent* event)
{
QWidget::mousePressEvent(event);
event->accept();
}
hope... |
2,617,907 | 2,666,007 | using 9 function of 21h interrupt in c++ | function 09h interrupts 21h
dx = offset of the text , ds = segment of the text
how can i obtain segment and offset in c++?
| #include <dos.h>
FP_SEG(&var);
returns segment of var
FP_OFF(&var);
returns offset of var
|
2,618,138 | 2,618,148 | Introduction to C# for C/C++ users | I have 6+ years of C/C++ experience. Tomorrow starts a university assignment where I will have to use C#. Therefore I would like to have a list of links/resources which you think important or an extensive tutorial - in short everything you think worthy.
Coding style, best practices, ...
(I don't know any specifics abou... | Charles Petzold has: .NET book zero
|
2,618,199 | 2,618,232 | Run function on running application on execute | Alright so what I am trying to do is essentially create a program that, when it is already executed, can be "executed" again, detect the already existing process and instead of creating another process, execute a function in the existing process.
Any ideas?
It's possible I am going at this all wrong. I am trying to ada... | 1: The typical solution is to use a named mutex for this. See this question asked on MSDN for more details.
2: Use one of these functions (maybe FindWindowEx?) and (if needed) some way to get the information for locating the HWND between the two processes. Sorry I can't be more clear, there are way too many ways to d... |
2,618,285 | 2,618,860 | C++ thread to separate process | Is there any way I can have a thread branch off into its own independent process? I know there's the CreateProcess function but as far as I can tell, you can only run external applications with it. Is what I'm asking for at all possible?
| It is possible.
You could call CreateProcess with a dummy application and with the CREATE_SUSPENDED flag so it doesn't run immediately. Then you can use VirtualAllocEx to allocate memory space in the created process and WriteProcessMemory to write code and data into it. And then unsuspend the process to run it.
You can... |
2,618,414 | 2,618,444 | Convert an int to a QString with zero padding (leading zeroes) | I want to "stringify" a number and add zero-padding, like how printf("%05d") would add leading zeros if the number is less than 5 digits.
| Use this:
QString number = QStringLiteral("%1").arg(yourNumber, 5, 10, QLatin1Char('0'));
5 here corresponds to 5 in printf("%05d"). 10 is the radix, you can put 16 to print the number in hex.
|
2,618,494 | 2,618,613 | C++ compilers and back/front ends | For my own education I am curious what compilers use which C++ front-end and back-end.
Can you enlighten me where the following technologies are used and what hallmarks/advantages they have if any?
Open64 - is it back-end, front-end, or both? Which compilers use it? I encounter it in CUDA compiler.
EDG - as far as I ... | EDG is a front-end used by Intel and Comeau. See EDG's list of customers for other users.
ANTLR is a parser generator. I'm not aware of any C++ compiler built around a parser that was built with ANTLR (that doesn't mean it couldn't exist though).
GCC is a suite of compilers, with front ends for C, C++, Fortran, Ada, J... |
2,618,516 | 2,618,547 | C++ Report alternatives? | I came across this recommendation for reading the C++ report magazine. However, when I searched for it, i realized it has become defunct.
Can someone please recommend me some other magazine / rss etc which is of the same genre ? I look forward to read more about some of the elusive and other C++ techniques that veteran... | The obvious choices would be C Vu and Overload, both published by the ACCU (formerly known as the Association of C and C++ Users).
Also, even though this isn't a magazine, a great source of C++related material that is updated quite often is Herb Sutter's blog: Sutter's Mill.
|
2,618,526 | 2,618,534 | Problems Expanding an Array in C++ | I'm writing a simulation for class, and part of it involves the reproduction of organisms. My organisms are kept in an array, and I need to increase the size of the array when they reproduce. Because I have multiple classes for multiple organisms, I used a template:
template <class orgType>
void expandarray(orgType* ol... | You need to pass oldarray as a reference: orgType *& oldarray. The way it's currently written, the function will delete the caller's array but will not give it the newly allocated one, causing the crash.
Better yet, use std::vector instead of reimplementing it.
|
2,618,625 | 2,618,696 | error: expected constructor, destructor, or type conversion before '(' token | include/TestBullet.h:12: error: expected constructor, destructor, or type conver
sion before '(' token
I hate C++ error messages... lol ^^
Basically, I'm following what was written in this post to try to create a factory class for bullets so they can be instantiated from a string, which will be parsed from an xml file... | Here's how you get what you want. (Not using your code, exactly, skips including headers, etc. Just for the idea.):
// bullet_registry.hpp
class bullet;
struct bullet_registry
{
typedef bullet* (*bullet_factory)(void);
std::map<std::string, bullet_factory> mFactories;
};
bullet_registry& get_global_registry... |
2,618,694 | 2,618,703 | C++ Class Construction and Member Initialization | The first print shows the member value to be false, and the other two prints show it as true. Why does the first output differ from the last two?
#include <vector>
#include <iostream>
using namespace std;
class MyClass
{
public:
bool value;
bool stuff;
};
class Container
{
public:
vector<MyClass> my_classes;
... | The two members are primitive (non-class) objects and thus uninitialized. That means that their values will be arbitrary at runtime. You must initialize them in the constructor:
class MyClass {
public:
bool value;
bool stuff;
MyClass(): value(false), stuff(false) { }
};
|
2,618,753 | 2,618,805 | C++ domain specific embedded language operators | In numerical oriented languages (Matlab, Fortran) range operator and semantics is very handy when working with multidimensional data.
For example:
A(i:j,k,:n) // represents two-dimensional slice B(i:j,0:n) of A at index k
unfortunately C++ does not have range operator (:). of course it can be emulated using range/sli... | A solution that I've used before is to write an external preprocessor that parses the source and replaces any uses of your custom operator with vanilla C++. For your purposes, a : b uses would be replaced with something like a.operator_range_(b), and operator:() declarations with declarations of range_ operator_range_(... |
2,619,227 | 2,619,255 | Best way to get ints from a string with whitespace? | I know this is simple, I just can't recall the best way to do this.
I have an input like " 5 15 " that defines the x and y of a 2D vector array.
I simply need those two numbers into int col and int row.
What's the best way to do this? I was attemping stringstreams, but can't figure out the correct code.
Thanks for any... | You can do it using a stringstream:
std::string s = " 5 15 ";
std::stringstream ss(s);
int row, column;
ss >> row >> column;
if (!ss)
{
// Do error handling because the extraction failed
}
|
2,619,480 | 2,619,500 | Access Violation When Writing Dynamic 2D Array... Sometimes | This program is meant to generate a dynamic array, however it gives an access violation error when writing when given certain dimensions. Eg: R = 6, C = 5 crashes, but then R = 5, C = 6 doesn't. In case your wondering, it isn't my homework to "fix" this broken program, this is the method we were taught in class. Also p... | for(int i=0; i<C; ++i){
d[i] = new char[C];
}
should be
for(int i=0; i<R; ++i){
d[i] = new char[C];
}
|
2,619,551 | 2,623,662 | Output iterator's value_type | The STL commonly defines an output iterator like so:
template<class Cont>
class insert_iterator
: public iterator<output_iterator_tag,void,void,void,void> {
// ...
Why do output iterators define value_type as void? It would be useful for an algorithm to know what type of value it is supposed to output.
For example... | The real value type of the iterator could well be the iterator itself. operator* may easily just return a reference to *this because the real work is done by the assignment operator. You may well find that *it = x; and it = x; have exactly the same effect with output iterators (I suppose special measures might be taken... |
2,619,630 | 2,619,741 | C++ exceptions binary compatibility | my project uses 2 different C++ compilers, g++ and nvcc (cuda compiler).
I have noticed exception thrown from nvcc object files are not caught in g++ object files.
are C++ exceptions supposed to be binary compatible in the same machine?
what can cause such behavior?
try { kernel_= new cuda:: Kernel(); }
catch (...) { k... | nvcc is a wrapper around a normal c++ compiler, and is basically a preprocessor to convert the cuda syntax into something compilable. You can see what compiler it uses with the --verbose flag.
For instance on my machine compiling
// test.cpp
int main(){return 0;}
with nvcc -v gives
#$ _SPACE_=
#$ _MODE_=DEVICE
#$ _HE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.