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 |
|---|---|---|---|---|
5,809,340 | 5,819,041 | Glade C++ app, GUI design not the same at Runtime | Im very new to gui programming in linux and Im stumbling at the 1st hurdle, Im using glade to design a form (i come from windows background) it looks completly different in Glade than it does when I run the compiled program.
heres a screen grab of them
see link as they wont let me post images
heres the c++
#include <g... | You have nothing in the empty spaces in your HBox and VBox. If there are no other widgets taking up the space, then your button will expand to fill all available space. Put some other widgets in your window if you don't want the button to fill it. Sizing and placement work differently in GTK than they do in other toolk... |
5,809,476 | 5,809,578 | POSIX Program to search entire file system for a file | Hey everyone. I need to write a POSIX program to search through an entire file system for a specified file starting at the top directory. I've got some code which isn't done at all, but when I run it, and check to see if a particular file is a directory, it's saying this file which is not at all a directory is a direct... | ->d_name returns just the name of the file, not the path to the file. You need to stat (not yet constructed) new_Directory instead of dptr->d_name.
You also have a problem if a directory contains more than one subdirectories. Your construction of new_Directory is incorrect for each subdirectory after the first.
You nev... |
5,809,912 | 8,159,865 | MFC: Creating modeless dialog box without displaying | I'm trying to create a simple modeless dialog box which I'm creating from my CWinApp derived InitInstance() function.
BOOL CMyApp::InitInstance()
{
...
m_pMyDialog = new CMyDialog();
m_pMyDialog->Create(CMyDialog::IDD);
...
retrun TRUE;
}
I've created the dialog template in the resource editor and ... | The problem was with AnimateWindow() which was causing the dialog to display prematurely.
|
5,810,123 | 5,828,896 | OpenGL Multitexturing - glActiveTexture is NULL | I have started a new project, which I want to use multitexturing in.
I have done multixexturing before, and is supported by my version of OpenGL
In the header I have:
GLuint m_TerrainTexture[3];//heightmap, texture map and detail map
GLuint m_SkyboxTexture[5]; //left, front, right, back and top textures
PFNGLMULTITE... | You quoted your code to load the extensions like following:
PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB;
PFNGLACTIVETEXTUREARBPROC glActiveTexture;
glActiveTexture = (PFNGLACTIVETEXTUREARBPROC) wglGetProcAddress((LPCSTR)"glActiveTextureARB");
glMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC) wglGetProcAddres... |
5,810,152 | 5,810,504 | Why won't this code compile and run in Visual Studio 2010? | I am trying to get Visual Studio 2010 set up to do plain old ANSI compilation, without Microsoft extensions of any kind.
I started with an empty project template, since there doesn't seem to be a plain ANSI project template in 2010 anymore.
Then I set
Properties -> Configuration Properties -> C/C++ -> Language -> Dis... | The error disappears if you define wchar_t as native type.
|
5,810,153 | 5,810,301 | Get Process Information | Im using C++ and im trying to create a program similar to handle.exe from sysinternals.
Basically, i am getting the filename from the user, and I need to be able to display which process is locking the file.
Does anyone know where I can get this information from? I've tried using some process functions in winapi, but I... | There is an undocumented option on NtQuerySystemInformation to get the file handles for a process. There is sample code here.
Second sample (in Delphi) is here.
|
5,810,190 | 5,811,888 | How to tell a std::priority_queue to refresh its ordering? | I have a priority queue of pointers to a struct city. I modify the objects pointed by these pointers outside the priority queue, and want to tell the priority queue to "reorder" itself according to the new values.
What should I do?
Example:
#include <iostream>
#include <queue>
using namespace std;
struct city {
i... | This is a bit hackish, but nothing illegal about it, and it gets the job done.
std::make_heap(const_cast<city**>(&cities.top()),
const_cast<city**>(&cities.top()) + cities.size(),
Compare());
Update:
Do not use this hack if:
The underlying container is not vector.
The Compare functor has... |
5,810,410 | 5,810,456 | Alternative for fflush(stdin)? | Is fflush(stdin) is really required in C++ and is it good to do it this way to flush the newline in the buffer?
| The call to fflush(stdin) is undefined behavior in C (and, consequetly, in C++).
The C language standard, ISO 9899:1999 states in 7.19.5.2/2
If stream points to an output stream or an update stream in which the most recent
operation was not input, the fflush function causes any unwritten data for that stream
to be... |
5,810,681 | 5,810,705 | avoid copy by value when initializing reference | I have a function interface:
struct iFace {
virtual Type& getType() = 0;
}
and the idea is to retrieve it like:
iFace& iface = getIface();
Type& type = iface.getType();
however, i occassionally i do a mistake and write:
Type type = iface.getType();
which copies by value, which is what i want to avoid. However when... | Make iFace noncopyable by putting the copy constructor and assignment operator under "private". Then provide an explicit Copy method.
class Type {
public:
virtual Copy(Type& dest) = 0;
private:
Type (const Type &) {assert(false)}
Type & operator=(const Type &) {assert(false)}
}
You can also use boost noncopyabl... |
5,810,970 | 5,819,602 | Get raw data from QImage | I have a QImage that I built from a pixmap something like the following:
QPixmap fullPmap = topItem->pixmap();
fullPmap = fullPmap.copy(isec.toRect());
QImage chip = fullPmap.toImage();
This is basically intersecting with a rectangle on screen to crop the image to a chipped size.
I now need to get the character array ... | When dealing with raw image data, you need to be aware of some basic issues:
What is the format or layout of pixel
data. The QImage converted from
QPixmap is not necessarily always in
RGB888 or RGB32. Call
QImage::format() and deal with
different layout differently.
Especially with RGB32 family, you
need to make sure ... |
5,810,975 | 5,811,051 | Is there a time when a superclass's constructor is not called in C++? | This question got me in an interview. If B is A's subclass. When constructing B, is there a time when A's constructor is not called?
EDIT: I told the interviewer that I couldn't think of such case because I thought it would only make sense for a superclass to be constructed properly before constructing the subclass.
| One possible instance is when both A and B have no user-declared constructors and an instance of B is being value-initialized.
A and B both have implicitly declared constructors which wouldn't be used in this initialization.
Similarly if A has no user-declared constructor but appears in the member initializer list of a... |
5,811,077 | 5,811,108 | is it perfectly ok to return a naked pointer to a unique_ptr from a class | Is it ok to do the following? Obviously the caller is not prevented from deleting the naked pointer. Should I use shared_ptr and return a shared_ptr? It seems too heavy for this.
class A
{
B* GetB() { return pointer.get(); }
private:
unique_ptr<B> pointer;
};
| I think that it should work fine as it is, making it clear in the documentation that such pointer is not intended to be deleted.
Still, I would probably return a reference: in that case it's implicit that the caller mustn't delete anything.
class A
{
B & GetB() { return *(pointer.get()); }
private:
unique_ptr<B> ... |
5,811,350 | 5,811,393 | Shared Ptr variable access, and object oriented programming for newbie | I need some advice, because I am new to c++
For my wind turbine analysis program, I divided it up into various objects that handle certain tasks.
One object handles file input/output, and in my troublesome case i read from a file to get data, and this data is filled into an array of objects called blade, which each hol... | If you want to use straight up arrays (as in C), you'll need to created an array of Blades, whereas your code creates just one. You'll also need to review this question: TR1 Shared Arrays
But rather than messing with all that, how about just returning a std::vector<Blade> or perhaps a std::tr1::array<Blade, N> if it w... |
5,811,659 | 5,811,683 | Could anyone tell me why float can't hold 3153600000? | I know this is stupid but I'm a quiet a noob in a programming world here is my code.
This one works perfectly:
#include <stdio.h>
int main() {
float x = 3153600000 ;
printf("%f", x);
return 0;
}
But this one has a problem:
#include <stdio.h>
int main() {
float x = 60 * 60 * 24 * 365 * 100 ;
... | You're multiplying integers, then putting the result in a float. By that time, it has already overflowed.
Try float x = 60.0f * 60.0f * 24.0f * 365.0f * 100.0f;. You should get the result you want.
|
5,811,779 | 5,994,131 | scrolling rect (and point) into view | I have a logical order problem.
Lets say I have three points of significance. Left side of edit field, right side of edit field, caret position in edit field.
I want to show the control that has focus, and show it's caret.
To show a field that has focus, I generally try to ensure the following in this order.
1. Ensure ... | Here's the solution. Don't scroll the Field's rect into view if you need to scroll the caret into view. To decide, check if the field is bigger than the scrollable area.
if (cFocusRect.Width() < cClientRect.Width())
{
if (cFocusRect.right > cClientRect.right)
{
cFinalPoint.x += cClientRect.right - cFocu... |
5,811,892 | 5,811,941 | c++ vector iterator conversion error | little help guys im still a newbie at c++
error: invalid conversion from 'VboVO* const* const' to 'VboVO**'
im getting this error when trying to compile. here is the relevant parts of my code
struct VboVO{..};
vector<VboVO*> m_vboVos;
vector<VboVO*>::iterator iVbovo;
for(iVbovo = m_vboVos.begin() ; iVbovo != m_vboVo... | This is a guess
You are probably trying to perform this loop in a const member function of some class, with m_vboVos as a member variable. Therefore m_vboVos is const, and you cannot use an iterator with a const vector. Use const_iterator instead.
|
5,811,933 | 5,811,950 | C++ Overload = operator | I'm not sure why I get the following error when trying to overload the = operator
error: passing ‘const MyCircle’ as ‘this’ argument of ‘double MyCircle::getRadius()’ discards qualifiers|
Code:
#include <iostream>
#define PI 3.14
using namespace std;
class MyCircle
{
public:
MyCircle();
MyCircle(int r);
... | You need to add a const qualifier to the getRadius() method, like
double MyCircle::getRadius() const
{
return radius;
}
this will qualify the method to be called with an const object. You might want to add this qualifier to any methods that don't change member variables, avoiding this type of error.
|
5,811,988 | 5,812,007 | Why is this a compiler error? (g++) | So I'm attempting to utilize a generic compare functor in my utility class.
I attempt to define it and call it like so
template <class T>
bool AVL_tree<T>::avl_insert(AVL_Node<T> *& top, const AVL_Node<T> * insertNode, bool & taller) {
std::binary_function<T,T,bool>::first_argument_type insertNodeValue;
insertN... | It's a dependent name, so it requires the typename keyword:
typename std::binary_function<T,T,bool>::first_argument_type insertNodeValue;
Similarly for others. See the SO FAQ entry on dependent names.
|
5,812,281 | 5,812,375 | visual studio c++ problem with two independent projects in a solution? | I created two projects in a solution in Visual Studio C++.Both of them have the same files including the file containing the main function. But I am unable to execute the projects independently. One of them throws an error. Do all the projects in a solution link to one
exe/assembly ?
|
Do all the projects in a solution link to one exe/assembly ?
No. However if you want to run several debugging sessions using debuggers integrated into Visual Studio at same time then you have to run several Visual Studios at same time.
It is debugging only single process per time.
|
5,812,448 | 5,812,852 | how to profile code more accurately and precisely on windows vista? | Hey guys, I have a question.
how to profile code more accurately and precisely?
My OS is windows vista and my processor is Intel Centrino.
Right now I am compiling my c++ code using "-O0 -o" option on g++ and I am profiling using window's "QueryPerformanceCounter" and related APIs
accuracy and precision are two differe... | There's lots of discussion on this. If the reason for profiling is to discover ways to make the code faster, what helps you the most is to find them with certainty. Measuring the amount of time they cost with precision is much less important.
Here's an example in another language and OS, but the principle is the same.
|
5,812,483 | 5,812,749 | No target() of boost::function of a member function | I'm trying to get a pointer to a function in this way:
boost::function<void(float)> Function;
Function = boost::bind(&myClassType::myMemberFunction, this, _1);
void(*)(float) finalFunction = *Function.target<void(*)(float)>();
/* crash becouse Function.target<void(*)(bool)>() is null */
But I can not get the pointe... | function::target() is defined (I'm using the C++11 draft, which I think is a bit more clear than boost's reference) as follows:
per C++0x n3290 20.8.11.2.5[func.wrap.func.targ]/3
Returns: If target_type() == typeid(T) a pointer to the stored function target; otherwise a null pointer.
In your case, T is your type void... |
5,812,631 | 5,812,913 | How may I forbid calls to const member function of an rvalue object in C++ 2011? | The following code
#include <vector>
#include <string>
#include <iostream>
std::string const& at(std::vector<std::string> const& n, int i)
{
return n[i];
}
std::vector<std::string> mkvec()
{
std::vector<std::string> n;
n.push_back("kagami");
n.push_back("misao");
return n;
}
int main()
{
std:... | No, and you shouldn't. How am I to do std::cout << at(mkvec(), 0) << std::endl;, a perfectly reasonable thing, if you've banned me from using at() on temporaries?
Storing references to temporaries is just a problem C++ programmers have to deal with, unfortunately.
To answer your new question, yes, you can do this:
cla... |
5,812,797 | 5,814,107 | SLERP & skeletal animation interpolation help! | I had skeletal animation in my program working fine, but I was interpolating between the 4x4 matrices stored for each bone between frames in a linear way, i.e.
bMatrix bMathbMathInterpolate(bMatrix const * const p_a,bMatrix const * const p_b, float p_delta)
{
bMatrix l_mat;
for(unsigned char i = 0;i lessthan (... | You should be able to convert the translation component of the matrices to vectors, and then linearly interpolate them, and then convert the rotation component to a quaternion, and slerp (or lerp, or nlerp) them, and then recombine the resulting vector and quaterion back into a matrix.
|
5,813,272 | 5,813,280 | Dynamically creating 2d arrays | This is a situation where I have a function that receives the number of rows and columns of a ray and I want to dynamically create it within the function.
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
for... | Visual C++ is a C++ compiler, and C++ requires you to cast void*s explicitly, unlike C which allows implicit casting of void*s.
Try
array = (int**)malloc(nrows * sizeof(int *));
However, that's how you would do it in C, and if you decide later to change the data from ints to some sort of object, the object's construct... |
5,813,498 | 5,813,544 | Error when deleting allocated memory in C++ | I am new to C++ and am trying to understand the proper way to deallocated array memory. I am getting the following error when try to delete an allocated pointer array:
"pointer being freed was not allocated."
My pointer is defined as:
T * al ;
al = new T[top] ;
While my destructor for the class where the pointer al is... | Just use the delete [], not the loop in addition. delete [] will delete each element of the array.
Also, your loop in the class T destructor is trying to delete p+1 instead of p+i
|
5,813,499 | 5,813,581 | typedef-name as base class: illegal but widely tolerated | The first paragraph of [class.derived] says of base class specifiers,
If the name found is not a class-name, the program is ill-formed.
However, a simple test shows that Comeau and g++ -ansi -pedantic both accept a typedef-name as a base. A simple grep -r '[^:]: mpl' over the Boost headers shows that popular library ... | I believe this is in accordance with the standard. Specifically, §9.1/5: "A typedef-name (7.1.3) that names a class is a class-name, [...]".
|
5,813,516 | 5,813,553 | Reconstructing a value from an array of bits | I have an array of bits (stored as Boolean) that I want to reconstruct into an integer. I want to insert bits from the right hand side and shift them left for every bit in my array.
How do I insert a bit at the LSB side and shift it over at the same time?
| You would do something like this:
bool yourarray[32];
int output = 0;
for(int i = 0; i < 32; i++)
{
// Shift the bits left by 1. The first time through the loop this
// will have no real effect since 0 << 1 == 0.
output <<= 1;
// If this particular bit is "on", activate the LSB using a bitwise-or
... |
5,813,681 | 5,854,278 | CoCreateInstance does not start or connect to ATL COM service | I have a ATL COM service exe (MyService.exe), which compiles and runs fine. If I install this service (via MyService.exe /Service), it is successfully installed into the SCM. I can start the service through the SCM and it runs fine, under the LOCALSYSTEM account.
My problem arises when I attempt to create an instance o... | It turns out the culprit was how the service was registered. In order for a class to launch it's controlling application as a service, the controlling application needs to add entries into the registry so it is recognised as a local server, i.e:
(MyService.rgs)
HKCR
{
NoRemove AppID
{
ForceRemove {6E5B1... |
5,813,693 | 5,837,402 | Handling events from wxTextCtrl on wxFrame - C++/wxWidgets | I have a MyFrame which derives from wxFrame. A wxTextCtrl is added to this frame. Can I handle EVT_KEY_DOWN of this text control in frame? Something like,
BEGIN_EVENT_TABLE(wxTextCtrl, wxControl)
EVT_KEY_DOWN(MyFrame::OnKeyDown)
END_EVENT_TABLE()
The above code seems to be not working. Documentation says events li... | The wxCommandEvent and wxNotifyEvent type events from a child controls are set to propagate upward to the parent frame automatically. However, the wxKeyEvent is derived from the wxEvent so it is not propagating to the parent frame. Well, you may use dynamic event handlers to route some of the events to any of wxEvtHand... |
5,813,700 | 5,813,736 | Difference between size_t and std::size_t | What are the differences between size_t and std::size_t in terms of where they are declared, when they should be used and any other differentiating features?
| C's size_t and C++'s std::size_t are both same.
In C, it's defined in <stddef.h> and in C++, its defined in <cstddef> whose contents are the same as C header (see the quotation below). Its defined as unsigned integer type of the result of the sizeof operator.
C Standard says in §17.7/2,
size_t which is the unsigned i... |
5,813,729 | 5,813,763 | What is the difference between these two headers? | I have these two header files and one produces an error if I don't put std:: in front of all string declarations and the other doesn't. I was just wondering what the difference between the two was.
The following will produce an error if the std:: is not in front of the string declarations:
#include <string>
#include <v... | The second file is included after some other that defines
using namespace std;
|
5,813,852 | 5,814,566 | Is there a way to warn me Global Namespace Pollutions? | Does gcc (or any other compiler) have an option to warn me global namespace pollutions?
I tried to compile a sample application suite, but it turned out quite a few of header files of that samples are stricken with global namespace pollutions (using namespace in header files), so that Mac OS X global struct Rect become... | I don't know about gcc, but CLang has it:
def warn_using_directive_in_header : Warning<
"using namespace directive in global context in header">,
InGroup<HeaderHygiene>, DefaultIgnore;
You can activate it directly using -Wusing-directive-in-header or via the group -Wheader-hygiene (it is, for now, the sole member ... |
5,813,954 | 5,822,244 | How can an OpenOffice document be created in C++ |
Possible Duplicate:
Creating, opening and printing a word file from C++
Hi,
I need to create a word document from a c++ program,
Im using windows 2008 server,office automation fails sometimes here and also I need non interactive service to handle as automation provides interactive service.I've implemented automation... | Here's a newly released C library called libOPC which has the same intent as the Open XML SDK, but can be used in all of Linux/Windows/Mac/etc. You can read about it here: libOPC version 0.0.1 released and get the code from CodePlex (be sure to check the documentation page for demo videos).
|
5,814,021 | 5,814,876 | QDeclarativeImageProvider does not load image in container | Image {
id: backImage
source: "image://imageprovider/frontimage"
}
works fine, but doesn’t work with Column or another container
Column {
Image {
id: backImage
source: "image://imageprovider/frontimage"
}
}
whereas
Column {
Image {
id: backImag... | Possibly that the Image using the ImageProvider doesn't declare its width and height correctly? Columns get a bit funny with items that don't declare their width and height. Try hard coding the width and height in your Image in your second example and it should work.
|
5,814,402 | 7,755,541 | Where can I Find XFS api | I want to develop a sample XFS Application which could handle a pin pad keyboard(EPP).
So i found XFS API refrence form Here but still don't know where can i find these API.
I'll appreciate who can help me.
| I just started the process of writing a wrapper for XFS in C# for a Wincor Nixdorf Cineo T2000 self-service terminal that will handle the functions for Card Reader, PinPad and Integrated Printer.
Currently, I am working for the bank that just bought the terminal, so I have access to the API, the physical device and the... |
5,814,406 | 5,814,498 | Does a static_cast to the same (primitive) type produce any code? | I guess it's all said in the title...
But here's an example. Given
void functionThatTakesAFloat(float par);
float f = 3.5f;
does
functionThatTakesAFloat(static_cast<float>(f));
produce any additionial code compared to
functionThatTakesAFloat(f);
or is this static_cast completely eliminated by the compiler?
Edit:
I'm... | The simple answer here is that by definition a cast from float to float is a no-op. There is no conceivable code that could worth emitting for this cast. It may be true that some compiler in this universe emits unquestionably redundant code in this case, but it is safe to assume that you will never encounter such a c... |
5,814,412 | 5,814,523 | using same datatype in boost variant | Can we explicitly typecast the value which is to be stored in boost varaint??
Example:
typedef int abc;
typedef int asd;
typedef boost::variant<abc, char, asd, float> link_try1;
int main()
{
link_try1 qw;
qw = static_cast<asd>(1234);
printf("value of which is:%d", qw.which());
return 0;
}
Here I want the w... | It is possible, but it won't work as expected.
The key idea, on a variant, is that the type acts as a key. When you actually request a given type (using boost::get or visitation), the first type in the variant that matches the key is elected, thus here asd would be haughtily ignored.
If you need to store several intege... |
5,814,524 | 5,815,417 | how to project my window as active window on foreground | There were some windows opened, And from my process I want to launch one more window(high priority) in which user has to enter credentials. And i want to put this credentials window to foreground, in turn it might give good experience to user as he need not manually select the credentials window. And this is one time l... | This works for me without having to use SetWindowPos to make the window 'always on top':
HWND foreGround = GetForegroundWindow();
if (foreGround != m_hWnd)
{
if (!::SetForegroundWindow(m_hWnd))
{
if (!foreGround)
{
foreGround = FindWindow(_T("Shell_TrayWnd"), NULL);
}
... |
5,814,553 | 5,814,743 | When should I use the new ranged-for and can I combine it with the new cbegin/cend? | The new ranged-for in C++11 will be very concise and useful, of course. As far as I understand how it works, it looks up the "containers" begin and end by trying *Argument-Depending-Lookup" (ADT).
But another addition is that all the containers now have cbegin() and cend() to get the const_iterators for the container.
... | cbegin() allows you to get const_iterators from a non-const container without an explicit cast or conversion. If you have a const container then begin() will return a const_iterator anyway.
The new for construct uses begin() because that's the most general, and it avoids too many special cases. Also, by default, the va... |
5,814,578 | 5,822,640 | simple custom made mutex failing | Can you spot the error in the code? tickets ends up going below 0 causing long stalls.
struct SContext {
volatile unsigned long* mutex;
volatile long* ticket;
volatile bool* done;
};
static unsigned int MyThreadFunc(SContext* ctxt) {
// -- keep going until we signal for thread to close
while(*ctxt... | I posted a bug where I thought it was a legitimate multithreaded problem but really it was just bad logic. I solved the bug as soon as I posted. Here is the problem lines and answer
unsigned int lockedaquired = 0;
I initialized lockaquired to 0 and then after I added an if statement to skip the expensive operation of ... |
5,814,910 | 5,815,083 | Why using static namespace/class member variables is a bad idea in C++? | What are disadvantages of using static variables like in following code:
namespace XXX
{
static int i;
class YYY
{
static m_i;
};
}
Is using static variables only in .cpp (so they are invisible to other code) file OK?
| Various things allowed by C++ represent choices and compromises in software design. There is nothing inherently, absolutely evil about any of them (except perhaps throw specifications, which Prof. Stroustrop deems a broken facility ;-P).
Whether this particular code is a good choice in a particular situation depends o... |
5,814,915 | 5,815,004 | A data type like vector but sorted | Is there a data type like vector or queue where you can easily add items, but when they get added, they are automatically inserted in the right order?
Also is there an easy way to delete an item from a vector or queue if you know what it is, without having to actually search through and find it?
| It sounds like you are looking for a set and not a vector. It will be sorted according to the natural ordering (the < operator). To remove an element by value call erase.
Alternately you can just use sort on a vector to sort the elements. If you need random access to the elements then you will want this approach; the ... |
5,815,047 | 5,815,591 | C++, SQLite - pointer to pointer to string | I work with C++ and SQLite3 (with Microsoft Visual C++ 2008) and would like to read a value from my database and store it in a variable to work with it on.
The select statement works fine, but every time I viewed the callback function and try to read the value from char **argv, I get "only" the memory address, or the ... | I don't see why you need a callback - this should work (depending on the size of the data):
char myvalue[100];
while (sqlite3_step(stmt) == SQLITE_ROW)
{
strcpy( myvalue, (const char *) sqlite3_column_text(stmt, 0) );
// do something with myvalue
stmt_count++;
}
|
5,815,227 | 5,815,682 | Fix/Improve Word Wrap Function | I have a simple word wrap function that takes a long string as an input and then breaks that string into smaller strings and adds them to an array to be outputted later. Right now the last word or two isn't outputting. That's the main problem. However, I would also like to improve the function. I know it's kind of mess... | Here is an example code.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
void WordWrap(const string& inputString, vector<string>& outputString, unsigned int lineLength)
{
istringstream iss(inputString);
string line;
do
{
string word;
iss >> wor... |
5,815,236 | 5,815,352 | Strange zero initialization with g++ | I came across on a strange behavior of the following code, while playing around with initialization of ints using g++ 4.4.3.
int main()
{
int x(int());
int y = int();
cout << x << " " << y << endl;
}
the result is:
1 0
The value of "y" is 0 as expected, but the value of x is s... | To complement GMan's answer here (x is a function definition) as to why the 1.
The reason for the output to be 1 is that at the place of call std::cout << x, the function decays into a pointer to the function (the language does not allow you to pass functions as arguments to other functions, so as with arrays an implic... |
5,815,416 | 5,815,753 | Combining two regular expression c++0x | I have a text where a date can look like this: 2011-02-02 or like this: 02/02/2011, this is what I have been written so far, and my question is, if there is a nice way of combining these two regular expressions into one?
std::regex reg1("(\\d{4})-(\\d{2})-(\\d{2})");
std::regex reg2("(\\d{2})/(\\d{2})/(\\d{4})");
sma... | You could combine the two regexes together by |. Since only one of the | can be matched, we can then concatenate capture groups of different parts and think them as a whole.
std::regex reg1("(\\d{4})-(\\d{2})-(\\d{2})|(\\d{2})/(\\d{2})/(\\d{4})");
std::smatch match;
if(std::regex_search(item, match, reg1)) {
std:... |
5,815,424 | 5,815,524 | Global Keyboard Hook from windows service | Is it possible to write a global Keyboard Hook from windows(xp and 7) service ? ( using SetWindowsHookEx didn't work from a system service )
| The documentation for SetWindowsHookEx says:
or with all threads in the same desktop as the calling thread.
So you need to be associated with the same desktop (and there will be multiple desktops even without considering terminal services: the normal desktop, the secure desktop (used for UAC and login) and the scree... |
5,815,469 | 5,815,554 | func(" ") causes "call of overloaded QChar(const char[2]) is ambiguous | Can tell me why the code below causes this error :
call of overloaded 'QChar(const char[2])' is ambiguous
and the code :
void func(QChar a) {
qDebug() << a;
}
void main() {
func(" ");
}
When String.remove(QChar,Qt::CaseSensitive) works : a.remove(" ");
| You're passing a string literal (" "), which is of type const char[2] (one element containing the space, and another one for the terminating \0). You want to pass a char literal, written with single quotes: func(' ').
The QString::remove() function is overloaded for both strings and single characters. Even in that case... |
5,815,480 | 5,815,525 | "How can I jump to functions in a C++ project with vi | I am making a c++ program with vi. It has only one file but it's getting kind of big. It would be nice if I could easily see all the functions I created and jump to any one of them without having to search for them. Can vi do this, or is there a similar program that can?
| This seems like a dup of Jump to function definition in vim.
To sum up that answer, use ctags, and take a look at Vim and Ctags tips and tricks.
|
5,815,709 | 5,815,887 | pthread_create error in C++ (pthread inside class) | I have this C++ code, where i try to create a pthread, and i got 4 errors:
Can anyone please help?
Thanks in advance.
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
static void* func(void*);
class Test
{
public:
pthread_t *threadId;
pthread_create(threadId, NULL, func, NULL);... | You can't call functions in class declaration. In class declaration you can only declare (and possibly define) its members. And
pthread_create(threadId, NULL, func, NULL);
is not a valid member function definition.
The whole class Test seems to be redundant.
static void* func(void *arg)
{
printf("Thread function ca... |
5,815,822 | 5,815,912 | what happens with data declared as const in c++ | When we declare the const variable it is said in Bruce eckel book that constant folding happens that means memory is not allocated for the variable.
What happens when we declare the variable as const?
How is the compiler free to optimise const variables?
Is memory for const variables is always allocated, and under whi... | I found the following quote on a PDF attributed to Bruce Eckel:
const int bufsize = 100; You can use
bufsize anyplace where the compiler
must know the value at compile time.
The compiler can use bufsize to
perform constant folding, which means
the compiler will reduce a complicated
constant expression to a... |
5,815,823 | 5,815,949 | linux ubuntu c++ .h and .cpp file | I have a my.h file:
#ifndef __MY__
#define __MY__
#include <string>
#include <time.h>
class S
{
public: S();
std::string myname;
};
#endif
my.cpp
#include "my.h";
#include<string>
#include<iostream>
using namespace std;
S::S()
{
// .. code
}
I want to create an so file. There is no error when creati... | Well, first, it seems that you come from java because when you typed:
class S
{
public: S();
std::string myname;
};
I guess you actually meant:
class S
{
public:
S();
private:
std::string myname;
};
In the .cpp file, you typed s instead of S: note that C++ is case-sensitive regarding classes names.... |
5,815,838 | 5,816,029 | How do I find all the positions of a substring in a string? | I want to search a large string for all the locations of a string.
| The two other answers are correct but they are very slow and have O(N^2) complexity. But there is the Knuth-Morris-Pratt algorithm, which finds all substrings in O(N) complexity.
Edit:
Also, there is another algorithm: the so-called "Z-function" with O(N) complexity, but I couldn't find an English source for this algor... |
5,815,983 | 5,816,054 | RCDATA: Mixing strings and binary data | The next line added in a .rc will add the file NOTEPAD.EXE to resources as a binary data
0x3333 RCDATA "C:\\WINDOWS\\NOTEPAD.EXE"
however, using code below a string with value "C:\WINDOWS\NOTEPAD.EXE" will be added as resource
0x3333 RCDATA
BEGIN
"Hello world"
"C:\\WINDOWS\\NOTEPAD.EXE"
0x9999 ;hex number stor... | The second syntax does not support external files like the first syntax does. String literals are stored as-is, as you have noticed.
|
5,816,100 | 5,816,129 | Could someone explain this C++ syntax? |
Possible Duplicate:
What is this weird colon-member syntax in the constructor?
Hi, I recently came across this syntax in a C++ program. This is not passing parameters to a base class constructor as I know what that looks like and how to code it. This looks like some sort of variable initialization for the class... H... | That's the syntax for member initialization, as you surmised. Contrast this:
class C
{
private:
int i;
public:
C(int i_) : i(i_) {} // initialization
};
with:
class C
{
private:
int i;
public:
C(int i_) { i = i_; } // assignment
};
It's generally better to initialize members rather than assigning to them in t... |
5,816,218 | 5,816,235 | Difference between initializer and default initializer list in c++ | HI,
I have a question but cannot find the answer for a long time, that is,
what's difference between the following 2 statements about the parameter
initialization?
class A::A()
: a(0), b(0), c(0)
{
}
class A::A()
{
a = 0
b = 0;
c = 0;
}
I know there is "direct initialization" and "copy in... | The purpose of default initialization list is to initialize the constant variable with in the class.
Because the constant variable is initialized before the object is initialized.
I provide one sample to explain the difference between these two initializations:
class A
{
private:
const int x;
... |
5,816,263 | 5,824,528 | MSMQ c++ to c# problem | I want to write messages to a MSMQ queue using C++ and read them using C#.
I send the messages as strings.
It works fine if I both write and read the messages in C++ but if I try to read the message using C#, I get only the first character of the message. (eg: I send "abcd" and I receive only "a").
I also must mention ... | I solved myself the problem. I shall post here the code maybe there is someone else interested.
try
{
Message received;
Stream bodyStream = null;
int bufLength = 512;
byte[] buffer = new byte[bufLength];
received = this.readMQ.... |
5,816,342 | 5,816,367 | How to access static class variable in static member function of same class? | I provide my sample:
class a
{
public:
static int m_n;
static int memfuc();
};
int a::memfuc()
{
int k =m_n;
return k;
}
But the following sample throws linker error: unresolved external symbols
| You need to provide the implementation somewhere:
int a::m_n;
|
5,816,414 | 5,816,461 | Synonym for ApprovalWorkflow | We have an abstract workflow class that is called ApprovalWorkflow the thing is it can hold both an approve, reject and input state. Its slightly misleading to call it ApprovalWorkflow but I cant be sure of what the right term is.
Does anyone know of a better term to call ApprovalWorkflow as it can Authorize and Rejec... | I don't see a problem. Authorization can have two outcomes, Authorized and NotAuthorized = Rejected. That's the entire point of it, in fact.
I'm more worried about the input state part. That sounds like {True, False, FileNotFound}
|
5,816,658 | 5,816,692 | How to have a set of structs in C++ | I have a struct which has a unique key. I want to insert instances of these structs into a set. I know that to do this the < operator has to be overloaded so that set can make a comparison in order to do the insertion.
The following does not work:
#include <iostream>
#include <set>
using namespace std;
struct foo
{
... | This might help:
struct foo
{
int key;
};
inline bool operator<(const foo& lhs, const foo& rhs)
{
return lhs.key < rhs.key;
}
If you are using namespaces, it is a good practice to declare the operator<() function in the same namespace.
For the sake of completeness after your edit, and as other have pointed out, ... |
5,816,719 | 5,816,766 | Difference between function arguments declared with & and * in C++ | I typed the following example:
#include <iostream>
double f(double* x, double* y)
{
std::cout << "val x: " << *x << "\n";
std::cout << "val y: " << *y << "\n";
return *x * *y;
}
double f2(double &x, double &y)
{
std::cout << "val x: " << x << "\n";
std::cout << "val y: " << y << "\n";
return x *... | f2 is taking it's arguments by reference, which is essentially an alias for the arguments you pass. The difference between pointer and reference is that a reference cannot be NULL. With the f you need to pass the address (using & operator) of the parameters you're passing to the pointer, where when you pass by refere... |
5,816,883 | 5,816,987 | smart pointer implementation for derived to base pointers | I have created a smart pointer implementation as given below ::
#include <iostream>
#include <vector>
using namespace std;
class Obj {
int i, j;
public:
Obj() { i = 0 ; j = 0 ; }
Obj(int ii , int jj) : i(ii) , j(jj) { }
void f() { cout << i << endl; }
void g() { cout << j << endl; }
};
class ObjDerived ... | You can provide public get() function member to be able to retrieve raw pointer. Commonly smart pointers provide this functionality. Small example:
template <typename ULT >
class SP {
// ...
ULT* get() const {return ptr;}
template <typename OTHER>
SP<ULT>& operator=(SP<OTHER>& der) {
cout << "In operator\n";
... |
5,816,950 | 5,818,587 | Automatic tracing of program execution | I would like to know if we can enable tracing in any C or C++ application.
For example, with a gcc option or a small tool, I will enable trace and either trace is printed on console or dumped to a file.
Since there are lots of files and function / classes, I don't want to start adding the trace prints manually.
If suc... | To trace the function entry/exit, you can recompile your code with the option -finstrument-functions so that each time a function is invoked, a __cyg_profile_func_enter() function is called, and __cyg_profile_func_exit() is called when the function returns.
You can implement those functions to trace the addresses on th... |
5,817,200 | 5,817,349 | behavior of static variable with inheritance | I am asking this question for the discussion.
Suppose i have flowing class hierarchy
class A
{
public:
static int varr;
}
class B : public A
{
}
Class C : public A
{
}
If I create the Object of B b1,b2,b3; and C c1,c2,c3; and A a1, a2;
1.will varr is shared across ... | Yes, it will be shared accross all the instance of all derived(B,C) and base class(A)..
Only one instance for a static object will be created, and at all place that object will be refered. So if you change at one place it means change will be reflected at all location where its being refered.
|
5,817,274 | 5,898,820 | HTTP sending response to OPTIONS request [C] | Getting Response is null error while receiving HTTP response.
I am developing an sample small HTTP server in C using row sockets.
There are actually 2 servers in my application one is standard Apache server which I am using for serving HTML pages and my small server will respond to only XMLHttpRequest sent from the ... | This problem had occured as after processing the OPTIONS request by our server, any subsequent requests made, for some reason, were required to be responded back with "Access-Control-Allow-Origin: *" along with other normal headers and response body.
After providing this line in our responses, I always got the desired... |
5,817,380 | 5,817,495 | Overlays icon on different files based on statuses | Hi i am new to shell extensions.
I read the http://www.codeproject.com/KB/shell/overlayicon.aspx
article and was able to show overlays icon on the files whose names contains the string "sample".
Now my question is that i have an application, that displays different overlays for different files based on file status, s... | Just apply what you've learned in that article. What you're wanting to do now is almost the same thing. The shell calls your handler and asks for an overlay icon. Your code checks the item's status, and returns the correct overlay icon. If you don't own the item, you tell the shell not to draw an overlay at all.
You ca... |
5,817,491 | 5,823,081 | Maths in Programing Video Games | I've just finished second year at Uni doing a games course, this is always been bugging me how math and game programming are related. Up until now I've been using Vectors, Matrices, and Quaternions in games, I can under stand how these fit into games.
This is a General Question about the relationship between Maths and ... | Skizz's answer is true when taken literally, but only a small change is required to make it possible to compute the derivative of a C++ function. We modify skizz's function f to
template<class Float> f (Float x)
{
return x * x + Float(4.0f) * x + Float(6.0f); // f(x) = x^2 + 4x + 6
}
It is now possible to write a C+... |
5,817,971 | 5,819,686 | Use CGEvent with Qt on Mac Os X | I need to simulate keyPress on my Qt application (I'm on mac Os X 10.6).
I wrote this code:
#include <ApplicationServices/ApplicationServices.h>
...
CGEventRef mkey = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)46, true);
CGEventPost(kCGAnnotatedSessionEventTap, mkey);
CFRelease(mkey);
...
But there is an error:
Undef... | Add this line to your .pro file:
LIBS += -framework ApplicationServices
|
5,818,036 | 5,818,069 | Realtime C Programming Example | I want to use C or C++ to do hard realtime processing of market ticker data. Are there any special considerations to take into account when using either language? Such as headers or what not to do?
Regards
| Don't use dynamic memory allocation (malloc/free) because you can't predict the amount of time this will take. Don't use critical sections (same reason), use lock-free algorithms instead if necessary.
|
5,818,050 | 5,818,094 | _THROW not defined in GCC? | Please tell me where the _THROW macro is defined in GCC4 or how to define it manually
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <climits>
#include <stdexcept>
#include <sys/cdefs.h>
#include <sys/types.h>
void test() { _THROW(std::range_error,"Test"); }
... | If you want to throw an exception in C++, use the standard C++ throw keyword:
throw std::range_error("Test");
Please refrain from using some compiler-specific internal macro.
If you must define it, here you go:
#define _THROW(e, ...) throw e(__VA_ARGS__)
|
5,818,164 | 5,818,378 | Realtime TCP/IP stack | I want to program (as efficiently as possible) a TCP/IP communication stack in C or C++. It really must run as fast as possible.
Does anyone have a good example or suggestion of where to start?
| As Steve points out in the comments you do need quite a bit of experience to do this well. So rather than jumping directly to your end goal I recommend these possible steps:
Write a reliable transport using UDP as a normal user-land protocol.
Write a custom protocol using raw sockets in user-land.
Write a kernel leve... |
5,818,173 | 5,818,201 | Why does GetCurrentProcess return -1? | In this small program, why does GetCurrentProcess() return -1?
int _tmain(int argc, _TCHAR* argv[]) {
HANDLE h = GetCurrentProcess(); // ret -1
printf("0x%x\n",(DWORD)h);
return 0;
}
What's wrong?
In Kernel32.GetCurrentProcess I see this:
OR EAX,FFFFFFFF ; EAX - ?
RETN
| That is correct, see this API reference for GetCurrentProcess.
The GetCurrentProcess function retrieves a pseudo-handle for the current process, which is currently defined as (HANDLE)-1. However, because you should not assume that the value will never change, the GetCurrentProcess function is provided as an alternativ... |
5,818,270 | 5,827,475 | Undefined symbols for architecture i386: | I've recently moved over to a mac, and am struggling using the command line compilers. I'm using g++ to compile, and this builds a single source file fine. if I try to add a custom header file, when I try to compile using g++ I get undefined symbols for architecture i386. The programs compile fine in xCode however. Am ... | It looks like you’ve got three files:
matrix.h, a header file that declares the Matrix class;
matrix.cpp, a source file that implements Matrix methods;
main.cpp, a source file that defines main() and uses the Matrix class.
In order to produce an executable with all symbols, you need to compile both .cpp files and lin... |
5,818,350 | 5,818,784 | Break point hangs DirectX-based program in full screen mode | I started making a game, I have a global class that reads in a csv file, loads two direct x surfaces, and creates the background.
the surfaces are a tile sheet and the other the background created from the tiles. the background surface does no work, after instillation I check it and if null a message box appears. It al... | With directshow, it can be bothering to debug in full screen : if you really have to do it, I suggest either using a second screen (this way, you can debug on your screen 1 while your program runs in full screen on your screen2).
If this doesn't work, you'll have to use remote debugging (i.e. run the programm on a comp... |
5,818,534 | 5,818,633 | 'new' operator and typedef-ed arrays in C++ |
Possible Duplicate:
Is it possible to dynamically create an array of constant size in C++?
This is rather a theoretical question - I wonder why actually operator new[] in C++ returns pointer to first element of array and not actual array (or a pointer to it). This came to me while trying to do something like
typedef... | What I find strange here is that operator new[] is used. The code tries to allocate a single instance of an aggregate, which would be legal if the aggregate was a struct.
But this is the behavior called out by the standard in section [expr.new].
However, there's a very simple workaround:
typedef int int4[4];
int4* ni4... |
5,818,650 | 5,818,720 | Error in a Link List | I wrote the following code for a Link list to create a Book its serial no. and search it. I am using linked list in it.
When I add my first entry , it is added successfully, but when I add second entry it shows segmentation fault. I am not able to figure out why. Please help.Thanks in advance.Code:
#include<iostream>
... | Here
while(n->next!=NULL)
{
n=n->next;
}
n=n->next;
you iterate through the linked list to find the last element, then step past it. After this, n will be null.
What you are missing is creating a new element and appending it to the end of the list.
And here
n->accno=x;
n->name=s;
you must also assign n->next = null... |
5,818,687 | 5,819,236 | set difference for duplicates in the second range, alternative remove_copy | I have two arrays or vectors, say:
int first[] = {0,0,1,1,2,2,3,3,3};
int second[] = {1,3};
I would like to get rid of the 1s and 3s in the first set, set_difference can only get rid of the first occurrences of these values however this is not what I want to have.
Should I do this with remove_copy by iterating on... | Write a specialised set_difference:
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
OutputIterator set_difference_any( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
Outp... |
5,818,695 | 6,097,072 | Why it reads the file correctly only at second time | I have a file which first 64 bytes are:
0x00: 01 00 00 10 00 00 00 20 00 00 FF 03 00 00 00 10
0x10: 00 00 00 10 00 00 FF 03 00 00 00 10 00 00 FF 03
0x20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
When i'm reading the file (mode read and write) at p... | Now I'm writing an answer, because my attempt to contact TonyK failes (I asked for writing an answer).
The perfect answer to my question was to enable exceptions by calling exceptions (eofbit | failbit | badbit).
Rumo
|
5,818,751 | 5,818,808 | Why the following code is not working? | I have Created a static control using following styles...
picBoxDisp = CreateWindow("STATIC", "image box",
WS_VISIBLE |WS_CHILD | SS_BITMAP |WS_TABSTOP | WS_BORDER,
50, 50, 250, 300,
hwnd , (HMENU)10000, NULL, NULL);
SetWindowLongPtr(picBoxDisp,GWLP_WNDPROC,(LONG) dispWndProc);
from somep... | It's possible that some other code is also sending STM_SETIMAGE to your window. Count the number of times you call SendMessage(STM_SETIMAGE) and the number of times you reach case STM_SETIMAGE.
Also, HDC imgDC = GetDC((HWND)img); is never going to work. An HBITMAP is not an HWND.
|
5,819,066 | 5,819,207 | Best multiformat C++ mobile development solution? | We are thinking about developing some programs and games for Android and iPhone. Everyone involved have most experience working with C++ and OpenGL for games. I found BatteryTech and MoSync. Have anyone tried these and/or any other soultion and has some cons/pros to share?
| I'm porting a network protocol library to Airplay SDK, you may want to look at it. I'm aware of a few "big names" using it to develop iOS/Android games (due to NDA I'm not able to disclose the names).
The APIs provided are quite OK (there were a few bugs in the sockets API in the past). The tools are a bit crude, but ... |
5,819,198 | 5,819,261 | Allocators for game engine | I am currently coding a memory allocation system for a game engine, and I was wondering if there were any experienced developers out there who could help with some advice about what allocator structures are useful.
I know that sounds a bit worrying to some people, and so I think I need to justify my position a little b... | Well, honestly, the ones I've been using most are Pool<T> for short-lived objects and pre-allocated heap as a replacement over C++ default allocator.
But once again, develop what you need when you need it.
|
5,819,217 | 5,819,256 | Verify type of string (e.g. literal, array, pointer) passed to a function | I have a function, which takes a character array and its size:
void store_string (const char *p, size_t size); // 'p' & 'size' stored in map
The function is wrapped by a macro as:
#define STORE_STRING(X) store_string(X, sizeof(X))
My problem is that I want to somehow prohibit or inform user that only string literal s... | You can know it compile time, by simply changing your macro to:
#define STORE_STRING(X) store_string("" X, sizeof(X))
Usage:
char a[] = "abcd", *p;
STORE_STRING(a); // error
STORE_STRING(p); // error
STORE_STRING("abcd"); // ok
|
5,819,995 | 5,820,267 | Operation overloading C++ in a MANAGED C++ project | I've a managed C++ dll which talks with a C# GUI. It works fine, the communication goes through a wrapper and it all works. The code inside the dll is all written in C++, but I can't get operator overloading working and im planning to use it for sorting vectors. I don't know if there's an error in my code or if it does... | Your vector elements are Move* (a pointer). This is a built-in type, you can't redefine its operators. And less_than_second has the wrong signature, it doesn't accept pointers.
|
5,820,159 | 5,820,225 | typedef an existing enum type, possible? | Given the following:
namespace otherns
{
enum MyEnum_e { MyEnum_YES, MyEnum_NO };
}
namespace myns
{
typedef otherns::MyEnum_e MyEnum_e;
}
Why is the following not valid?
int e = myns::MyEnum_YES;
I get a compiler error stating:
'MyEnum_YES' is not a member of 'myns'
| Because the enum values live in the namespace otherns, not as a child of MyEnum_e: to reference MyEnum_YES, you type otherns::MyEnum_YES.
You might try this:
namespace otherns
{
namespace MyEnum_e_space {
enum MyEnum_e { MyEnum_YES, MyEnum_NO };
}
using namespace MyEnum_e_space;
}
namespace myns
{
... |
5,820,269 | 5,820,365 | C++ / Boost: Undefined Symbols in example? | The example I'm trying to compile is from: http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/examples.html
(the chat example)
Here is what I'm using to make it:
>>> g++ chat_client.cpp chat_message.hpp
>>> g++ chat_server.cpp chat_message.hpp
This is what the terminal outputs:
% g++ chat_client.cpp chat_m... | You need to provide g++ boost libraries to link with usins -l option. I have a quick look on this examples and guess that you definitly need thread library. You can link with it using
g++ source.cpp -o executable -lboost_thread
Also you may need with boost_system library using
g++ source.cpp -o executable -lboost_th... |
5,820,273 | 5,820,300 | Difference between !(variable) and (!variable) | In either C or C++, is there a conclusive difference between using !(variable) and (!variable) in an if-statement, such as:
if (!(variable)) { .. // do something }
or
if (!variable && !(variable2)) { .. // do something }
such that one version delivers a different result over the other?
| The only way it would make a difference is if the variable is an expression, then its a matter of operator precedence. Otherwise && has lower precedence than !
|
5,820,407 | 5,820,555 | c++ overloading the [] operator without a class | I have created a structure:
struct a{
int a1;
int a2;
int a3;
};
Is there any way to create a function where a[1] will give access to a1 in the same way that I'll be able through an array?
Edit, I have pasted the part that I actually do:
struct lipid{
particle mainPart;
bead * head;
bead * body;
bead ... | As noted by delnan, you can use methods on structures, just like classes.
So:
struct a{
int a1;
int a2;
int a3;
int &operator[]( int i ){
switch(i){
case 1: return a1;
case 2: return a2;
case 3: return a3;
default: return -1
}
}
};
|
5,820,530 | 5,820,633 | Can I delete class pointer copied using memcpy()? | Is the following snippet of code valid?
class Foo
{
public:
int a;
SomeClass* pb;
Foo() {...}
Foo(const Foo& rhs)
{
this->a = rhs.a;
memcpy(this->pb, rhs.pb, sizeof(SomeClass));
}
~Request()
{
delete this->pb; // Suppose pb is a result of copy constructor,
... | You haven't actually allocated anything for pb. If you allocate it with new, then using delete in the destructor is perfectly valid.
But why oh why are you doing a memcpy? You should be using the copy constructor of the class and letting it copy itself in the appropriate fashion. The only time a memcpy would be remotel... |
5,820,539 | 5,821,010 | Why does ubuntu ship with a memory allocator that is 2x slower than google tcmalloc? | benchmarks here:
On the use and abuse of alloca
I assume the same holds for other Unices, when google perftools exists, and it is 2x (a bit more) faster than a standard allocator, why then do distributions still ship with sub-optimal ones ? Bearing in mind that tcmalloc has been available for 5+ years.
| It's rare that something is quite simply "2x faster" than something else. It might be 2x faster 90% of the time, and 10x slower 10% of the time. For a general system allocator, you want something that does fairly well all the time, rather than very-good-at-specific-cases. That's probably why the default allocator is... |
5,820,552 | 5,820,625 | How do you display the contents of a string using the position of a substring as a starting point? | Is it posible to cout a string from a position gained by using string.find to the end of the string.
| It is certainly possible, and in more ways than one. string.find() returns a position, so
#include <iostream>
#include <string>
int main()
{
std::string str = "This is a test";
std::string::size_type pos = str.find("test");
if(pos != std::string::npos)
std::cout << str.substr(pos) << '\n';
}
or wit... |
5,820,641 | 5,820,676 | illegal use of this type as expression (error) C++ | The most recent file I've added to my VC++ 2010 project is suddenly giving me errors about the data types.
After doing a bit of searching, this error seems to be common in C code but I'm using C++ (and yes, my file extension is correct).
My BUFFER class still works fine in all my other files and if I comment those out... | Most likely the misspelled private is confusing the compiler on the next line where your BUFFER bfTaskBuffer is declared.
EDIT:
Also a few comments about the code and style:
Double underscores are reserved in any context, and leading underscores are some contexts (followed by capital letter or in the global namespace,... |
5,820,716 | 5,820,799 | Predefine Derived Class | I am trying to predefine a derived class as follows,
class Base{
}
class Derived;
class Unreleated{
Base* ptr;
public:
Unreleated& operator, (const Unreleated& m){
static_cast<Derived*>(ptr); // pointer is a derived.
return *this;
}
}
class Derived : public Base{
//this is a container holding a b... | Move the definition of Unreleated::operator, to after the definition of Derived.
class Base{
};
class Derived;
class Unreleated{
Base* ptr;
public:
Unreleated& operator, (const Unreleated& m);
};
class Derived : public Base{
//this is a container holding a bunch of unrelated.
};
Unreleated& Unreleated::op... |
5,820,946 | 5,820,989 | GetModuleFileName Antivirus False Detection ??? Get current process PATH | Hellow I am trying to retrive path off current process...
here is my first code:
#include <windows.h>
#include <iostream>
using namespace std;
int CALLBACK WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
char loaded_file_name[MAX_PATH];
GetModuleFileName(NU... | Your code was fine, you aren't the problem.
Antivirus software sucks, period.
|
5,821,012 | 5,821,084 | why does gcc linker choose older version of shared lib? | I'm puzzled. I have 2 versions of libssl.so in /lib:
/lib/libssl.so.4 and /lib/libssl.so.6
Here is a stripped down minimal example -- I'm linking "nothing" with libssl -- the result being that it links to libssl.so.4. What determines this?
$ g++ -o foo.so -shared -lssl
$ ldd foo.so |grep ssl
libssl.so.4 => /lib/lib... | The option -lssl instructs the linker to look for the file named libssl.so or libssl.a. If all you have are libssl.so.4 and libssl.so.6, then you would have a linker error.
Look for a symlink called "libssl.so" somewhere in your library directories, likely in /lib.
|
5,821,075 | 5,821,115 | Why do virtual functions need to be passed with a pointer and not by value(of the object)? | I think I understand the concept of virtual methods and vtables, but I don't understand why there is a difference between passing the object as a pointer(or reference) and passing it by value (which kind of scraps the vtable or something?)
Why would something like this work:
Material* m = new Texture;
poly->setMaterial... | Because if you pass by value, then object slicing will occur, and runtime polymorphism cannot be achieved. And in your code, the very line Material m = Texture() causes object slicing. So even if you pass m by pointer (or reference), runtime polymorphism cannot be achieved.
Also, runtime polymorphism is achieved throug... |
5,821,141 | 5,821,198 | Two questions in C++ language | I am learning C++ language. There are two concepts I can not figure out:
What is the difference between new and malloc?
What is the difference between pointer and reference?
Can anyone help?
The original title of the question and the claim about learning said the question was about C, not C++. But the questions ar... | C is not C++.
new is how you allocate memory and call constructors in C++. malloc just allocates memory, in both C and C++.
A pointer can be NULL - aka point to a defined invalid location. A reference (which doesn't exist in C) will always refer to something - it cannot legally refer to an invalid location.
|
5,821,188 | 5,821,379 | Makefile: problem getting ifstatement to work =( | MAC_BOOST_PATH = -L/opt/local/lib
LINUX_BOOST_PATH = -L/usr/lib/
DEFAULT_PATH = -L/usr/local/lib
BOOST_PATH = $(DEFAULT_PATH)
ifeq ($(UNAME), Darwin)
BOOST_PATH = MAC_BOOST_PATH
@echo Compiling for Mac OS X
@echo
endif
ifeq ($(UNAME), Linux)
BOOST_PATH = LINUX_BOOST_PATH
@echo Compiling for Linux
@echo
endif
The ec... | You can't put commands in a Makefile independent of targets. You need to introduce a target which displays the OS. Also, you're lacking '$()'. Use e.g.
UNAME=$(shell uname)
MAC_BOOST_PATH = -L/opt/local/lib
LINUX_BOOST_PATH = -L/usr/lib/
DEFAULT_PATH = -L/usr/local/lib
BOOST_PATH = $(DEFAULT_PATH)
ifeq ($(UNAME),Darwi... |
5,821,707 | 5,912,732 | Cropping a video file with defined width, length, and pixel location | I an trying to create a program that will detect a face in a video. There are a few requirements that must be passed before I accept the "face". After all of the requirements are met I then want to take the frames that hold that "face" and crop them to make the face the area of focus. The program will go through every ... | There is a couple of options you have. If you want to pre-process the video before running your application (in case it is in some unusual format) I would suggest to use VirtualDub for that. You can run it with console as far as I remember. If your video is in some standard format you can just ignore this paragraph.
Fo... |
5,821,717 | 5,821,843 | How can I find programatically where iexplore.exe is? | I need to run myApp.exe that in turn will launch iexplore.exe.
What is the most robust, generic way (OS bit version agnostic) to do so?
Can you point me to the right registry key /env var/other mean to do so?
Thanks,
Guy
| For newer versions of Internet Explorer you can check the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Capabilities\ApplicationDescription.
That being said, the most backward- and forward-compatible way will be to look in the following paths (in this order):
In Registry: HKEY_CLASSES_ROOT\IE.AssocFile.HT... |
5,821,802 | 5,821,874 | QSpinBox inside a QScrollArea: How to prevent Spin Box from stealing focus when scrolling? | I have a control with several QSpinBox objects inside a QScrollArea. All works fine when scrolling in the scroll area unless the mouse happens to be over one of the QSpinBoxes. Then the QSpinBox steals focus and the wheel events manipulate the spin box value rather than scrolling the scroll area.
I don't want to comp... | Try removing Qt::WheelFocus from the spinbox' QWidget::focusPolicy:
spin->setFocusPolicy( Qt::StrongFocus );
In addition, you need to prevent the wheel event from reaching the spinboxes. You can do that with an event filter:
explicit Widget( QWidget * parent=0 )
: QWidget( parent )
{
// setup ...
Q_FOREACH... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.