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 |
|---|---|---|---|---|
7,213,469 | 7,262,117 | Best way to add seed to Perlin noise? | I'm trying to implement 2D Perlin noise generation in C++, and some implementations I found use no seed at all (here, here or here). Other implementations take a seed value to get different noise depending on the noise value.
However I found example code where one added the seed value to the function parameters calcula... | Since no one is going to write up an answer from the comments, I'm trying myself. Please upvote when I'm correct, comment when not :)
There are several implementations and example code that (try to) implement Perlin noise. First, there is the Improved Noise reference implementation from Ken Perlin himself.
Case 1: Impr... |
7,213,571 | 7,213,636 | Determine when my Application is run for the very first time | I have a Native WinApi C++ Application that finds media(.wmv, .mp3 etc.) files in a specified directory & creates random playlists. The first time the application is run(& only the first time) I want to prompt the user to specify a 'home' directory that the Application will always check for media files & create a playl... | In the installer you could create a registry value for your program.
Then when you start your program, check the registry value.
When you run the program for the first time update that value to so you know it's been run already.
|
7,213,690 | 7,213,703 | Successfull return of a reference of a local variable | template <typename dataTypeA,
typename dataTypeB>
dataTypeB const& functionX (dataTypeA argA,
dataTypeB const& argB)
{
return argA;
}
int main ()
{
cout << functionX (3, 1L);
return 0;
}
The compilation:
ani... | The compiler issues a warning, that you are returning an reference to local variable.
It works because returning a reference to local variable from a function is Undefined Behavior.
Undefined Behavior means anything can happen and the behavior cannot be explained within the semantics of the C++ Standard.
You are just... |
7,213,723 | 7,213,751 | Difference: Environment Variables & Registry Keys | What is the difference between a Registry Key & an Environment Variable?
I think Environment Variables are only something found in windows OS? And I hear thats its very easy to change these so its not good to trust them? Are Registry Keys just as easy to change?
Are Registry keys stored in the kernal?
My most important... | Another important difference:
Environment variables are loaded to the process when it starts. So if you change them after the process is running, the process won't see that.
And about your other question:
User Variables: HKEY_CURRENT_USER\Environment
System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Contro... |
7,213,839 | 7,213,859 | C++ Equivalent of C# Yield? | public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
}
public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}
Is there a way with template trick (or... | Take a look at boost::Coroutine. It does what you want.
http://www.crystalclearsoftware.com/soc/coroutine/index.html#coroutine.intro
Example from tutorial
http://www.crystalclearsoftware.com/soc/coroutine/coroutine/tutorial.html
int range_generator(generator_type::self& self, int min, int max)
{
while(min < max)
... |
7,213,941 | 7,214,351 | Choosing between virtual function, function_pointer and functors | I am writing a class in which a one of the function's implementation depends on the users. Currently I have it as a virtual function and users need to override my class to provide its implementation. I am thinking of making it a functor(boost::function)/function_pointer so that users can register to it.
Application is ... | If you are after performance, go with naked function pointers. If you need state, provide a separate state argument of type void* in your function, and let the users register their state. There's no magic that can make any C++ construct to be faster than that, since functors and virtual functions and all the rest are a... |
7,214,110 | 7,214,131 | Trust the Registry Keys or the Environment Variables | I have a program I am making in C++ WinAPI & I need to determine the version of Windows the user is running & the path to Program Files.
I know I can determine this by looking at the Windows Environment Variables or the Registry Keys(can I get the path to program files from the Registry?) BUT which is better practice?
... | You should use the GetVersionEx Function API instead. It's better than the environment variable and the registry.
For the path to program files, there is also an API: SHGetFolderPath Function
|
7,214,230 | 7,214,380 | Compiling VMime in VC++ | EDIT:
I'm trying to compile Vmime from the Vc++ project file they supported in the zip and i get this : http://pastebin.com/RXpBQ2Wa
I searched on google but no one had this kind of error : /
| It probably doesn't work with path names with spaces in them, since the copy in the error log doesn't seem to have quotes around its arguments.
|
7,214,435 | 7,214,451 | How can one implement a custom string class using the STL? | In C++ - The Complete Reference, the author gives us a challenge after showing how he implements a custom C++ string class. Excerpt from the book:
A Challenge:
Try implementing StrType (the string class) using the STL. That is, use a container to store the characters that comprise a string. Use iterators to operate ... | Yes, std::vector<char> sounds like a great idea. It will save you from the troubles of writing a custom destructor, copy constructor and copy assignment operator. Plus all the iterator member functions (begin, end and co.) can just delegate to the std::vector<char> versions.
can u give some code on how to do string ma... |
7,214,623 | 7,215,486 | Rule for lambda capture variable | For example:
class Example
{
public:
explicit Example(int n) : num(n) {}
void addAndPrint(vector<int>& v) const
{
for_each(v.begin(), v.end(), [num](int n) { cout << num + n << " "; });
}
private:
int num;
};
int main()
{
vector<int> v = { 0, 1, 2, 3, 4 };
Example ex(1);
ex.add... | 5.1.2/9:
The reaching scope of a local lambda expression is the set of
enclosing scopes up to and including the innermost enclosing function
and its parameters.
and 5.1.2/10:
The identifiers in a capture-list are looked up using the usual rules
for unqualified name lookup (3.4.1); each such lookup shall find a... |
7,214,764 | 7,214,874 | Static Vs Dynamic libraries | I have read about static and dynamic libraries.
My question is little specific.
dlopen dlclose :
Benifit of dlopen is we can start the EXE with out
loading the necessary libraries at the begining. Only when we
need we will load the libratries and unload it from the memory.
This is behaviour of dynamic linking libarie... | Unfortunately, the words "static" and "dynamic" are way too overused, especially in C and C++. So, I prefer the following terminology:
Link-time linking, a.k.a "static linking": All symbols are resolved at link time from static libraries. The result is a monolithic, statically linked executable with no load-time depen... |
7,214,826 | 7,214,974 | read in values and store in list in c++ | i have a text file with data like the following:
name
weight
groupcode
name
weight
groupcode
name
weight
groupcode
now i want write the data of all persons into a output file till the maximum weight of 10000 kg is reached.
currently i have this:
void loadData(){
ifstream readFile( "inFile.txt" );
... | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
struct entry
{
entry()
: weight()
{ }
std::string name;
int weight; // kg
std::string group_code;
};
// content of data.txt
// (without leading space)
//
// John
// 80
// Wrestler
//
// Joe
// 75... |
7,215,439 | 7,225,722 | Clearing the screen after switching away from fullscreen mode? | So I've got an OpenGL application running that can toggle between fullscreen mode and windowed mode. It currently does this by resizing the window and changing styles.
However, it seems to not invalidate the screen when switching from fullscreen mode to windowed mode, which leaves things I've drawn lingering onscreen a... | As datenwolf mentions in another answer's comment, you want to use SetWindowPos() instead of MoveWindow() when making use of SetWindowLongPtr().
My dirty background problems were solved by calling ChangeDisplaySettings(NULL, 0) AFTER resizing my window. Doing it before does little, but afterwards appears to work fine.
|
7,215,549 | 7,215,596 | Returning objects from C++ to Java | I want to return an object from c++ to java code using JNI.
I don't need to use its methods, but just read its fields.
How can I do it?
This class is just something like this:
class MyOutputClass
{
public:
Array<SomeOtherClass> m_objects1;
Array<YetAnoterClass> m_objects2;
}
Array is a class of mine, but i'll use ... | If you want to pass a C++ object to Java you can't.
But you can create a Java object in native and then return this from your native method.
That would be done like this:
JNIEXPORT myJavaObj JNICALL Java_cls_getObj
(JNIEnv *env, jobject obj)
{
jclass myClass;
//Find your class
myClass = (*env)->FindClass(env, "()LMyJa... |
7,215,591 | 7,215,631 | Is it better allow a function to throw or throw in the constructor? | I think, it is easier explain using an example. Let's take a class that model the speed of a Formula 1 car, the interface may look something like:
class SpeedF1
{
public:
explicit SpeedF1(double speed);
double getSpeed() const;
void setSpeed(double newSpeed);
//other stuff as unit
private:
double speed_;
};
... | First off, don’t overestimate the cost of the extra constructor. In fact, this cost should be exactly the cost of initialising a double plus the cost for the validity check. In other words, it is likely equal to using a raw double.
Secondly, lose the setter. Setters – and, to a lesser degree, getters – are almost alway... |
7,215,741 | 7,215,781 | How to run C++ applications on a webpage? | Are there any tools to run C++ applications written in QT on standard web browsers?
My C++ app has to run from a webpage, do some math, and return the result back to the webpage.
| Maybe you could embed the code in an ActiveX control.
|
7,215,804 | 7,215,862 | Sorting Coordinate Points c++ | in an application I measure a lot of 2d coordinates (x,y) of a
pattern. This pattern consists of a set of points on grid with fixed
pitches in x and y direction. These coordinates all have a score for
quality and are sorted on this score. What I want to do is to sort
these coordinates first on x and define groups (regi... | If you know the range of you numbers you could multiply the X by some large number and then add y to that number. Now you can simply just sort that single number or you can use stl library to do it as others have described.
|
7,215,872 | 7,219,233 | VS2010 custom build tool for generating .h file | I'm trying to integrate a custom build tool in VS2010 that generates a .h-file from a source file. I've created a .xml, .targets and .props for the step. The XML is mostly copy-pasted from the MASM-file and ends with:
<ItemType Name="FOO" DisplayName="Foo compiler" />
<FileExtension Name="*.foo" ContentType="FOO" />
<C... | The FooCompile target is using "target batching" which causes the target to iterate once for each item in the array specified for the Outputs attribute, %(Foo). The ClCompile target on the other hand operates using the entire item array @(ClCompile).
You can alter the verbosity of the logger to avoid the messages, spe... |
7,216,011 | 7,216,035 | template <typename T> perculating all through the code | I templatized a class earlier and as a result of this templatization, all classes that received objects of this newly templated type require templating as well, even where the templatization is completely irrelevant.
So:
class Shape is the base class for class Sphere, Cube, Model
Each Shape contains a Mesh
Mesh has n... | I would suggest you create a non-templated base class for Mesh (or VertexBuffer, whichever makes the most sense) that exposes the functionality that doesn't depend on the template, and use that in other places. For example:
class MeshBase
{
// Functionality that doesn't depend on the template type.
};
template<typ... |
7,216,072 | 7,827,908 | Adding Base Address + Offsets to Modify Value | I'm trying to modify a value for Solitaire such as the score.
Anyways I found the addresses (using CheatEngine) that the pointers point to but I'm having difficult injecting code to modify the score. I'm almost certain it's the way I'm adding the offsets to the base value and not Windows DEP, my injecting method, or a... | What I was doing wrong:
I needed to use the ReadProcessMemory() API to find the address that a pointer points to. And then add the offsets.
|
7,216,443 | 7,216,468 | Dynamically creating std::vector // creating a pointer to a vector | I am new so I more than likely missing something key.
I am using std::vector to store data from a ReadFile operation.
Currently I have a structure called READBUFF that contains a vector of byte. READBUFF is then instantiated via a private type in a class called Reader.
class Reader{
public:
void Read();
typedef struct... | You shouldn't be using new in this case. It causes you to have to manage the memory manually, which is never something you should want to do for many reasons1. You said you want to manage the lifetime of the vector by using new; in reality, the lifetime of the vector is already managed because it's the same as the obje... |
7,216,635 | 7,216,708 | Reading from text file into an array | I'm trying to read a textfile that I've edited with Vim into an array.
The textfile is 30*50 and is composed of single digit numbers. I've been going crazy trying to get it to work, but I think I'm having issues due to newline characters. Here's what I've been using:
Map::Map(char* filename)
{
grid[30][50] = (0);
stri... | If I understand Your problem: Your parsing sets the value from the entire line where only a digit should be...
int tnum = atoi(line.c_str());
grid[i][k] = tnum;
Translating the digit (ASCII to an int/byte/... can be done in this way:
grid[i][k] = line[k] - '0';
(Perhaps some casting is needed.)
|
7,216,676 | 7,216,719 | Static constructors in C++ on my own OS kernel | I am trying to write a kernel in c++ and I am a beginner in OS development. Now I am implementing cout to display on a monitor, but I am facing some problems. I know the question I am asking is foolish, but I am a newbie in c++ as well.
I have written an OStream class which calls the system function write to display on... | First, your implementation of cout is non-conforming. If you're going to be writing a C++ standard library, you must write it to be conforming to said standard (not to what you think the standard is).
Second, you need to implement static constructor support. You haven't specified your compiler, so all I can say is figu... |
7,216,799 | 7,216,817 | C++ How to convert last 4 characters of array to an integer? | I know how to convert a character array containing numbers to an integer using iostream:
char[] ar = "1234";
int num;
ar >> num;
but how would I convert the last four characters of that array to an int?
char[] ar = "sl34nfoe11intk1234";
int num;
????;
Is there a way to point to an element in the array and start stre... | char* p = ar + strlen(ar) - 4;
Now p points to the '1' of "1234", and you can feed p into the stream.
|
7,217,287 | 7,217,357 | 2 way communication with main exec module and dynamic lib | When I want to call a function from a dynamic linked library, I'm using dlopen then dlsym from <dlfcn.h>.
But what is the right way to call functions from the main executable module from within dll functions? Is the only correct way to pass function-pointers into dll module and calling them (for progress reporting purp... | Libraries that you link at run-time should really not be too central to your program flow; rather, they should be at the "leaf ends", if you will. Especially general purpose libraries usually exhibit only functions that accomplish one particular task (e.g. encrypt something).
Think about it, all you can import from a l... |
7,217,316 | 7,217,406 | Boost timer - how to set level of detail, I want microseconds? | So I try to create simple speed bench with boost 1.47.0. But results like 1.423 are not detailed enough for me. I need more detailed ones. How to get tham? How to make boost::timer show microseconds?
bench code:
#include <iostream>
#include <boost/thread.hpp>
#include <map>
#include <boost/thread.hpp>
#include <boost/t... | See if this thread from the Boost mailing page helps.
And you could look at this Stackoverflow question
|
7,217,611 | 7,217,650 | Should my std::vector contain pointers or structs? | I know that holding pointers incurs the overhead of an extra dereference operation but it saves me including the (potentially large) header file that contains the definition of my struct.
However my preference is to be determined by the advantage of having a std::vector<myStruct> *ptr2Vect member. Namely, not having to... | As a general rule of thumb I'd say you probably don't want to put pointers in your containers, unless there's a good reason.
Possible reasons to consider pointers:
You have virtual functions
You have a class hierarchy
You don't know the size of the objects where you're using them this. (You can only use pointers or re... |
7,217,629 | 7,217,692 | c++ win32 background | How can I force WM_PAINT without clearing the screen?
I want to load a background and I also want to load different images depending on where is the mouse. My problem is, the background is loaded well but when the mouse reach a position and want to load the new image onto the background It doesn't happen because I can'... | You can trigger a repaint of your window with InvalidateRect http://msdn.microsoft.com/en-us/library/dd145002(VS.85).aspx
|
7,217,962 | 7,217,991 | Simulate non-existing 3D Driver | I'm currently developing a 3D-based Application (In C++, if that matters). To test special circumstances, I also need to test the behaviour when no 3D Interface could be loaded (e.g, glutInit() failed).
The environment is currently Linux, so a Linux-based solution would be preferable.
How would I test a case where no 3... | Try running the application under something like a VNC server, or Xnest. Those don't generally support OpenGL.
|
7,217,987 | 7,218,724 | Make a line of source code bold in MediaWiki | I'm using a default install of MediaWiki and am trying to emphasize a certain line of code to students in a lab text I am writing.
Specifically, I am trying to bold the template line in:
template <typename T>
class Node {
This doesn't work:
<code>
<b>template <typename T></b><br>
class Node {
</code>
Is there a way t... | The precise thing you've written seems to work on mediawiki.org, I just tried it in the sandbox:
http://www.mediawiki.org/w/index.php?title=Sandbox&oldid=429106
It's a very subtle bolding effect. But it's definitely different than when you don't have the <b> tags. You might need to throw in some CSS for bolded things... |
7,218,026 | 7,218,039 | Calling push_back on a std::vector of objects (not pointers) has serious side effects. So would pointers be better? | This follows on from my previous question, where I was slow to supply all the information so I am creating a new question in the hope of more input. Given:
struct otherClass {
ImportantObj *ptrToImpObj;
otherClass() {ptrToImpObj = NULL;}
};
struct anEntry {
Thing *thing;
s... | It depends on how expensive and big your objects are. Having a vector of objects is ok if they're small, but if they're big or expensive1, all the copying/constructing/destructing can add up to a large performance hit, in which case you should use pointers (and then you have to manage the memory for all the objects, et... |
7,218,062 | 7,218,111 | How to change boost threads limitation? | So I try to create simple speed bench with boost 1.47.0. But if I try to create more than 1450 threads it throws exeption. How to get rid of such boost::tread limitation?
My code sample:
#include <iostream>
#include <boost/thread.hpp>
#include <map>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
#include... | I am not so sure it is a limitation of Boost, but a limitation of Windows. According to Mark Russinovich the maximum threads on a 32 bit OS is 2048 which means you have allocated approximatly 3/4's of the maximum allowed threads. If you have other processes running it will decrease the amount of threads available for y... |
7,218,188 | 7,218,219 | DLL / SO library, how does library memory relate to the calling process's? | I was reading that all a process's memory is released by the OS when the process terminates (by any means) so negating the need to call every dtor in turn.
Now my question is how does the memory of a DLL or SO relate to clean up of alloc'd memory?
I ask because I will probably end up using a Java and/or C# to call into... | The library becomes part of the process when it is loaded. Regarding tidy up of memory, handles, resources etc., the system doesn't distinguish whether they were created in the executable image or the library.
|
7,218,202 | 8,083,442 | Initializing union of structs nicely | I'm coding a Vec3 class, and for optimization purpose, I make it with no constructor.
I also would like to be able to access its members as x, y, z OR as r, g, b OR as a tab.
Easy, you might think : use a union
template <typename T> struct Vec3_t
{
union
{
T val[3];
struct { T x,... | It cannot be done without a constructor, and it is a bad idea to avoid using a ctor at all costs.
|
7,218,296 | 7,218,311 | What is crossplatform code snippet for getting totall cores amount in C++? |
Possible Duplicate:
Programatically detect number of physical processors/cores or if hyper-threading is active on Windows, Mac and Linux
I wonder if there is any crossplatform (std or boost based or even c) way to get totall number of cores in a crossplatform manner? (for linux Mac Os X and Windows)
| Oooh, you'll probably have to get down to assembly...
http://code.google.com/p/geekinfo/source/browse/trunk/
Or go boost:
boost::thread::hardware_concurrency(); // returns number of cores/HT/procs
|
7,218,502 | 7,218,530 | simulate ulltoa() with a radix/base of 36 | I need to convert an unsigned 64-bit integer into a string. That is in Base 36, or characters 0-Z. ulltoa does not exist in the Linux manpages. But sprintf DOES. How do I use sprintf to achieve the desired result? i.e. what formatting % stuff?
Or if snprintf does not work, then how do I do this?
| You can always just write your own conversion function. The following idea is stolen from heavily inspired by this fine answer:
char * int2base36(unsigned int n, char * buf, size_t buflen)
{
static const char digits[] = "0123456789ABCDEFGHI...";
if (buflen < 1) return NULL; // buffer too small!
char * b = buf +... |
7,218,519 | 7,218,633 | Pass a class member function as a function parameter | I have 2 C++ Class questions:
The 1st question is: How can I make it so I can pass a class member function as a parameter in another function & how can I then run/call that function? And how can I do the same with a class static function. It maybe easier to understand my question by looking at this code:
class Debuggi... | Static member functions of classes are ultimately no different than regular functions. They're really just syntactic sugar; the function is simply has a name that include Classname::.
Non-static members are another matter altogether. There are two important things to remember about non-static member functions (NSMF).
F... |
7,218,574 | 7,218,644 | Avoiding default construction of elements in standard containers | I'm interested in building an uninitialized_vector container, which will be semantically identical to std::vector with the caveat that new elements which otherwise would be created with a no-argument constructor will instead be created without initialization. I'm primarily interested in avoiding initializing POD to 0. ... | I think the problem boils down to the type of initialization that the container performs on elements. Compare:
T * p1 = new T; // default-initalization
T * p2 = new T(); // value-initialization
The problem with the standard containers is that they take the default argument to be value initialized, as in resize(size_... |
7,218,668 | 7,218,676 | Drawing a different image for two objects of the same class | I have two objects, whitepawn and blackpawn, that are of type Piece. Everything about these two objects is the same except for the image used. Currently this is the code I use to draw the white pawn,
void Pawn::paintEvent(QPaintEvent *)
{
pixmap.load(":/whitepawn.png");
QPainter paint(this);
paint.drawPixm... | Virtual functions are the standard solution here:
class Pawn
{
virtual void paintEvent(QPaintEvent *) { }
// ...
};
class WhitePawn : public Pawn
{
virtual voidpaintEvent(QPaintEvent *)
{
pixmap.load(":/whitepawn.png");
QPainter paint(this);
paint.drawPixmap(x, y, pixmap);
}
};
// similar for cl... |
7,218,678 | 7,218,688 | Define default constructor for abstract base class | class ClassA {
public:
ClassA() {} // when this function must be provided
virtual ~ClassA() = 0 {}
};
class ClassB : public ClassA
{
// ...
};
I want to know when the default constructor of an abstract base class must be provided.
| there is no connection between providing a default constructor, and the abstractness or not of the class.
provide a default constructor definition if you need to initialize things.
provide a (possibly non-implemented) non-public declaration if you want to prohibit default construction.
cheers & hth.,
|
7,218,763 | 7,218,788 | Is the "virtual" keyword optional in base classes in C++? | I'm trying to understand the function of the "virtual" keyword in C++ - consider this example:
#ifdef USE_VIRTUAL
struct a {
virtual void say_hi() { std::cout << "hello from a" << std::endl; }
};
#else
struct a {
void say_hi() { std::cout << "hello from a" << std::endl; }
};
#endif
struct b : public a {
void say... | You aren't using polymorphism. Polymorphic behaviour only affects pointers and references to base classes, like so:
class A; class B1 : A; class B2 : A;
B1 x;
B2 y;
A z;
A & a1 = x; // static type A&, dynamic type B1&
A & a2 = y; // static type A&, dynamic type B2&
A & a3 = z; // static and dynamic type A&
Now a... |
7,218,866 | 7,218,875 | Allow derived class to implement a single pure virtual function from base abstract class | Is it possible to have a abstract base class with a number of pure virtual functions:
template <typename T, typename U = NullType, typename V = NullType>
class Functor {
public:
virtual ~Functor() {}
virtual T operator()() = 0;
virtual T operator()(U arg1) = 0;
virtual T operator()(U arg1, V arg2) = 0... | No, that's not possible. What if you called T operator()(U) on a Test* and it hadn't implemented it? You'll have to eventually have a class implement all of them (or inherit from one or more classes that implement each of them) to instantiate it.
You can leave any number of virtual functions undefined, but if you do, y... |
7,219,020 | 7,219,158 | Run process with string input and output | There are plenty of questions on here related to fork() and exec(). I have not found one that really makes the process of using them simple though, and making programmer's lives simple is the goal.
I need a C++, linux-friendly function that does the following:
string RunCommand(string command, string input){}
This ... | It appears that you need a function to:
Create two pipes and fork.
The child process then does:
Duplicate appropriate descriptors of the pipes so that one file descriptor is standard input and one standard output
Close the pipe descriptors
Split up the command string into arguments
Run the command with the arguments
... |
7,219,062 | 7,219,066 | What's preferred pattern for reading lines from a file in C++? | I've seen at least two ways of reading lines from a file in C++ tutorials:
std::ifstream fs("myfile.txt");
if (fs.is_open()) {
while (fs.good()) {
std::string line;
std::getline(fs, line);
// ...
and:
std::ifstream fs("myfile.txt");
std::string line;
while (std::getline(fs, line)) {
// ...
Of course, ... | while (std::getline(fs, line))
{}
This is not only correct but preferable also because it is idiomatic.
I assume in the first case, you're not checking fs after std::getline() as if(!fs) break; or something equivalent. Because if you don't do so, then the first case is completely wrong. Or if you do that, then second ... |
7,219,063 | 7,219,089 | Win32: How to hide 3rd party windows in taskbar by hWnd | I have to hide popup windows in third party library.
I have implemented windows hook stuff with SetWindowsHookEx and know all the newely created hWnd(s). I listen to HSHELL_WINDOWCREATED callback and do the following:
long style= GetWindowLong(hWnd, GWL_STYLE);
style &= ~(WS_VISIBLE); // this works - window become... | Before you use SetWindowLong, call ShowWindow(hWnd, SW_HIDE), then call SetWindowLong, then call ShowWindow again like ShowWindow(hWnd, SW_SHOW). So your code will look like this:
long style= GetWindowLong(hWnd, GWL_STYLE);
style &= ~(WS_VISIBLE); // this works - window become invisible
style |= WS_EX_TOOLWINDOW; ... |
7,219,277 | 7,219,284 | Strange behavior of bitwise NOT (~) | How do I explain the following behavior?
#include<iostream>
using namespace std;
int main(){
unsigned char a = 8;
cerr << "a: " << (int)a << '\n';
unsigned char b = (~a) >> 6;
cerr << "b: " << (int)b << '\n';
unsigned char c = (~a);
c = c >> 6;
cerr << "c: " << (... | All arithmetic and bitwise operators in C always widen their arguments to at least int if they were originally shorter integral types. That's just how the language is defined. The language specification calls this the "integral promotion".
(The underlying reason for this is to make it easier to implement C on architect... |
7,219,434 | 7,219,530 | XML library optimized for big XML with memory constraints | I need to handle big XML files, but I want to make relatively small set of changes to it. I also want the program to adhere strict memory constraints. We must never use more than, say, 300Mb of ram.
Is there a library that allows me not to keep all the DOM in memory, and parse the XML on the go, while I traverse the DO... | It sounds like what you want is something similar to the Streaming API for XML (StAX).
While it does not use the standard DOM API, it is similar in principle to your "getChildren()" approach. It does not have the memory overheads of the DOM approach, nor the complexity of the callback (SAX) approach.
There are a numb... |
7,219,452 | 7,219,474 | Simple image analysis | I am looking for a method, software or library for simple image analysis.
The input image will be a white-colored background, and some random small black dots on it.
I need to generate a .txt file that represents these dots' coordinates. That is, if there are three dots in the image the output will be a text file that ... | It is quite simple in any language. Depending on the form of your input, you probably need to go over all of it (assuming it is a simple matrix - simply have two nested loops, one for the x coordinate and one for the y coordinate), whenever you encounter a black dot - simply output the current indexes which would be th... |
7,219,508 | 7,219,585 | Using boost::bind to create a function object binding a auto-release "heap" resource | I try to use boost::bind to create a function object, as well, I want to bind a object created on the HEAP to it for a delay call. The example code like below:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/typeof/typeof.hpp>
#incl... | You need to use bind composition:
return bind<int>( getM, bind(&shared_ptr<CTest>::get, a) );
|
7,219,614 | 7,219,627 | Floating point comparison in while loop with modulus | I would like some advise on how to optimise the following while loop:
double minor_interval = 0.1;
double major_interval = 1.0;
double start = 0.0;
double finish = 10.0;
printf("Start\r\n");
while (start < finish)
{
printf("Minor interval: %.20f\r\n", start);
double m = fmod(start, ... | I would implement this with a for loop over an int variable i. Using integers avoids rounding problems due to the limitations of floating point arithmetic. [See What Every Computer Scientist Should Know About Floating-Point Arithmetic.]
Let i run from 0 to iFinish-1 and set time equal to start + i*minor_interval. The v... |
7,219,615 | 7,221,035 | Getting Pointer or Reference to mapped_type from Arbitrary Map | Edit: I've found and written up a solution to my problem but I've left the question unanswered since my solution may still not be ideal.
I'm writing a small library designed to perform routines on maps of maps, but I'm having trouble designing a set of class templates that will let me get a pointer or reference (depend... | C and F seems wrong, the mapped type isn't boost::ptr_map. Otherwise it sounds like you could just use full template specialization to decide whether it is an std::map or boost::ptr_map. Something like this:
template <class Map>
class Whatever;
template <class K, class V>
class Whatever<std::map<K, V> >
{
public:
... |
7,219,633 | 7,219,799 | Designing a shader class | Since I have started learning OpenGL, I thought I would as well write a small C++ framework (for myself) to avoid the nausea that the excessive use of C-ish code is apparently causing. :) Since I am intending to stick with Qt, the framework uses some Qt classes.
The first thing I really needed was an easy way to use s... | I say use option 1: it can do everything option 2 can (via smart pointers), whereas option 2 makes you pay the indirection cost even when you don't need it. On top of that, it's arguably easier to write.
Similarly I've once considered using handle-body/PIMPL when wrapping over a C API, to allow returning objects from f... |
7,219,639 | 7,219,956 | C++ application that receives JSON and writes to database | I guess this is a novice question, but here goes anyway...
How do I get an application running on a machine to send data to another application running on a remote server which processes this data and writes it to a database? I would like to also authenticate the incoming data as well
Thanks,
| You basically need the following components in your application:
network communication module (client/server)
JSON parser/encoder
authentication module
database access module
For excellent C++ network library have a look at Boost.Asio, there are many examples how to use it.
For JSON library there is a Boost-based JSO... |
7,219,640 | 7,219,673 | What bad things may happen without calling to ReleaseDC? | Programming with C++, once we get the context device by GetDC to use. What bad things may happen if we exit the program without calling to ReleaseDC?
| From the docs
The ReleaseDC function releases a device context (DC), freeing it for
use by other applications. The effect of the ReleaseDC function
depends on the type of DC. It frees only common and window DCs. It has
no effect on class or private DCs.
As you can see, it may be needed if other applications can... |
7,219,827 | 7,219,902 | Avoid automatic transition of QGraphicsScene on QGraphicsView | Qt's QGraphicsView has a habit of automatic transition/sliding of the view in such a way that everything drawn on the attached QGraphicsScene is visible. For example, suppose you've drawn something on the scene and viewing in the view. Now upon a button press you draw something along the right edge of the view. The sce... | The scene rectangle of QGraphicsScene is by default the bounding rectangle of all the items in the scene. As such it grows when items are added.
The scene rectangle of QGraphicsView is by default taken from QGraphicsScene::sceneRect. If you don't want this to change automatically you can set one explicitly with QGraphi... |
7,220,180 | 7,220,207 | Why does a C++ string end in a null terminator? |
Possible Duplicate:
What's the rationale for null terminated strings?
My question is very simple: why do C++ strings end in null terminators? Is this so that you do not need to keep count on the length?
| Traditional strings in C and C++ use a null terminator to indicate the end of the string. Since string pointers simply pointed to an array of characters, without any length or other meta data, the null terminator was the only way to determine the length of the string.
As far as why it was done this way, that's more dif... |
7,220,212 | 7,876,083 | can i mark notification as already read , using the graph api? | I'm using this to get a notification list:
https://graph.facebook.com/me/notifications/?include_read=0
Now I'd like to mark them as read, how do I do this?
| You should issue a POST request to https://graph.facebook.com/%notification_id%?unread=false where %notification_id% is the notification identifier you've received earlier (usually something like 'notif_XXXXX_YYYYY').
If you want to mark all notifications read, you can perform a batch request.
|
7,220,287 | 7,220,382 | Boost lambda::_1 in C++ 0x | int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
std::for_each(v.begin(), v.end(), std::cout << boost::lambda::_1 << "\n");
}
Can this code be translated to C++ without using Boost? I know C++ 0x lambda expression syntax, but didn't try to use placeholders in... | No placeholder needed in this case, as lambdas capture the parameter:
std::for_each(v.begin(), v.end(), [](int x){std::cout << x << "\n";});
|
7,220,309 | 7,220,562 | Change a variable based on a target in Makefile | How can I change the value of a variable based on one of the targets in Makefile? Something link this:
target:
DEFINES += -DDEPLOY
| If your make is GNU make,
target-specific variable
might meet the purpose.
This facility allows almost the same notation as in the question
like the following:
target: DEFINES += -DDEPLOY
|
7,220,364 | 7,220,376 | how to convert char[] to string& | I have a method setValue(string& val) that I need to call for some default values.
I would like to call it like this:
setValue("");
setValue("random value");
but I get the following error with g++: no matching function to call setValue(const char [10])
any idea on how I can do this beside creating a temp string object... | The problem is that string& will not bind to temporary objects, only to non const named objects (non-const lvalues in the Standard language). You'll have to name an object to pass to your function, as you do with the temp variable.
One workaround is to use a const reference to string and pass directly your string liter... |
7,220,661 | 7,220,691 | How to resolve "class must be used when declaring a friend" error? | class two;
class one
{
int a;
public:
one()
{
a = 8;
}
friend two;
};
class two
{
public:
two() { }
two(one i)
{
cout << i.a;
}
};
int main()
{
one o;
two t(o);
getch();
}
I'm getting this error from Dev-C++:
... | You need
friend class two;
instead of
friend two;
Also, you don't need to forward-declare your class separately, because a friend-declaration is itself a declaration. You could even do this:
//no forward-declaration of two
class one
{
friend class two;
two* mem;
};
class two{};
|
7,221,126 | 7,221,152 | Writing functions in c++ | EDIT:
Sometimes it happens that our problem is kind of not in code but in our way of judging what is right and wrong. I am writing my problem through an example as it would help to explain it. The problem is in short "should our function handle each exception in iteself. Through the example i showded it sometimes becom... | The simpler approach I would use is a classifyTriangle function, that returns an enum of triangle types. Then, any subsequent code can just consult the return value to act according to the triangle type.
Alternatively, I believe that each function should concentrate on checking its own condition, regardless of other tr... |
7,221,257 | 7,221,268 | Which sorting algorithm is used in GCC? | From cplusplus.com std::sort complexity is defined:
Complexity
Approximately N*logN comparisons on average (where N is last-first).
In the worst case, up to N2, depending on specific sorting algorithm used by library implementation.
I have some limitations at running time for my apps. So i need to know if should i ... | GCC uses a variation of Musser’s introsort. This guarantees a worst-case running time of O(n log n):
It begins with quicksort and switches to heapsort when the recursion depth exceeds a level based on … the number of elements being sorted.
The implementation can be found in the stl_algo.h header in the __introsort_lo... |
7,221,567 | 7,256,866 | Ext JS in a WebKitGTK webkit_web_view | I'm trying to embed a web browser into a gtk project. I'm trying to use WebKitGTK (but I'm not committed to it), every time I try and use it to parse an Ext JS page, it crashes the entire application. Here's the output, and how I'm including the .js files...
** (ttocui_gtk:16360): DEBUG: NP_Initialize
** (ttocui_gtk:16... | This is an Ubuntu issue with the flash plugin I was using. Here's the stack trace.
Program received signal SIGABRT, Aborted.
0x00007ffff159cd05 in raise () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) where
#0 0x00007ffff159cd05 in raise () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x00007ffff15a0ab6 in abort () from /li... |
7,221,668 | 7,222,029 | Incorrect report of "multiple definitions" | I have been working on a cross-platform library in C++. I been compiling both in Windows (MinGW/msys) and Ubuntu (g++) and it compiles without any errors.
I just got the hand on a computer with Kubuntu. When I try to compile it there I get some errors saying that I have multiple definitions on some variables. Those va... | I figured it out with the help of bdonlans comment. The problem was in my makefile when creating lib-archive. I used the command
ar -cvq
which did not overwrite exist files in the archive, when changing to
ar -cr
it links without any errors
|
7,221,776 | 7,221,887 | dll to main program communication | I want to trace some text from dll module to a main program window (to a log subwindow). How can I do this correctly? (through kernel primitives, via sending messages from window to window, passing callback interfaces?) The working example I've seen: Matlab and Octave. When calling mexPrintf then output printed in thei... | Your main program should export a logging function and make it known to the DLL. Your DLL needs to export a function, such as InitLogging, that takes a function pointer and stores the passed value somewhere into its global data.
An alternative is to put your "main" program in another DLL and make a "stub" main that li... |
7,222,143 | 7,222,201 | unordered_map hash function c++ | I need to define an unordered_map like this unordered_map<pair<int, int>, *Foo>, what is the syntax for defining and passing a hash and equal functions to this map?
I've tried passing to it this object:
class pairHash{
public:
long operator()(const pair<int, int> &k) const{
return k.first * 100 + k.second;
... | This is an unfortunate omission in C++11; Boost has the answer in terms of hash_combine. Feel free to just paste it from them! Here's how I hash pairs:
template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
n... |
7,222,192 | 7,222,209 | C++ Chat client missing lib file | I have made a chat program with using Winsock2.h and the lib file ws2_32.lib.
When I want to test the chat program out on a computer on another network, it shows me a message box with the text:
"The program can't start because MSVCR100.dll is missing from your computer. Try reinstalling the program to fix this problem... | you should create a setup project which includes the required libraries and installs them in the client machine during your application's setup.
In fact you need a setup anyway if you want to create a shortcut to your program in the Start Menu or on the desktop for example.
|
7,222,323 | 7,222,600 | Qt QML How to format (highlight) text | I would like to write a simple plain text editor including simple markdown instructions in QML. Therefore I added a TextEdit-Element and a JavaScript Function for Syntax Highlighting.
As an example:
I want to print the string between two asterisks '*' in bold.
So I have to insert a <b> tag before or a </b> tag after th... | You can use window.getSelection() for get the selected text.
For example:
HTML:
<div id="test" onmouseover="getSelectedText()">a*b*</div>
JavaScript:
function getSelectedText() {
var m = 'getSelection';
if(m in window) {
var Selection = new String(window[m]());
var ... |
7,222,559 | 7,222,926 | How to use gluPerspective only once? | glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
//set viewpoint
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(VIEW_ANGLE,Screen_Ratio,NEAR_CLIP,FAR_CLIP);
gluLookAt(0,5,5, 0,0,0, 0,1,0);
//transform model 1
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(Theta, 0,1,0);
//draw model 1
glBegi... | You call gluPerspective there, because it belongs there. OpenGL is not a scene graph where you initialize things. It's a state driven drawing API. The projection matrix is a state and every serious graphics application changes this state multiple times throughout a single frame rendering.
OpenGL does not know geometric... |
7,222,657 | 7,299,335 | C++ project organisation | I've become a maintainer of a shared library project. The library is split into a few modules, each of them compiled as static library, then linked together. Eclipse is used as IDE, code stored at SVN server. So far the building process was handlet by hand - building libraries, moving all the .a and .h into shared fold... | So I solved it for now. I created a folder called Pool. Directory tree:
Pool
- inc
- arm
- proj1 public headers directory
- proj2 public headers directory
- proj3 public headers directory
- lin
- proj1 public headers directory
- proj2 public headers directory
- proj3 public... |
7,222,743 | 7,222,755 | In what order are global constructors called | In what order get the constructors of global object in C++ called?
This question arises in the context of a memory pool that manages the memory needs for some consumers. I was presented with a rather large source code which defines at global namespace some consumers just using heap functions. A memory pool should be ad... | Global variables are initialized in the order in which they're declared. So their constructor will be called in the same order in which they're initialized. This is true within one translation unit. However, the initialization order across multiple translation-units is not defined by the language specification.
And th... |
7,223,227 | 7,223,242 | Why does a false statement still execute? | I have this code...
void drawMap(void)
{
if (false)
return;
for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
{
if ((*iter)->get() == NULL)
continue;
PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
}
}
If I'm not mistaken it should NEVER execut... | if (false) will never execute its body... because the value of the condition is never true. So in the code you've given, the remainder of drawMap will always execute because it will never return at the start.
Consider if (x == 5) - that will only execute if the expression x == 5 is true. Now substitute false for x == 5... |
7,223,272 | 7,223,556 | Qt thread problem with single core CPU on Windows XP | I am developing a cross-platform fractal explorer using Qt. I am experiencing a performance problem specifically when running on a single core CPU under Windows XP (program compiled with MSVC Express 2010), I haven't tried other versions of Windows. With two cores the program runs fine. It also runs fine under Linux wi... | You say the update is slower than the calculation - how much slower? Have you done any comprehensive profiling to see where exactly the bottleneck occurs? A cursory google finds this profiler which may help you.
Remember that for older CPU's, thread context switching is very expensive. This may be part of your problem... |
7,223,432 | 7,223,544 | C++ data members. Goal: Initialize in constructor then leave alone, will const work here? | I have the following
struct dweDMPair {
const dweller *occu;
const double sqDM;
float prob;
dweDMPair(dweller *inOccu, double sqdm) : occu(inOccu), sqDM(sqdm) {} };
I want to return an array of pointers to these objects but desire that they should not be accidentally de... | You clarify that what you really want is:
Then I can export this instance as a const dweDMPair *ptrToVal so that the client cannot then call delete- because that won't work on pointers to const instances will it?
Delete can be called on pointers to const instances and it can be called on objects which contain const ... |
7,223,613 | 7,223,724 | C++ polymorphism without pointers | EDIT: A better title for this would be: polymorphism for large collections of objects without individual heap allocations.
Suppose that I have a base class Animal with virtual functions and some derived classes (Cat, Dog, etc.). The real derived classes contain 4-8 bytes of data. I want to store a std::list<Animal> whi... | Ultimately, no.
Polymorphism only works with non-value types: references and pointers. And since references can only be bound once, you cannot really use them in standard containers. That leaves you with pointers.
You're attacking the problem at the wrong end. If you are concerned about the overhead of allocating lots ... |
7,223,623 | 7,223,695 | Storing different vertex attributes in different VBO's | Is it possible to store different vertex attributes in different vertex buffers?
All the examples I've seen so far do something like this
float data[] =
{
//position
v1x, v1y, v1z,
v2x, v2y, v2z,
...
vnx, vny, vnz,
//color
c1r, c1g, c1b,
c2r, c2g, c2b,
...
cnr, cng, cnb,
};
GLuint buffname;... | The association between attribute location X and the buffer object that provides that attribute is made with the glVertexAttribPointer command. The way it works is simple, but unintuitive.
At the time glVertexAttribPointer is called (that's the part a lot of people don't get), whatever buffer object is currently bound ... |
7,223,734 | 7,223,762 | Automatic object destruction | Is the destruction of automatic objects (objects created on the stack) guaranteed to be executed not before they go out of scope?
To clarify:
#include <iostream>
class A {
public:
A() {
std::cout << "1";
}
~A() {
std::cout << "3";
}
};
void test123() {
A a;
std::cout << "2";
}
To pr... | The destruction order of stack objects is strictly defined - they execute in reverse order of declaration, when you leave the scope (either by running off the end of the {}, or by return, or by an exception). So, you will always see 123 there.
Note, however, that compiler optimizations are governed by the 'as-if' rule.... |
7,223,809 | 7,224,487 | using from_string with boost date | I have the following code:
#include <iostream>
#include <string>
#include <iomanip>
#include <locale>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/gregorian/parsers.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
u... | Boost date_time isn't header only, you need to link it on the command line, for example:
gcc myprogram.cpp -omyprogram -lboost_date_time
|
7,223,813 | 7,223,888 | C++ Covariance and references | Lets say I have an abstract base class with a pure virtual that returns an expensive object. As it's an expensive object, I should return a reference to it.
But life's not that simple, let's say I have two classes derived from it: one has the function called often, so it is more efficient to store a copy in the instan... | One solution is to create a smart pointer class to manage BigObj*s:
class BigObjPtr {
public:
BigObjPtr(bool del, BigObj* ptr) : del(del), ptr(ptr) { }
BigObj* operator->() {
return ptr;
}
virtual ~BigObjPtr() {
if (del) delete ptr;
}
private:
BigObj* ptr;
bool del;
};
Th... |
7,223,833 | 7,223,897 | how to write a wrapper class for sigc++? | would like to have a central place to register new signals, connect to signals, and so on. now i thought to use sigc++. however, i don't know how to code a wrapper class for this template based lib. something along the lines of:
class EventManager {
public:
... singleton stuff ...
template<typename ReturnType, ... | You'll need a base class which have emit() function:
template<class Ret>
class SigBase {
public:
virtual Ret emit()=0;
};
and then some implementation of it:
template<class Ret, class Param1>
class SigDerived : public SigBase<Ret>
{
public:
SigDerived(sigc::signal<Ret, Param1> *m, Param1 p) : m(m), p(p){ }
Ret ... |
7,223,863 | 7,223,902 | why isn't assignment operator called here? | Edit: sorry I used "assignment constructor" instead of "assignment operator" in my original post. Fixed now.
It turns out that the copy constructor is called instead of the assignment operator in the following code. Anyone can tell me the reason behind this? Thank you.
class A
{
int i;
public:
A(int ii) { i = ii; }
A(... | A a(4);
A b = a;
None of them is assignment1. Both are initialization.
First one is called direct-initialization, and second one is called copy-initialization.
The difference between them is that first one would work even if the copy-constructor is inaccessible (i.e its either private or protected), and second one w... |
7,223,991 | 7,224,086 | C++11 predefined macro | Are there any predefined macros for C++ in order the code could identify the standard?
e.g. Currently most compilers puts "array" into "tr1" folder but for C++11 it would be part of STL. So currently
#include <tr1/array>
but c++11
#include <array>
What is the predefined macros for 03 standard and 11 standard in order... | From Stroustrup's C++11 FAQ
In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.
You can likely test it's value to determine if it's c++0x or not then.
|
7,223,993 | 7,224,251 | Will C++ linker automatically inline functions (without "inline" keyword, without implementation in header)? | Will the C++ linker automatically inline "pass-through" functions, which are NOT defined in the header, and NOT explicitly requested to be "inlined" through the inline keyword?
For example, the following happens so often, and should always benefit from "inlining", that it seems every compiler vendor should have "automa... | Here's a quick test of your example (with a MyA::foo() implementation that simply returns 42). All these tests were with 32-bit targets - it's possible that different results might be seen with 64-bit targets. It's also worth noting that using the -flto option (GCC) or the /GL option (MSVC) results in full optimization... |
7,224,259 | 7,224,268 | Iteration Vs. Enumeration | For iteration, I know there are different types of iterators E.g. Forward, Bidirectional, Random Access that can be used to access items in an array.
For enumeration, I've only heard about enums that can be used to index items. But are there terms called 'enumeration' or enumerator? If so then, What's the difference be... | The terminology is really tied to the language, and gets pretty confusing.
In C++, an "enumeration" (enum) is a name, meaning "a bunch of numbered items", so there's no action going on; it's just a thing (like a class).
And of course, "iteration" refers to an action, meaning "to repeat an action many times". Often, t... |
7,224,300 | 7,252,341 | Error "msvcr100.dll" (only on Windows 7 & Vista) even AFTER statically linking (/MT) | I have a simple dll that is being injected into a target process using MS detours. The process doing the injecting is C# .net application.
Both the DLL and the detours library have been statically linked (/MT option).
However when I try to inject the dll into a target program on a client's machine I get error "msvcr... | So I never did discover exactly what the issue is but on a hunch I tried running the application (exact same build w/ mscvr100.dll error) on another Windows 7 machine and it worked fine.
I reinstalled Windows 7 on the "problem" machine and the same build works fine without error. In my google searching I came across a... |
7,224,358 | 7,224,401 | Why isn't setjmp saving the stack? | Why isn't setjmp saving the stack?
Consider the following code:
#include <iostream>
jmp_buf Buf;
jmp_buf Buf2;
void MyFunction()
{
for(int i = 0; i < 5; i++)
{
std::cout << i << std::endl;
if(!setjmp(Buf))
longjmp(Buf2, 1);
}
}
int main (int argc, const char * argv[])
{
wh... | Because unfortunately thats not how setjmp works. setjmp copies the current instruction pointer and register set into the jump buffer but it does not copy the stack (obviously be cause the stack is huge). It looks like you want to use some kind of coroutine based techniques. If you want to do this yourself checkout... |
7,224,386 | 7,224,432 | Iterating with size_t 0 as a boundary condition | What's the "correct" way to write a decreasing loop with a size_t value and a boundary condition. Example incorrect implementation:
for (size_t elemNum = listSize-1; elemNum >= 0; --elemNum) { /* ... */ }
When it reaches zero it will wrap around to the max value rather than acting as a boundary condition. Iterating th... | The most succinct approach is to use post-increment:
for (size_t i = listSize; i--;) ...
|
7,224,457 | 7,224,492 | Loop quitting for no reason | I have a question regarding C++. This is my current function:
string clarifyWord(string str) {
//Remove all spaces before string
unsigned long i = 0;
int currentASCII = 0;
while (i < str.length()) {
currentASCII = int(str[i]);
if (currentASCII == 32) {
str.erase(i);
... | Okay so the erase function you are calling looks like this:
string& erase ( size_t pos = 0, size_t n = npos );
The n parameter is the number of items to delete. The npos means, delete everything up until the end of the string, so set the second parameter to 1.
str.erase(i,1)
[EDIT]
You could change the first loop to ... |
7,224,699 | 7,224,715 | Writing C/C++ Compiler to the MBR to execute source code before Booting up the OS | I am trying to write the full OS independent program on C++. I want to load the program just before booting up the OS (i.e. Windows). I tried to replace the MBR with my simple “Hello World” program, but nothing happens and I lost Partition table of Virtual Hard disk.
I think I should write the C++ compiler to the MBR ... | It is impossible to write such program in plain C/C++. There is no OS, and the compiler should work in "freestanding" mode. In this mode there is not "stdin.h" header, no files, no file access and no printf are available.
So, you program should call BIOS functions directly, e.g. using asm keyword.
Format of MBR binary... |
7,224,820 | 7,224,855 | Auto delete object while cycling vector | I have an std::vector of objects and i cycle it calling some methods of the object. One of them will check a particular condition and if needed will delete itsef from the vector. The point is that erasing the element invalidate the iterator and I cannot continue the loop of it. I found boost::shared_ptr and boost::weak... | Never mind what your vector contains - the deletion of managed resources can indeed be left to smart pointers, but the more pressing issue is how to manipulate the container itself.
std::vector indeed has very poor iterator invalidation: erasing or inserting invalidates all iterators from the erasee/insertee onwards, s... |
7,224,919 | 7,225,283 | QT SDL Not Recognized (Have Qmake File listed. Am I doing it wrong?) | Here is my qmake file. For whatever reason, when I try to compile the program SDL isn't being recognized. Why is this?
LIBS += -L/usr/include/SDL.h -lSDL
HEADERS += \
render.h \
screenwriter.h
SOURCES += \
screenwriter.cpp \
render.cpp
| It seems SDL uses pkgconfig:
$ repoquery -l SDL-devel | fgrep .pc
/usr/lib/pkgconfig/sdl.pc
/usr/lib64/pkgconfig/sdl.pc
So the best way to link with it would be to use link_pkgconfig, instead of adding it manually to LIBS:
CONFIG += link_pkgconfig
PKGCONFIG += sdl
This will automatically modify QMAKE_CXXFLAGS, QMAKE_... |
7,224,944 | 7,225,006 | Can I default a private constructor in the class body or not? | GCC 4.5 doesn't let me do this:
class foo {
public:
foo() = default;
private:
foo(foo const&) = default;
foo& operator=(foo const&) = default;
};
It complains that:
error: 'foo::foo(const foo&)' declared with non-public access cannot be defaulted in the class body
error: 'foo& foo::operator=(const foo&... | There is nothing in N3291 that says you cannot declare something private and default. Note that this was a change to the specification, in section 8.4.2, paragraph 2; earlier versions said that they must be public.
|
7,225,076 | 7,225,093 | Strange Compiler Error: "undefined reference to 'main'" | Could someone tell me what this means?
/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status
make: *** [program] Error 1
My make file looks like as follows:
program : main.o render.o screenwriter.o
g++... | That first rule should be
program : main.o render.o screenwriter.o
g++ -o program main.o render.o screenwriter.o -lSDL
Assuming that you want to link main.o render.o screenwriter.o into an executable called program
Also, in the compile steps ( -c ) the -lDSL bit is not useful, it's a linker instruction.
|
7,225,079 | 7,225,188 | How do i call an external function? | I have code i'm trying to write, I have a void function, info.
void info(char *,char *);
This, I'm trying to call from my main function in a separate file. I want to use dlopen to open a so file. How would i call the function: info. From my other file?
I'm trying to use
info("testing: ","Success");
I get an undefine... | The usual path is something like this:
/* Set up a typedef for the function pointer to make the code nicer */
tyepdef void(*Info_ptr)(char*, char*);
/* Get the function, lib must be the dlopened library.*/
Info_ptr info;
info = (Info_ptr)dlsym( lib, "info");
/* Use the function pointer */
(*info)("testing: ", "Suc... |
7,225,294 | 7,225,302 | Constructors in union causing undefined behavior? | I get the values for NumericType Values (10, 3.1416, 20) to be 20, 3.1416, 20 after the object has been constructed. is the behaviour for constructors in a union defined?
union NumericType
{
NumericType() {}
NumericType(int i, double d, long l)
{
iValue = i;
dValue = d;
lValue = l;
... | What you're doing doesn't make sense. Because it's a union, you're assigning to the same area of memory 3 times. Because you assign to lvalue in the constructor last, that's what everything remains at. All three variables are at the same location and occupy the same memory (with the exception of dValue which takes up 4... |
7,225,315 | 7,225,327 | Should the objects initialized and stored in another class be dynamically/statically allocated? | I am new to C++ but I have some basic memory allocation knowledge in C. I am writing a class Card, which stores the card number and a list of class Activity object.
class Card {
public:
Card();
~Card();
vector<Activity> activities;
int cardNo;
}
Currently, I initialize the Activity object using co... | No, what you're doing is fine. When you push an object onto a vector, a copy is made. So when your function returns, your a is destroyed, but the vector you added it to still has its own seperate copy.
One reason someone might allocate an instance of a class dynamically and push it onto a vector would be that copying o... |
7,225,441 | 7,225,465 | How is this Precedence operators working? | I know this is silly question but I don't know which step I'm missing to count so can't understand why the output is that of this code.
int i=2;
int c;
c = 2 * - ++ i << 1;
cout<< c;
I have trouble to understanding this line in this code:
c = 2 * - ++ i <<1;
I'm getting result -12. But I'm unable to get it how is prece... | Have a look at the C++ Operator Precedence table.
The ++i is being evaluated, yielding 3.
The unary - is being evaluated, yielding -3.
The multiplication is being done1, yielding -6.
The bit shift is evaluated (shifting left by 1 is effectively multiplying by two) yielding -12.
The result -12 is being assigned to the ... |
7,225,645 | 7,225,704 | Least brute force way to see how many groups of numbers in a group of numbers add to a given number in C++ or Python | The title is probably a little ambiguous.
There is a given number.
There is a set of numbers all less than the given number and greater than zero.
I want to know how many different combinations of adding numbers there are that equal the given number.
For example if the given number is 14 and the numbers in the set are... | Don't be discouraged by the claims that this is NP-complete. The Wikipedia article on Subset Sum linked by @isbadawi mentions a 1999 paper by Professor David Pisinger with an algorithm that sounds like it would work with your existing constraints in linear time: http://www.sciencedirect.com/science/article/pii/S019667... |
7,225,781 | 7,225,810 | What is the best way to implement operator<? | Sorry if this is a stupid question, but it's something that I'm curious about.
I am overloading the less-than operator for my sort algorithm based on last name, first name, middle name. I realize there is not a right or wrong here, but I'm curious as to which style is written better or preferred among fellow programmer... | I prefer:
bool CPerson::operator<(const CPerson& key) const
{
if (m_Last == key.m_Last) {
if (m_First == key.m_First) {
return m_Middle < key.m_Middle;
}
return m_First < key.m_First;
}
return m_Last < key.mLast;
}
Nice and systematic, and it is obvious how new members c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.