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,774,934 | 2,774,961 | Setting precision on std::cout in entire file scope - C++ iomanip | I'm doing some calculations, and the results are being save in a file. I have to output very precise results, near the precision of the double variable, and I'm using the iomanip setprecision(int) for that. The problem is that I have to put the setprecision everywhere in the output, like that:
func1() {
cout<<setprecis... | Are you looking for cout.precision ?
|
2,775,024 | 2,775,090 | Name lookup for names not dependent on template parameter in VC++2008 Express. Is it a bug? | While experimenting a bit with C++ templates I managed to produce this simple code, for which the output is different, than I expected according to my understanding of C++ rules.
void bar(double d)
{
std::cout << "bar(double) function called" << std::endl;
}
template <typename T> void foo(T t)
{
bar(3);
}
voi... | It is indeed a bug in the compiler. The problem was known to exist in VS2005 and before (I use a Blogspot blog as a notebook for cases like this, see 1.3 here). Apparently it is present in VS2008 as well.
You can test it with the following simple code
int bar(double d) { return 0; }
template <typename T> void foo(T t)... |
2,775,109 | 2,775,270 | Safe to cast pointer to a forward-declared class to its true base class in C++? | In one header file I have:
#include "BaseClass.h"
// a forward declaration of DerivedClass, which extends class BaseClass.
class DerivedClass ;
class Foo {
DerivedClass *derived ;
void someMethod() {
// this is the cast I'm worried about.
((BaseClass*)derived)->baseClassMethod() ;
}
};
Now, Der... | It may work, but the risk is huge.
The problem is that most of the times Derived* and Base* will indeed have the same value under the hood (which you could print). However this is not true as soon as you have virtual inheritance and multi-inheritance and is certainly not guaranteed by the standard.
When using static_ca... |
2,775,236 | 2,775,250 | functionality of cin in c++ | I'm a bit confused by the results of the following function:
int main() {
string command;
while(1) {
cin >> command;
if(command == "end")
return 0;
else
cout << "Could you repeat the command?" << endl;
}
return 0;
}
First of all - the output line ("could you...") repeats once for ... | The formatted input operator >>() reads space separated tokens from input. If you want to read whole lines, use the getline() function:
string command;
getline( cin, command );
|
2,775,248 | 2,775,441 | How to bundle C/C++ code with C-shell-script? |
I have a C shell script that calls two
C programs - one after the another
with some file handling before,
in-between and afterwards.
Now, as such I have three different files - one C shell script and 2 .c files.
I need to give this script to other users. The problem is that I have to distribute three files - wh... | Sounds like you're worried that your users aren't savy enough to figure out how to resolve issues like command not found errors and the like. If absolutely MUST hide "complexity" of a collection of files you could have your script create the other files. In most other circumstances I would suggest that this approach is... |
2,775,277 | 2,775,295 | Can a single argument constructor with a default value be subject to implicit type conversion | I understand the use of the explicit keyword to avoid the implicit type conversions that can occur with a single argument constructor, or with a constructor that has multiple arguments of which only the first does not have a default value.
However, I was wondering, does a single argument constructor with a default va... | The existence of a default value does not stop the single-argument ctor from being used for implicit conversion: you do need to add explicit if you want to stop that.
For example...:
#include <iostream>
struct X {
int i;
X(int j=23): i(j) {}
};
void f(struct X x) {
std::cout << x.i << std::endl;
}
int main() {... |
2,775,469 | 2,775,505 | Calling a function that uses object members without giving the object | void CVisualStudioDemoDoc::updateLine(void)
{
int newln = GetLineNumber(p_buf);
reinterpret_cast<CVisualStudioDemoView *>(m_viewList.GetHead())->SetCurrentLineNumber(ln, newln);
ln = newln;
}
I want to call this function from another part of my code without having to give the object pointer and include headers.
I want... | You can't do this.
If a member function refers to member variables, it needs a valid this pointer. If you don't include the header file that declares the function, the compiler can't know what you're referring to. How can it know that updateLine() is a function unless you tell it?
If you're trying to call a C++ membe... |
2,775,578 | 2,775,658 | Biased Random Number Generator | I am looking for a random number generator that can be biased. For instance, say I want a random number between 1-5, with the probability being:
1: Comes up 20% of the time
2: Comes up 10% of the time
3: Comes up 40% of the time
4: Comes up 25% of the time
5: Comes up 5% of the time
Is there anything in the standard ... | The Boost random number library provides the ability to specify different shaped distributions for your generator. It's a great library - see http://www.boost.org/doc/libs/1_42_0/libs/random/index.html.
|
2,775,602 | 2,775,636 | im counting the number of characters in a file but i want to count the number of words that are less than 5 and 6 or greater | i want to do this:
reads the words in the file one at a time. (Use a string to do this)
Counts three things: how many single-character words are in the file, how many short (2 to 5 characters) words are in the file, and how many long (6 or more characters) words are in the file. HELP HERE
im not sure on how about read... | I'm not quite sure where to start...
Your loop:
while(!infile.eof())
{
infile.get(letter);
cout << letter;
numb_char++;
break;
}
Would only execute once due to the extra break;
Also this code looks like it is trying to read the number of characters in a file, and not count up the number of words that are 5 l... |
2,775,854 | 2,775,952 | Map a 32 bit float to a 32 bit integer | Is there a way to map floats to ints or unsigned ints so that with the exception of NaN, order is preserved?
So if a and b are floats, and F is the mapping function,
a < b implies F(a) < F(b)
and
a == b implies F(a) == F(b)
| Hm, just out of the DawsonCompare routine in Game Programming Gems 6, it's a normal bit-cast followed by a sign flip (since negative floats order opposite then negative integers). I'll borrow that idea.
You have:
// utility
template <typename R, typename T>
R& bit_cast(T& pX)
{
return reinterpret_cast<R&>(pX);
}
/... |
2,776,313 | 2,776,328 | Foo f = Foo(); // no matching function for call to 'Foo::Foo(Foo)' ... huh? | class Foo
{
public:
explicit Foo() {}
explicit Foo(Foo&) {}
};
Foo d = Foo();
error: no matching function for call to 'Foo::Foo(Foo)'
I tried changing Foo(Foo&) to Foo(Foo) as the error suggests, which AFAIK is not a valid constructor, and sure enough I get:
error: invalid constructor; you probably meant ‘... | There are two questionable things that you have in your copy constructor.
First, you've made the copy-constructor explicit (which is a questionable thing to do), so you would (in theory) need to do:
Foo d( (Foo()) );
Second, your copy constructor takes a reference and not a const reference which means that you can't u... |
2,776,381 | 2,776,393 | What Does an OS Actually Do? | What exactly does an operating system do? I know that operating systems can be programmed, in, for example, C++, but I previously believed that C++ programs must be run under an operating system? Can somebody please explain and give links? thanks in advance, ell
| An operating system is a layer between your code (user code) and the hardware.
The OS is responsible for managing the physical components and giving you a simple (hopefully) API off of which to build. It handles which programs run, when, who goes first, how memory is handled, who gets memory, video drawing, and all th... |
2,776,389 | 2,776,457 | Operator+ for a subtype of a template class | I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+.
#include <iostream>
template<typename other_type>
struct c {
c(other_type v) : cs(v) {}
struct subtype { subtype(other_type v) : ... | Your suspicion is correct. The compiler doesn't know what other_type is. It can't deduce it from the arguments. Such forms often are too loose to provide the needed informations. Consider
template<typename other_type>
struct c {
c(other_type v) : cs(v) {}
typedef int subtype;
};
If you were to pass an int, then a... |
2,776,608 | 2,776,650 | How to demonstrate memory error using arrays in C++ | I'm trying to think of a method demonstrating a kind of memory error using Arrays and C++, that is hard to detect. The purpose is to motivate the usage of STL vector<> in combination with iterators.
Edit: The accepted answer is the answer i used to explain the advantages / disadvantages. I also used: this
| A memory leak? IMO, vector in combination with iterators doesn't particularly protect you from errors, such as going out of bounds or generally using an invalidated iterator (unless you have VC++ with iterator debugging); rather it is convenient because it implements a dynamically resizable array for you and takes care... |
2,776,775 | 2,777,040 | Question on Virtual Methods | IF both methods are declared as virtual, shouldn't both instances of Method1() that are called be the derived class's Method1()?
I am seeing BASE then DERIVED called each time. I am doing some review for an interview and I want to make sure I have this straight. xD
class BaseClass
{
public:
virtual void Method1() ... | What you are seeing here is called "slicing". Casting an object of the derived class to the base class "slices off" everything that is not in the base class.
In C++ virtual functions work correctly only for pointers or references. For your example to work right, you have to do the following:
DerClass myClass;
((Bas... |
2,776,872 | 2,777,026 | QGLWidget + QGraphicsScene + QGraphicsView problem | I would like to create a simple thumbnail viewer using QGLWidget, QGraphicsScene and QGraphicsView. And I have a problem with placing QGLWidget on QGraphicsScene. The code is similar to this:
QGraphicsScene *testScene = new QGraphicsScene (0, 0, 400, 400, 0);
QGLWidget *testWidget1 = new QGLWidget();
testWidget1->rend... | The QGraphicsScene::addWidget documentation states that QGLWidget is not a supported widget type.
Parenting a QGLWidget onto the viewport of the QGraphicsView doesn't seem to work either.
Edit:
Actually parenting a QGLWidget to the viewport does work provided I put the renderText call within the paintGL method of my te... |
2,777,003 | 2,777,052 | c++ problem, maybe with types | I have a little problem in my code. The variables don't want to change their values. Can you say why?
Here is my code:
vector<coordinate> rocks(N);
double angle;
double x, y;
// other code
while (x > 1.0 || x < -1.0 || y > 1.0 || y < -1.0) {
angle = rand() * 2.0 * M_PI;
cout << angle << endl;
cout << rocks[... | Why are you expeciting x and y to change? You assign to them the value of a calculation that doesn't change?
rand() * 2.0 * M_PI is always a multiple of 2 * pi (as far as a double can represent) so cos(angle) will be 1 and sin(angle) will be 0.
|
2,777,104 | 2,777,172 | Compile C++ from VS08/10 without Run Time Library / MFC | Are there settings I can adjust in Visual Studio so that it does not compile with any run time library or MFC. I started learning C++ to get away from C#'s .Net, and this is just as bad. When I execute the program in a Windows XP virtual machine I get an error. I can compile without the dependencies in Code::Blocks, bu... | You can simply link to the static version of the CRT; just go into the project properties and specify, for the Release configuration, the "Multithreaded (/MT)" CRT instead of the "Multithreaded DLL (/MD)" (you can leave the debug configuration alone, since you'll run it just on your machine anyway). In this way your ex... |
2,777,177 | 2,777,210 | Can I use MFC objects in STL containers? | The following code doesn't compile for me in MSVC2005:
std::vector<CMenu> vec(10);
CMenu is an MFC menu object (such as a context menu). Through some testing I learned that CMenu does not have a public copy constructor.
To do what I wanted to do, I needed to use a dynamic array.
CMenu* menus = new CMenu[10];
// ...
de... | You could use pointer containers or containers of smart pointers, e.g. using shared_ptr from Boost or TR1:
std::vector<shared_ptr<CMenu> > vec;
vec.push_back(make_shared<CMenu>());
|
2,777,241 | 2,777,254 | Function calculating the probability of a letter in an sentence | I have a function that is supposed to calculate the number of times a letter occurs in a sentence, and based on that, calculate the probability of it occurring in the sentence. To accomplish this, I have a sentence:
The Washington Metropolitan Area is the most educated and affluent metropolitan area in the United Stat... | When you divide occur by sum, you are dividing an int by an int, which truncates (to 0 in this case). It doesn't matter that you are assigning the result to a double. To fix this, cast occur to a double before the division:
box[c8].prob = ((double)box[c8].occur)/sum;
|
2,777,248 | 2,777,925 | How does GetGlyphOutline function work? (WinAPI) | Basically I want to get bezier control points from a ttf font and then draw them. I was basically wondering 2 things.
Does it return an array of points or is it more complex?
How can you tell the points of 1 contour from another ex: the letter O which has 2 contours?
Thanks
| Found it:
The native buffer returned by GetGlyphOutline when GGO_NATIVE is specified is a glyph outline. A glyph outline is returned as a series of one or more contours defined by a TTPOLYGONHEADER structure followed by one or more curves. Each curve in the contour is defined by a TTPOLYCURVE structure followed by a nu... |
2,777,360 | 3,669,586 | Only Integrating Box2D collision detection in my 2d engine? | I have integrated box2d in my engine, ( Debug Draw, etc. ) and with a world I can throw in some 2d squares/rectangles etc.
I saw this post, where the user is basically not using a world for collision detection, however the user doesn't explain anything about how he's using the manifold (b2Manifold), etc.
Another post, ... | Is there any reason you can't use a b2World? Just because you use it, doesn't mean you have to use the physics simulations, unless you're severely performance limited.
See this example on using Box2D for collision only in Cocos2d. Maybe you can apply something similar to your project: http://www.raywenderlich.com/606/h... |
2,777,372 | 2,777,433 | Constructors with inheritance in c++ | If you have 3 classes, with arrows going from parent to child classes (i.e. "A -> B" means "B inherits from A":
shape -> 2d shape -> circle
+----> 3d shape -> sphere
When you write your constructor for the circle class, would you ever just initialize the grandparent Shape object and then your current object, skippi... | Yes, as you pointed out at the end of the post, you class constructor can only call its immediate parent's constructor, you can't "skip" classes and initialise your parent's parent.
|
2,777,375 | 2,777,392 | C++ increment operator | How to differentiate between overloading the 2 versions of operator ++ ?
const T& operator ++(const T& rhs)
which one?
i++;
++i;
| These operators are unary, i.e., they do not take a right hand side parameter.
As for your question, if you really must overload these operators, for the preincrement use the signature const T& operator ++(), and for the postincrement, const T& operator(int). The int parameter is a dummy.
|
2,777,527 | 2,777,995 | Stopping a runaway Lua subprocess | I have embedded Lua in an Objective-C application using LuaObjCBridge. I need to know how to stop the Lua process if it taking too much time (infinite loop?).
Would running it in a separate thread help?
| The usual way to do this is to use lua_sethook to schedule a callback every count VM instructions; when the callback lua_Hook function occurs after a excessive time your hook function can raise an error forcing control to your protected call.
|
2,777,541 | 2,777,558 | Static const double in c++ | Is this the proper way to use a static const variable? In my top level class (Shape)
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
static const double pi;
private:
double originX;
double originY;
};
const double Shape::pi = 3.14159265;
#endif
And then later in a class that extends Shape, I use... | Because const double Shape::pi = 3.14159265; is the definition of Shape::pi and C++ only allows a single definition of a symbol (called the one-definition-rule which you may see in it's acronym form ODR). When the definition is in the header file, each translation unit gets it's own definition which breaks that rule.
... |
2,777,707 | 2,778,752 | Performance considerations when mixing C++ and Objective-C in same file | I have some high-performance C++ that I need to interface with Objective-C, is there any performance penalty to just dumping this code into a .mm file that contains my Objective-C code vs. leaving this code in a separate .cpp file and extern-ing all the functions I need to call from the .mm file?
| There are a handful of issues here.
(1) if your C++ engine code is running in isolation -- if the Objective-C is acting as the front-end that triggers the underlying engine -- then there is no penalty at all. The C++ bits in ObjC++ compile just like regular C++.
(2) If you are calling into Objective-C from within the ... |
2,777,751 | 2,777,760 | Convert integer to formatted LPCWSTR. C++ | I have a direct3d project that uses D3DXCreateTextureFromFile() to load some images. This function takes a LPCWSTR for the path to file. I want to load a series of textures that are numbered consecutively (ie. MyImage0001.jpg, MyImage0002.jpg, etc) But c++'s crazy strings confuse me.
How do i:
for(int i=0; i < 3;i++... | One option is std::swprintf:
wchar_t buffer[256];
std::swprintf(buffer, sizeof(buffer) / sizeof(*buffer),
L"MyImage%04d.jpg", i);
You could also use a std::wstringstream:
std::wstringstream ws;
ws << L"MyImage" << std::setw(4) << std::setfill(L'0') << i << L".jpg";
ws.str().c_str(); // get the underlyin... |
2,777,873 | 2,777,889 | c++ exceptions and program execution logic | I have been thru a few questions but did not find an answer.
I wonder how should the exception handling be implemented in a C++ software so it is centralized and it is tracking the software progress?
For example, I want to process exceptions at four stages of the program and know that exception happened at that specifi... | You could keep a global variable containing the state of the program, and print it out in the catch block. Then you would only need two catch blocks, one for std::exception and one for everything else.
|
2,777,937 | 2,777,991 | How to wrap two unmanaged C++ functions into two managed C# functions? | I've got two unmanaged C++ functions, Compress and Decompress. The arguments and returns go as followed:
unsigned char* Compress (unsigned char*,int)
unsigned char* Decompress (unsigned char*,int)
Where all uchars are arrays of uchars.
Could someone please help me lay out a way to convert these into managed C# code usi... | You should be able to pass the unsigned char* parameter in as a byte[] and standard P/Invoke marshaller should handle that. You will have to marshal the output unsigned char* yourself, but that should just be a call to Marshall.Copy(). See below for an example of what I think will work.
Two big questions:
How does t... |
2,778,193 | 4,714,939 | segfault during __cxa_allocate_exception in SWIG wrapped library | While developing a SWIG wrapped C++ library for Ruby, we came across an unexplained crash during exception handling inside the C++ code.
I'm not sure of the specific circumstances to recreate the issue, but it happened first during a call to std::uncaught_exception, then after a some code changes, moved to __cxa_alloca... | Following Michael Dorgan's suggestion, I'm copying my comment into an answer:
Found the real cause of the problem. Hopefully this will help someone else encountering this bug. You probably have some static data somewhere that is not being properly initialized. We did, and the solution was in boost-log for our code base... |
2,778,271 | 2,778,288 | compiling a c++ program including mysql | I'm new to gcc, and trying to compile a c++ program which includes mysql.h using the command:
g++ -o test test.cpp -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql
It works without issue, but I was wondering if someone could explain the arguments to me. I don't like using commands I don't understand.
Thanks
| -o test means the output file is to be named "test".
test.cpp is your source file, of course.
-L/usr/include/mysql means to look for libraries in /usr/include/mysql, as well as in the usual link path. (It probably isn't finding any libraries here; my libmysqlclient.a is in the standard library directory /usr/lib. So I... |
2,778,289 | 2,778,337 | struct size is different from typedef version? | I have the following struct declaration and typedef in my code:
struct blockHeaderStruct {
bool allocated;
unsigned int length;
};
typedef struct blockHeaderStruct blockHeader;
When I do sizeof(blockheader), I get the value of 4 bytes back, but when I do sizeof(struct blockHeaderStruct), I get 8 bytes.
Why is ... | Looking at the definition of your struct, you have 1 byte value followed by 4 byte Integer. This integer needs to be allocated on 4 byte boundary, which will force compiler to insert a 3 byte padding after your 1 byte bool. Which makes the size of struct to 8 byte. To avoid this you can change order of elements in the ... |
2,778,352 | 2,778,357 | Template Child Class Overriding a Parent Class's Virtual Function | The below code compiles with gcc v4.3.3 and the templated child class seems to be overriding a virtual function in the parent, but doesn't that break the rule that you cannot have a virtual template function? Or is something else happening that I don't understand?
class BaseClass
{
public:
virtual void Func(int var)... | A class template may have virtual member functions.
A member function template cannot be virtual. That is, the following is invalid:
class C
{
public:
template <typename T>
virtual void f();
};
In addition, if a derived class has a member function template with the same name as a virtual function in a base cl... |
2,778,578 | 2,778,731 | What are pointers to class members used for? | I have read about pointers to class members, but I have never seen them being used in any practical applications. Can someone explain what are the use cases of such pointers? Is it really necessary to have such pointers?
Eg.
class abc
{
public:
int a;
abc(int val) { a = val; }
};
int main()
{
int abc::*da... | The biggest advantage of a pointer-to-member or pointer-to-member-function is that you
don't have to bind to a specific instance right away
don't need to place any restrictions on the member names, only the type has to match.
This can be used for e.g. call-backs or abstract algorithms:
std::map<int,int> m;
m.insert(... |
2,778,621 | 2,778,640 | Can I use C++/CLI (.NET Winforms/WPF ) to provide GUI for app written in native C & C++ | I've an app written C & C++. Now, I need to provide a GUI for this app. MFC is the best option for me. But I'm not familiar with MFC.
So can I use .NET to build GUI for this? If so, How? Please be clear.
If I can use .NET I guess I can use WPF too right?
| You can technically write a GUI in C++/CLI, but I would highly discourage it. C++/CLI is good for writing .NET wrappers around native C++ and exposing it to other .NET languages, but not much else.
In your case, if you're really set on using WinForms/WPF, then I would suggest using C++/CLI to create a wrapper around yo... |
2,778,889 | 2,778,951 | Difference in behaviour (GCC and Visual C++) | Consider the following code.
#include <stdio.h>
#include <vector>
#include <iostream>
struct XYZ { int X,Y,Z; };
std::vector<XYZ> A;
int rec(int idx)
{
int i = A.size();
A.push_back(XYZ());
if (idx >= 5)
return i;
A[i].X = rec(idx+1);
return i;
}
int main(){
A.clear();
rec(0);
puts("FINI... | The recursive call to rec() might modify the vector while you're assigning a value to it.
What happens if you replace
A[i].X = rec(idx+1);
with
int tmp = rec(idx+1);
A[i].X = tmp;
?
Also, just to summarize the useful comments: the operand evaluation order of a = operation is unspecified and since the vector wasn't pr... |
2,779,155 | 2,779,191 | template; Point<2, double>; Point<3, double> | I want to create my own Point struct it is only for purposes of learning C++.
I have the following code:
template <int dims, typename T>
struct Point {
T X[dims];
Point(){}
Point( T X0, T X1 ) {
X[0] = X0;
X[1] = X1;
}
Point( T X0, T X1, T X2 ) {
X[0] = X0;
X[1] = X... | Your dimensions are fixed at compile time, by the template arguemnt dims, so you can iterate over them:
std::string str(){
//how to distinguish between 2D and 3D ???
std::stringstream s;
s << "{ ";
std::copy( X, X+dims, std::ostream_iterator<T>( s, "|") );
s << " }";
return s.str();
}
Also,... |
2,779,294 | 2,785,413 | Scaling a CBitmap - what am I doing wrong? | I've written the following code, which attempts to take a 32x32 bitmap (loaded through MFC's Resource system) and turn it into a 16x16 bitmap, so they can be used as the big and small CImageLists for a CListCtrl. However, when I open the CListCtrl, all the icons are black (in both small and large view). Before I starte... | Make sure you deselect the CBitmaps after using them:
// Select the objects
CBitmap* ret1 = bigDC.SelectObject(bmpBig);
CBitmap* ret2 = smallDC.SelectObject(bmpSmall);
...
// Do the painting
...
// Deselect
bigDC.SelectObject(ret1);
smallDC.SelectObject(ret2);
|
2,779,316 | 2,779,452 | behaviour of the implicit copy constructor / assignment operator | I have a question regarding the C++ Standard.
Suppose you have a base class with user defined copy constructor and assignment operator. The derived class uses the implicit one generated by the compiler.
Does copying / assignment of the derived class call the user defined copy constructor / assignment operator? Or do yo... | If a derived class does not declare a copy constructor, and implicit one will be declared (12.8/4 "Copying class objects") - even if the base class has a user-delcared and defined copy constructor. If the base class has a user-defined copy constructor in this case, that base class sub-object is copied using that user... |
2,779,345 | 2,779,363 | C++ stack in Objective-C++ | I'd like to use a C++ stack type in Objective-C, but I'm running into some issues. Here's a sample of what I would like to do:
#import <stack>
#import <UIKit/UIKit.h>
@interface A : NSObject {
stack<SEL> selectorStack;
}
@end
Unfortunately, this doesn't compile. After messing around with the code for a while a... | Have you tried
@interface A : NSObject {
std::stack<SEL> selectorStack;
}
|
2,779,469 | 5,054,690 | Can I use dtsearch in C++ under linux, if yes what APIshould i use? | I want to use dtsearch in my desktop application written in C++ and Gtkmm. Can i have any API or link to the API to do my thing.
| If you are talking about dtSearch Desktop, the Windows end-user product, it is not intended or licensed to be used via the API.
The dtSearch Engine for Linux (x32 or x64) on the other hand is a developer product and has C++ and Java APIs; it includes file filters for all popular file types, can search multiple indexes ... |
2,779,543 | 2,797,924 | How to create GIF file from other format file in C++ | I want to create 2 bits per pixel GIF files in VC environment from a TIFF file.
Is there any free library or maybe source that could help me?
Or how can I do it myself?
| You can use either OpenIL ( http://openil.sourceforge.net/ ), which is a C library, or if you really want a C++ only solution, Magick++ ( http://www.imagemagick.org/www/Magick++/ )
|
2,779,570 | 2,780,482 | How did it happen that "static" denotes a function/variable without external linkage in C and C++? | In C static can mean either a local variable or a global function/variable without external linkage. In C++ it can also mean a per-class member variable or member function.
Is there any reference to how it happened that the static keyword that seems totally irrelevant to lack of external linkage is used to denote lack ... | static is a storage specifier. The word "static" means unchanging. "Storage" refers to where the object is in memory, i.e. its address.
An object with static storage resides at a constant address.
It just so happens that an object with extern storage also has a constant address. Due to the way C and C++ programs are li... |
2,779,804 | 2,779,866 | Input accepting char when it should be string? | I am new to C++ and am making a simple text RPG, anyway, The scenario is I have a "welcome" screen with choices 1-3, and have a simple IF statement to check them, here:
int choice;
std::cout << "--> ";
std::cin >> choice;
if(choice == 1) {
//..
That works fine, but if someone enters a letter as selection (instead of... | Unfortunately 1 and '1' are not the same.
Look up your favorite ASCII table to know the integer value that represents the character "1" and you'll see it for yourself: '1' is mapped to 49.
There is another issue with this code "" denotes a C-string (const char*) whereas '' denotes a single character.
Here is your code ... |
2,779,901 | 2,783,661 | Asynchronous event loop design and issues | I'm designing event loop for asynchronous socket IO using epoll/devpoll/kqueue/poll/select (including windows-select).
I have two options of performing, IO operation:
Non-blocking mode, poll on EAGAIN
Set socket to non-blocking mode.
Read/Write to socket.
If operation succeeds, post completion notification to event lo... | I'm not sure there's any cross-platform problem; at the most you would have to use Windows Sockets API, but with the same results.
Otherwise, you seem to be polling in either case (avoiding blocking waits), so both approaches are fine. As long as you don't put yourself in a position to block (ex. read when there's no d... |
2,780,301 | 2,780,456 | Why would you use umask? | I am reading some source code and I found this statement at the very beginning of the main routine:
umask(077);
What could be the reason for that?
The man page (man 2 umask) states:
umask -- set file creation mode mask
This clearing allows each user to
restrict the default access to his
files
But is not clear to me ... | Setting umask(077) ensures that any files created by the program will only be accessible to their owner (0 in first position = all permissions potentially available) and nobody else (7 in second/third position = all permissions disallowed to group/other).
|
2,780,302 | 2,787,195 | Deny access to run certain installed software for users | I have a list of installed software, obtained from WMI class select * from Win32_Product.
I'd like to deny execution rights for some users on certain software like so:
find the path to installed software
recursively remove execution rights
I find the path to installed software from Win32_Product InstallLocation colum... | In general, no. The extreme edge case is a Firefox installation on an USB disk. It will leave no trace in the registry or Win32_Product InstallLocation.
The root cause is that Win32_Product InstallLocation has no location when the path is not in the registry. They're essentially 2 views on the same data.
There's also t... |
2,780,304 | 2,780,641 | How to Track Emitted Signals in QT? | Is there any way to observe all signals which are emitted?
PS. Of course we can write slots for all signals, but that is not I want.
| What do you mean by observing? Do you need real time feedback on console, or is logging to file on program exit enough?
If you need real time feedback on console, you can check then implementation of QTest. There is a -vs command line switch (Qt doc) which enables all signals printout on console (or you can just run yo... |
2,780,314 | 2,780,362 | Why are gettimeofday() intervals occasionally negative? | I have an experimental library whose performance I'm trying to measure. To do this, I've written the following:
struct timeval begin;
gettimeofday(&begin, NULL);
{
// Experiment!
}
struct timeval end;
gettimeofday(&end, NULL);
// Print the time it took!
std::cout << "Time: " << 100000 * (end.tv_sec - begin.tv_sec)... | You've got a typo. Corrected last line (note the number of 0s):
std::cout << "Time: " << 1000000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl;
BTW, timersub is a built in method to get the difference between two timevals.
|
2,780,365 | 2,780,397 | Using read() directly into a C++ std:vector | I'm wrapping up user space linux socket functionality in some C++ for an embedded system (yes, this is probably reinventing the wheel again).
I want to offer a read and write implementation using a vector.
Doing the write is pretty easy, I can just pass &myvec[0] and avoid unnecessary copying. I'd like to do the same a... | Use resize() instead of reserve(). This will set the vector's size correctly -- and after that, &myvec[0] is, as usual, guaranteed to point to a continguous block of memory.
Edit: Using &myvec[0] as a pointer to the underlying array for both reading and writing is safe and guaranteed to work by the C++ standard. Here's... |
2,780,612 | 2,781,565 | Outlook Add-in. How to manage Items Events | I'm doing an add-in for Outlook 2007 in C++.
I need to capture the events like create, change or delete from the Outlook Items (Contact, Appointment, Tasks and Notes) but the only information/examples I've found are for Visual Basic so I don't know how to connect the event handler.
Here is some information related: htt... | Its been a while, but you should get these item events by advising for Folder.Items:
CComPtr<Outlook::MAPIFolder> folder;
// get the folder you're interested in
CComPtr<Outlook::_Items> items;
hr = folder->get_Items(&items);
hr = MyItemEvents::DispEventAdvise(items, &__uuidof(Outlook::ItemsEvents));
Where your class M... |
2,780,868 | 2,781,520 | How to hook for particular windows message without subclassing? | Is there a way to hook for a particular windows message without subclassing the window.
There is WH_GETMESSAGE but that seems create performance issues.
Any other solutions apart from these which doesn't deteriorate performance?
| AFAIK there's no better solution than what you mentioned. And, of course, subclassing the window is better than hooking all the messages of the thread.
Let's think which path the message passes up until it's handled by the window:
The message is either posted or sent to the window, either by explicit call to PostMessa... |
2,781,015 | 2,781,088 | value of enum members, when some members have user-defined values | enum ABC{
A,
B,
C=5,
D,
E
};
Are D and E guaranteed to be greater than 5 ?
Are A and B guaranteed to be smaller than 5 (if possible)?
edit: What would happen if i say C=1
| It is guaranteed by C++ Standard 7.2/1:
The identifiers in an enumerator-list are declared as constants, and can appear wherever constants are
required. An enumerator-definition with = gives the associated enumerator the value indicated by the
constant-expression. The constant-expression shall be of integral or en... |
2,781,089 | 2,781,149 | Is there a convention for organizing the include/exports in a large C++ project? | In a large C++ solution, is there a best/standard way to separate the include files necessary to build an intermediary DLL and the include files which will be used by the DLL clients ?
We have grouped all the include files in a folder called Interface (for DLL interface), but there the customers have to either include ... | If an interface could consist of more than one header,
#include "ProjectName/Interface/header1.h"
seems better to me.
|
2,781,323 | 2,781,338 | Factory Method and Cyclic Dependency | Edit: Thanks folks, now I see my mistake.
If I'm not wrong, because of its nature in factory method there is cyclic dependency:
Base class needs to know subclasses because it creates them, and subclasses need to know base class. Having cyclic dependency is bad programming practice, is not it?
Practically I implemented ... | Solution 1: don't #include the derived class headers in the base class header, only in the base class cpp. The declaration of the factory method should not use the type of concrete classes returned, only the base type.
Solution 2: use a separate factory class (or a factory method within a separate class) to create your... |
2,781,339 | 2,781,537 | Global qualification in a class declarations class-head | We found something similar to the following (don't ask ...):
namespace N {
struct A { struct B; };
}
struct A { struct B; };
using namespace N;
struct ::A::B {}; // <- point of interest
Interestingly, this compiles fine with VS2005, icc 11.1 and Comeau (online), but fails with GCC:
global qualification of clas... | I think you are getting it right: GCC implements the standard to the letter in this case, while the others implement it less strict (have a look at issue #355).
You could do the following to work-around the limitation of the syntax
struct identity< ::A >::type::B {};
Or you use an explicit named typedef
typedef ::A... |
2,781,425 | 2,781,912 | what is required to get intellisense for Gtkmm using editor Geany! | i want to get the intellisense in GTkmm application, similarly as we get in dot net under windows. However this time i am using Linux, C++, Gtkmm and Geany as my editor. Please guide how to get the intellisense. Moreover, if any kind of editor supports the property of intellisense, please mention that also.
Thanks and ... | Geany automatically indexes your open files for auto-completion, but if you want it to index some library or API, you have to create a global tags file like it describes here in the documentation. I have had mixed results getting this to work completely and correctly though.
I used to use Geany on Linux, but I have mo... |
2,781,486 | 2,781,805 | C++ calculation evaluated to 0 | I'm parsing a file and trying to decode coordinates to the right unit.
What happens is that this code is evaluated to 0. If I type it into gdb the result is correct.
int pLat = (int)(
(argv[6].data() == "plus" ? 1 : -1)
* ( atoi(argv[7].data())
+ atoi(argv[8].data()) / 60.
... | Assuming you're trying to convert degrees to WGS84 coordinates, there are two errors:
The conversion factor is out by a factor of 10 (180/223 is approximately 2.145767*10-5, and you have 2.145767*10-4)
You are multiplying by the conversion factor when you should be dividing by it. This will give you a very small numbe... |
2,781,798 | 2,781,846 | const TypedeffedIntPointer not equal to const int * | I have the following C++ code:
typedef int* IntPtr;
const int* cip = new int;
const IntPtr ctip4 = cip;
I compile this with Visual Studio 2008 and get the following error:
error C2440: 'initializing' : cannot convert from 'const int *' to 'const IntPtr'
Clearly my understanding of typedefs is not what is should be.
... | When you write const IntPtr ctip4, you are declaring a const-pointer-to-int, whereas const int * cip declares a pointer-to-const-int. These are not the same, hence the conversion is impossible.
You need to change the declaration/initialization of cip to
int * const cip = new int;
To resolve this issue in your example,... |
2,781,863 | 2,781,940 | C++ Pass a hidden arg to a class constructor? | I would like to define a class that accept the pointer to it's parent class as an Argument, but would it be possible to somehow pass it without needing to pass it directly such as:
class Child
{
public:
Child(Parent* hiddenArg);
};
class Parent
{
public:
Child myChild;
};
I know this is weird, but I am making m... | You can't do it automatically, but all you need to do is construct myChild in the Parent constructor like this:
Parent::Parent()
: myChild(this) // passing pointer to parent to child constructor
{
}
Note some compilers will emit a warning for that code: it thinks you're using the this pointer before the Parent cla... |
2,781,899 | 2,781,916 | How to find whether an element exists in std::map? | My use case:
map<string, Car> cars;
bool exists(const string& name) {
// somehow I should find whether my MAP has a car
// with the name provided
return false;
}
Could you please suggest the best and the most elegant way to do it in C++? Thanks.
| Sure, use an iterator
map<string,Car>::const_iterator it = cars.find(name);
return it!=cars.end();
|
2,782,092 | 2,782,127 | Casting a container of shared_ptr | I have a method
void foo(list<shared_ptr<Base>>& myList);
Which I'm trying to call with a two different types of lists, one of DerivedClass1 and one of DerivedClass2
list<shared_ptr<DerivedClass1>> myList1;
foo(myList1);
list<shared_ptr<DerivedClass2>> myList2;
foo(myList2);
However this obviously generates a comp... | You can't cast a container of one type to a container of another type. There are a few ways to create a new container from an existing container, if the type of object stored by the existing container is convertible to the type of object stored by the new container:
You can use std::copy to do the conversion element-b... |
2,782,311 | 2,782,634 | WM_NCHITTEST and secondary monitor to left of primary monitor | The described setup with 2nd monitor to left of primary causes WM_NCHITTEST to send negative values which is apparently not supported according to this post.
I have a custom control written in win32 that is like a Group control. It has a small clickable area. No MOUSE events are coming to my control when the window c... | You must use GET_X_LPARAM and GET_Y_LPARAM macros to extract mouse coordinates. They will correctly return negative values, unlike LOWORD et al. which return unsigned values.
POINT Pt = { GET_X_LPARAM(lP), GET_Y_LPARAM(lP) };
The rest of the code should be fine.
|
2,782,343 | 2,782,375 | Customers angry, fighting unknown DLL dependencies | I'm a one man show developing a C++ Windows application for a customer. Over the past several months we've been running to the same problems with missing DLL dependencies on customer machines. Despite my best efforts something keeps going wrong and we get angry emails back. My boss and my boss's boss are angry with ... | If you don't have a test machine, can you at least use a virtual machine with a clean Windows installation?
|
2,782,677 | 2,782,694 | Unit testing a functions whose purposes is side effects | How would you unit test do_int_to_string_conversion?
#include <string>
#include <iostream>
void do_int_to_string_conversion(int i, std::string& s) {
switch(i) {
case 1:
s="1";
break;
case 2:
s="2";
break;
default:
s ="Nix";
}
}
int main(int argc, char** argv... | I assume this is just an example. Why can't you assert on the value of little_s after each call?
do_int_to_string_conversion(1, little_s);
assert_are_equal("1", little_s);
|
2,782,725 | 2,782,742 | Converting float values from big endian to little endian | Is it possible to convert floats from big to little endian? I have a big endian value from a PowerPC platform that I am sendING via TCP to a Windows process (little endian). This value is a float, but when I memcpy the value into a Win32 float type and then call _byteswap_ulongon that value, I always get 0.0000?
What... | simply reverse the four bytes works
float ReverseFloat( const float inFloat )
{
float retVal;
char *floatToConvert = ( char* ) & inFloat;
char *returnFloat = ( char* ) & retVal;
// swap the bytes into a temporary buffer
returnFloat[0] = floatToConvert[3];
returnFloat[1] = floatToConvert[2];
return... |
2,782,915 | 2,782,968 | What should I know about Structured Exceptions (SEH) in C++? | What important points about Structured Exceptions should every C++ developer know?
| They are the Win32 equivalent to Unix signals, and let you catch CPU exceptions such as access violation, illegal instruction, divide by zero.
With the right compiler options (/EHa for Visual C++), C++ exceptions use the same mechanism as stack unwinding works properly for both C++ (user) exceptions and SEH (OS) except... |
2,783,239 | 2,783,258 | Increment and Decrement operators | How are the below valid and invalid as shown and what do they mean. When would such a situation arise to write this piece of code.
++x = 5; // legal
--x = 5; // legal
x++ = 5; // illegal
x-- = 5; // illegal
| The postfix (x++/x--) operators do not return an lvalue (a value you can assign into).
They return a temporary value which is a copy of the value of the variable before the change
The value is an rvalue, so you could write:
y = x++ and get the old value of x
|
2,783,269 | 2,783,978 | QSqlQuery UPDATE/INSERT DateTime with server's time (eg CURRENT_TIMESTAMP) | I am using QSqlQuery to insert data into a MySQL database. Currently all I care about is getting this to work with MySQL, but ideally I'd like to keep this as platform-independent as possible.
What I'm after, in the context of MySQL, is to end up with code that effectively executes something like the following query:
... | I have no SQL server to test here, but addBindValue() binds Qt's data types. You should put the timestamp function direct into the query
QSqlQuery query;
query.prepare("INSERT INTO table SET time_field=CURRENT_TIMESTAMP() WHERE id=?");
query.addBindValue(5);
query.exec();
should do the trick.
|
2,783,603 | 2,783,626 | QT Creator simple application | I'm developping a very simple app on my Ubuntu using QtCreator.
It's a console application and I want the user to enter its name, and then I display his name. Here is the code :
#include <iostream>
int main(int ArgC, char* ArgV[])
{
char Name[1000];
std::cout << "Type your name : ";
std::cin >> Name;
... | Looks like "Application Output" tab doesn't support Input. Try to start your application in standalone console.
|
2,783,612 | 2,783,652 | Listing C/C++ functions (Code analysis in Unix) | Whether we're maintaining unfamiliar code or checking out the implementation details of an Apache module it can help if we can quickly traverse the code and build up an overview of what we're looking at. Grep serves most of my daily needs but there are some cases where it just wont do.
Here's a common example of how it... | Run it through doxygen. It will complain about lack of commenting , but it will still produce call graphs and list all the functions. Presented in HTML with links to follow code paths.
doxygen
|
2,783,786 | 2,783,833 | C++: Everytime I read in by fstream I got 1 extra character at the end | Everytime I read in by fstream I got 1 extra character at the end, How can I avoid this?
EDIT:
ifstream readfile(inputFile);
ofstream writefile(outputFile);
char c;
while(!readfile.eof()){
readfile >> c;
//c = shiftChar(c, RIGHT, shift);
writefile << c;
}
readfile.close();
writefile.close();
| This typically results from testing for the end of file incorrectly. You normally want to do something like:
while (infile>>variable) ...
or:
while (std::getline(infile, whatever)) ...
but NOT:
while (infile.good()) ...
or:
while (!infile.eof()) ...
The first two do a read, check whether it failed, and if so exit t... |
2,783,814 | 2,784,176 | C++ string sort like a human being? | I would like to sort alphanumeric strings the way a human being would sort them. I.e., "A2" comes before "A10", and "a" certainly comes before "Z"! Is there any way to do with without writing a mini-parser? Ideally it would also put "A1B1" before "A1B10". I see the question "Natural (human alpha-numeric) sort in Micros... | Is there any way to do with without writing a mini-parser?
Let someone else do that?
I'm using this implementation: http://www.davekoelle.com/alphanum.html, I've modified it to support wchar_t, too.
|
2,784,262 | 2,784,304 | Does a const reference class member prolong the life of a temporary? | Why does this:
#include <string>
#include <iostream>
using namespace std;
class Sandbox
{
public:
Sandbox(const string& n) : member(n) {}
const string& member;
};
int main()
{
Sandbox sandbox(string("four"));
cout << "The answer is: " << sandbox.member << endl;
return 0;
}
Give output of:
The an... | Only local const references prolong the lifespan.
The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of reference declarations. The reference in your example is bound to the constructor's argument n, and becomes invalid when the object n is bound to goes out of scope.
The life... |
2,784,264 | 2,784,445 | LocalAlloc and LocalRealloc usage | I have a Visual Studio 2008 C++ Windows Mobile 6 application where I'm using a FindFirst() / FindNext() style API to get a collection of items. I do not know how many items will be in the list ahead of time. So, I would like to dynamically allocate an array for these items.
Normally, I would use a std::vector<>, but, ... | From what I can tell, LHND is not even a valid flag to use in the Windows Mobile version of LocalAlloc.
When you call the non-mobile version of LocalAlloc with LMEM_MOVEABLE, the return type is not INFO_STRUCT*. The return type is HLOCAL — a handle to the memory that you've allocated. It's not a pointer itself, so it i... |
2,784,523 | 2,789,308 | Is it possible to duplicate a GDI handle? | Or in my particular case a windows region (HRGN)?
Updated:
The problems is the following:
I've a collection of objects, each of these objects can hold a HRGN. These region once acquired is released when the object is destroyed. Since some of those objects are stored in a std::vector I've to define an assignement operat... | Wrap each HRGN in a reference-counting object modeled after any smart pointer e.g. shared_ptr.
|
2,784,603 | 2,784,666 | C++ fstream variable | please, what contains the fstream variable? A can find many tutorials on fstream, but no ona actually says what is the fstream file; declaration in the beginning. Thanks.
| The fstream class is an object that handles file input and output. It is mostly equivalent to both an ifstream and ostream object in one, in that you can use it for both input and output. This tiny demonstration will create a file and write data to it.
#include <fstream>
using namespace std;
int main()
{
fstream myFil... |
2,784,639 | 2,802,602 | Boost timed_wait leap seconds problem | I am using the timed_wait from boost C++ library and I am getting a problem with leap seconds.
Here is a quick test:
#include <boost/thread.hpp>
#include <stdio.h>
#include <boost/date_time/posix_time/posix_time.hpp>
int main(){
// Determine the absolute time for this timer.
boost::system_time tAbsolut... | Ok, here is what I did. It's a workaround and I am not happy with it but it was the best I could come up with:
int main(){
typedef boost::date_time::c_local_adjustor<boost::system_time> local_adj;
// Determine the absolute time for this timer.
boost::system_time tAbsoluteTime = boost::get_syste... |
2,784,742 | 2,787,632 | What are the lengths/limits C preprocessor as a language creation tool? Where can I learn more about these? | In his FAQ, Bjarne Stroustrup says:
To build [Cfront, the first C++
compiler], I first used C to write a
"C with Classes"-to-C preprocessor. "C
with Classes" was a C dialect that
became the immediate ancestor to C++...
I then wrote the first version of
Cfront in "C with Classes".
When I read this, it piq... | For an example of the kind of monstrosity of a "language" you can create using the C preprocessor, have a look at this header file:
http://minnie.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh/mac.h
It's from the source code of the original Unix shell written by Steve Bourne and it aims to turn C into an Algol like l... |
2,784,811 | 2,784,817 | How does the compiler know to call function once per static variable? | E.g
foo1() {
static const char* str = foo2();
}
const char * foo2 () {
...
}
How does the compiler makes sure it calls foo2 just once.
| foo2 is called at the initialisation of your program, just before main().
Edit: this is wrong! I assumed this as this is how normally static initialisation works. But in this case, they are called once at the start of the function.
It must work with some kind of static boolean. Yep. At least in gcc, this:
int test2()
{... |
2,785,183 | 2,788,079 | best alternative to in-definition initialization of static class members? (for SVN keywords) | I'm storing expanded SVN keyword literals for .cpp files in 'static char const *const' class members and want to store the .h descriptions as similarly as possible. In short, I need to guarantee single instantiation of a static member (presumably in a .cpp file) to an auto-generated non-integer literal living in a pot... | probably, with a static function?
// Foo.h:
class Foo {
static Logger const verLog;
static char const*const getHInfo() { return "$Id$"; }
public:
static char const *const cInfo;
};
// Foo.cpp: static inits called here
char const *const Foo::cInfo = "$Id$";
Logger const Foo::verLog(Foo::cInfo, ... |
2,785,206 | 2,785,468 | The pImpl idiom and Testability | The pImpl idiom in c++ aims to hide the implementation details (=private members) of a class from the users of that class.
However it also hides some of the dependencies of that class which is usually regarded bad from a testing point of view.
For example if class A hides its implementation details in Class AImpl which... | The idea behind pimpl is to not so much to hide implementation details from classes, (private members already do that) but to move implementation details out of the header. The problem is that in C++'s model of includes, changing the private methods/variables will force any file including this file to be recompiled. Th... |
2,785,257 | 2,785,393 | OpenGL antialiasing not working | I'v been trying to anti alias with OGL. I found a code chunk that is supposed to do this but I see no antialiasing. I also reset my settings in Nvidia Control Panel but no luck.
Does this code in fact antialias the cube?
GLboolean polySmooth = GL_TRUE;
static void init(void)
{
glCullFace (GL_BACK);
glEnable (GL_C... | Have you tried to supply GLUT_MULTISAMPLE to the glutInitDisplayMode(..) call? It's not sure your glut implementation supports it though.
|
2,785,306 | 2,785,316 | Calculating volume for sphere in C++ | This is probably an easy one, but is the right way to calculate volume for a sphere in C++? My getArea() seems to be right, but when I call getVolume() it doesn't output the right amount. With a sphere of radius = 1, it gives me the answer of pi, which is incorrect:
double Sphere::getArea() const
{
return 4 * Sha... | You're using integer division in (4 / 3). Instead, use floating point division: (4.0 / 3.0).
4/3 is 1, because integer division only produces integers. You can confirm this by test code: std::cout << (4/3) << std::endl;.
|
2,785,309 | 2,785,331 | Accessing derived class members with a base class pointer | I am making a simple console game in C++
I would like to know if I can access members from the 'entPlayer' class while using a pointer that is pointing to the base class ( 'Entity' ):
class Entity {
public:
void setId(int id) { Id = id; }
int getId() { return Id; }
protected:
int Id;
};
class entPlayer : p... | It is possible by using a cast. If you know for a fact that the base class pointer points to an object of the derived class, you can use static_cast:
Entity* e = /* a pointer to an entPlayer object */;
entPlayer* p = static_cast<entPlayer*>(e);
p->setName("Test");
If you don't know for sure, then you need to use dyna... |
2,785,434 | 2,786,158 | How to interact with checkbox actions ? (QTableView with QStandardItemModel) | I'm using QTableView and QStandardItemModel to show some data.
For each row, there is a column which has a check Box, this check box is inserted by setItem, the code is as follows:
int rowNum;
QStandardItemModel *tableModel;
QStandardItem* __tmpItem = new QStandardItem();
__tmpItem->setCheckable(true);
__tmpItem->se... | handle the click event, there you will get the modelindex, get the data and modify the same
if you are going to insert more than one text or icon, then you need to set the delegate for your listview
|
2,785,449 | 2,785,470 | find window text and save txt to file named that wont work | my code wont work and idk why. the point of my code is to find the top window and save a text file with the name the same as the text on the top menu bar (task bar i think?). then save some data to that text file. but everytime i try to use it the write fails if i set the name of the text file before hand so it wont ch... | You are not sanitizing the name of your text file. There are quite a few illegal file names. Primarily, characters such as ":", "/" and "\" are not allowed in a filename.
|
2,785,601 | 2,785,605 | C++ Numerical truncation error | sorry if dumb but could not find an answer.
#include <iostream>
using namespace std;
int main()
{
double a(0);
double b(0.001);
cout << a - 0.0 << endl;
for (;a<1.0;a+=b);
cout << a - 1.0 << endl;
for (;a<10.0;a+=b);
cout << a - 10.0 << endl;
cout << a - 10.0-b << endl;
return 0;
}
Output:
0
6.66134e-16
0.001
-1.035... | Yes, this is normal numeric representation floating point error. It has to do with the fact that the hardware must approximate most floating point numbers, rather than storing them exactly. Thus, the compiler you use should not matter.
What Every Computer Scientist Should Know About Floating-Point Arithmetic
|
2,785,612 | 2,785,639 | C++, What does the colon after a constructor mean? |
Possible Duplicates:
Variables After the Colon in a Constructor
C++ constructor syntax question (noob)
I have some C++ code here:
class demo
{
private:
unsigned char len, *dat;
public:
demo(unsigned char le = 5, unsigned char default) : len(le)
{
dat = new char[len]; ... | As others have said, it's an initialisation list. You can use it for two things:
Calling base class constructors
Initialising member variables before the body of the constructor executes.
For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling ... |
2,785,901 | 2,789,577 | "Debug Assertion" Runtime Error on VS2008? | I'm writing a C++ MFC program on VS2008 and I'm getting this "Debug Assertion Error" when I first run the program sometimes. When I try to debug it, it takes me to this winhand.cpp file which is not part of the program I wrote so I'm not sure how to debug this.
It takes the error to this place in winhand.cpp
CObject* ... | The code that is asserting is part of MFC's CHandleMap class. MFC deals with windows as CWnd objects, but Windows deals with them as HWND handles. the handle map allows MFC to 'convert' an HWND into a pointer to the MFC object representing that object.
What the assertion seems to be doing is checking that when a look... |
2,785,969 | 2,785,988 | Template Sort In C++ | Hey all, I'm trying to write a sort function but am having trouble figuring out how to initialize a value, and making this function work as a generic template. The sort works by:
Find a pair =(ii,jj)= with a minimum value = ii+jj = such at A[ii]>A[jj]
If such a pair exists, then
swap A[ii] and A[jj] ... | most likely reason it fails, is because char = 453 does not produce 453 but rather different number, depending what char is (signed versus unsigned). your immediate solution would be to use numerical_limits, http://www.cplusplus.com/reference/std/limits/numeric_limits/
you may also need to think about design, because... |
2,786,245 | 3,185,308 | OCCI createEnvironment Blocks My Thread | I'm writing a multi-threaded application, where there is a main thread which distributes tasks to the worker threads. According to the task, a worker thread creates a connection, by using a global occi environment. When a worker thread completes its task, it closes the connection (I'm sure, there is no exception thrown... | I guess I didn't identify the problem correctly. I thought the threads get blocked, but actually they didn't, they simply exited there unexpectedly :). Problem solved.
|
2,786,286 | 2,786,307 | Advanced switch statement within while loop? | I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But..
Lets say I have the following scenario (theorietical co... | You could simply have the while loop check for a bool value that is set within one of your case statements.
bool done = false;
while(!done)
{
char something;
std::cout << "Enter something\n -->";
std::cin >> something;
//Switch to read "something"
switch(something) {
case 'a':
cout << "You ente... |
2,786,417 | 2,786,432 | Matrix Comparison algorithm | If you have 2 Matrices of dimensions N*M.
what is the best way to get the difference Rect?
Example:
2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3
2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3
2 3 4 5 4 3 2 3 <---> 2 3 2 3 2 3 2 3
2 3 4 5 2 3 2 3 2 3 2 3 2 3 2 3
2 3 2 3 ... | No, there isn't a more efficient algorithm. For identical matrixes, you must scan all elements, so the algorithm is necessarily O(n*m).
|
2,786,485 | 2,786,747 | Question regarding C++ Lists | list dog;
.............
............
So I added many dog objects to it.
If I call dog.pop_front();
Does memory automatically gets deallocated ? For the object that I popped out ?
So If I call
list<Dog*> dog2;
dog2.push_back(dog.front());
and then I will call dog.pop_front() So this will work? I will a... | You keep asking about this sequence:
list<Dog*> dog2;
dog2.push_back(dog.front()); // time 1
dog.pop_front(); // time 2
At time1, both dog2 and dog have a pointer to the same object.
At time2, the pointer to that object is removed from dog and is only in dog2.
Assuming you originally created that object ... |
2,786,581 | 2,786,618 | migrating C++ code from structures to classes | I am migrating some C++ code from structures to classes.
I was using structures mainly for bit-field optimizations which I do not need any more (I am more worried about speed than saving space now).
What are the general guidelines for doing this migration? I am still in the planning stage as this is a very big move af... | I can't name all the essential things, but I can name one: encapsulation.
The only technical difference in C++ between struct and class is the default access. In a struct, everything is public by default; in a class, everything is private. I'm assuming that you're talking about POD structs here, where everything is pub... |
2,786,785 | 2,786,825 | Why does gprof tell me that a function that is called only once from main() is called 102 times? | I am a beginner, and wrote the following program for fun, to search through a directory and replace every occurrence of one word with another. I call the crt_ls_file() function once, and once only, but gprof tells me it is being called 102 times. I am wondering if anyone knows why this is. I have tried compiling the pr... | On my system gprof shows only one call to crt_ls_file as it should be:
0.00 0.00 0.00 1 0.00 0.00 crt_ls_file(std::string const&, std::string const&)
So it seems you gprof is lying, which it sometimes does. If you really want to profile this program (there's little use), try callgrind and kc... |
2,786,816 | 2,786,872 | How to create C++ istringstream from a char array with null(0) characters? | I have a char array which contains null characters at random locations. I tried to create an iStringStream using this array (encodedData_arr) as below,
I use this iStringStream to insert binary data(imagedata of Iplimage) to a MySQL database blob field(using MySQL Connector/C++'s setBlob(istream *is) ) it only stores ... | There is nothing special about null characters in strings
std::istringstream iss(std::string(data, N));
setBlob(&iss);
Of course if you do
std::istringstream iss("haha a null: \0");
It will interpret that as a C-style string converted to std::string, and thus will stop at the \0, not taking it as a real content byte.... |
2,786,895 | 4,416,296 | C++: why a self pointer of a struct automatically changes to void* | struct ptr{
int node;
ptr *next;
ptr(){}
ptr(int _node, ptr *_next){ node=_node; next=_next; }
};
struct list_t{
ptr *sht;
int size;
void push(int node){
size++;
sht=new ptr(node,sht);
}
}shthead[100001], comp[200001], tree[200001];
The struct ptr is used as a linked lis... | Maybe this: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45088
I need to thank Tom Tromey for telling me this.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.