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 |
|---|---|---|---|---|
3,149,286 | 3,149,739 | Architectural tips on building a shared resource for different processess | In the company I work at we're dealing with a huge problem: we have a system that consists in several units of processing. We made it this way so each module has specific functionality. The integration between these modules is done using a queue system (which is not fast but we're working on it) and replicating message... | I also think that shared-memory is the way to go. To provide redundancy, let every process copy the data that is going to be changed to local/non-shared memory. Only after the module has done its work, copy it back to shared memory. Make sure the 'copy-to-shared-memory' part is as small as possible and nothing can g... |
3,149,371 | 3,149,404 | PHP-Based intranet application Call center | As in title, I am making a PHP-Based intranet application Call center, I've finished the DB design/UI. But now I need to automatically intercept calls and send the caller ID to the PHP webserver so the request is routed to the next free agent while his webpage refreshes with the caller's card(and previous questions may... | Have you looked at TrixBox? This should be able to handle incoming calls, and from memory I believe it has methods to send data elsewhere eg to your webserver. From there it should be able to route the call over an IP-based network to your next free agent.
This obviously depends on the flexibility of your hardware and... |
3,149,395 | 3,151,047 | How to compile and build this BHO for IE? | http://www.adp-gmbh.ch/win/com/bho.html
When I compile, I get lots of errors:
error C2236: unexpected 'class' 'adpbho'. Did you forget a ';'?
error C3381: 'adpbho' : assembly access specifiers are only available in code compiled with a /clr option
..\adpbho.cpp(15) : error C3861: 'MB1': identifier not found
..\adpbho.... | Well, assuming you turned off your brain and just cut and pasted the garbage on that site, the first error is that this is not a valid way to declare a C++ class:
class BHO class adpbho : public IObjectWithSite, public IDispatch {
There are two class statements. That's not allowed. It's probably supposed to be:
cla... |
3,149,407 | 3,149,686 | Call a member function with bare function pointer | What's the best way to call a member function if you have an object and a bare function pointer pointing to the member? Essentially I want to call the function pointer with thiscall calling convention.
Background: I'm looking up symbols in a shared library dynamically, obtaining a factory function pointer and a pointer... | Unfortunately a member function pointer has more information than a standard function pointer, and when you get the standard function pointer, converting it to a member function pointer would effectively be trying to generate extra data out of thin air.
I don't think there's any portable way to do what you're attemptin... |
3,149,543 | 3,149,575 | Method return being assigned to variable | I have a method that is returning a CString and placing it into a variable, however this variable is a parameter in the method. Is there a better way to assign the return of the method into the variable?
Example:
CString foo = "foo";
foo = MakeBar(foo);
| Pass foo by reference into the function. In that way it's understood that it will be an input/output parameter.
void MakeBar(CString &foo)
{
if(foo == "foo")
foo = "bar";
}
//...
CString foo = "foo";
MakeBar(foo);
|
3,149,611 | 3,149,742 | Sort a vector on a value calculated on each element, without performing the calculation multiple times per element | can anyone recommend a nice and tidy way to achieve this:
float CalculateGoodness(const Thing& thing);
void SortThings(std::vector<Thing>& things)
{
// sort 'things' on value returned from CalculateGoodness, without calling CalculateGoodness more than 'things.size()' times
}
Clearly I could use std::sort with a c... | I can think of a simple transformation (well two) to get what you want. You could use std::transform with suitable predicates.
std::vector<Thing> to std::vector< std::pair<Result,Thing> >
sort the second vector (works because a pair is sorted by it first member)
reverse transformation
Tadaam :)
EDIT: Minimizing the n... |
3,149,816 | 3,149,912 | MFC: Save from CImage to database as selected file-type | We have a requirement that a user can load any standard image into a dialog, the image is displayed, and the image saved as a specific format (JPG) in a database. It seems CImage is the class to be using since it can load and save BMP/GIF/JPG/PNG. But is there an easy way to save the JPG as a BLOB in the database witho... | CImage::Save has two overloads. You could use
HRESULT Save(
IStream* pStream,
REFGUID guidFileType
) const throw();
to save the image to an IStream. You could write your own simple IStream implementation or could try to use the CreateStreamOnHGlobal function, which creates an IStream object on an HGLOBAL.
|
3,149,859 | 3,149,881 | std::map::const_iterator template compilation error | I have a template class that contains a std::map that stores pointers to T which refuses to compile:
template <class T>
class Foo
{
public:
// The following line won't compile
std::map<int, T*>::const_iterator begin() const { return items.begin(); }
private:
std::map<int, T*> items;
};
gcc gives me the followin... | Use typename:
typename std::map<int, T*>::const_iterator begin() const ...
When this is first passed by the compiler, it doesn't know what T is. Thus, it also doesn't know wether const_iterator is actually a type or not.
Such dependent names (dependent on a template parameter) are assumed to
not be types unless prefi... |
3,149,974 | 3,152,171 | Is C++ OTL SQL database library using parameterized queries under the hood, or string concat? | I've been looking at the OTL (Oracle, Odbc and DB2-CLI Template Library) for C++ database access. I'm unsure of whether the query I pass in is converted to a parameterized query for the underlying database, or if it's basically just concatenating all the arguments into one big string and passing the query to the datab... | OTL author's response to my e-mail:
OTL passes queries with placeholders into the DB API layers. The naming conventions for actual bind variables are different for different DB types. Say, for Oracle,
SELECT * FROM staff WHERE fname=:f_name<char[20]>
will be translated into:
SELECT * FROM staff WHERE fname=:f_name
pl... |
3,150,108 | 3,150,262 | Listview flickers on Win32 dialog when removing and re-adding all items and all columns | Consider a plain Win32 dialog with listview control (in report mode) written in C++. Upon a certain event all items and all columns are deleted and new columns and items are created. Basically, as content changes, columns are automatically generated based on content.
When old items/columns are removed and new ones adde... | The default list control painting is pretty flawed. But there is a simple trick to implement your own double-buffering technique:
CMyListCtrl::OnPaint()
{
CRect rcClient;
GetClientRect(rcClient);
CPaintDC dc(this);
CDC dcMem;
dcMem.CreateCompatibleDC(&dc);
CBitmap bmMem;
bmMem.CreateCompat... |
3,150,268 | 3,150,326 | Creating `char ***data`? | I have to create a 3-Dimensional array, wich gets allocated at object creation. I've done such stuff before with normal arrays.
typedef unsigned char byte; // =|
byte ***data;
| If you're using C++, I strongly advise you using std::vector instead of raw arrays.
Something like:
std::vector<std::vector<std::vector<char> > > data(3, std::vector<std::vector<char> >(3, std::vector<char>(3, 0)));
Will create a 3x3x3 array of chars, all initialized to 0.
You can then access the items the same way yo... |
3,150,310 | 3,150,330 | C++ virtual override functions with same name | I have something like that (simplified)
class A
{
public:
virtual void Function () = 0;
};
class B
{
public:
virtual void Function () = 0;
};
class Impl : public A , public B
{
public:
????
};
How can I implement the Function () for A and the Function() for B ?
Visual C++ lets you only define t... | You cannot use qualified names there. I you write void Function() { ... } you are overriding both functions. Herb Sutter shows how it can be solved.
Another option is to rename those functions, because apparently they do something different (otherwise i don't see the problem of overriding both with identical behavior)... |
3,150,477 | 3,150,521 | C++ and C# interoperability : P/Invoke vs C++/CLI | In the course of finding a way to interoperate between C# and C++ I found this article that explains about P/Invoke.
And I read a lot of articles claiming that C++/CLI is not exact C++ and requires some effort to modify from original C++ code.
I want to ask what would be the optimal way when I have some C++ objects (c... | I would not recommend rewritng your C++ library into C++/CLI. Instead, I would write a C++/CLI wrapper that you can call from C#. This would consist of some public ref class classes, each of which probably just manages an instance of the native class. Your C++/CLI wrapper just "include the header, link to the lib" to u... |
3,150,563 | 3,159,074 | adding a document to a Lucene index causes crash | i'm trying to index an mp3 file with only one ID3 frame. using CLucene and TagLib. the following code works fine:
...
TagLib::MPEG::File file("/home/user/Depeche Mode - Personal Jesus.mp3");
if (file.ID3v2Tag()) {
TagLib::ID3v2::FrameList frameList = file.ID3v2Tag()->frameList();
lucene::document::Document *doc... | This is a scope issue - by the time you call writer->addDocument, the fields you added to it are freed. Use this code instead:
document->add(* new lucene::document::Field(fieldName, fieldValue, true, true, true, false));
You may want to look at cl_demo and cl_test to see some code samples.
|
3,150,581 | 3,151,794 | UnicodeString to char* (UTF-8) | I am using the ICU library in C++ on OS X. All of my strings are UnicodeStrings, but I need to use system calls like fopen, fread and so forth. These functions take const char* or char* as arguments. I have read that OS X supports UTF-8 internally, so that all I need to do is convert my UnicodeString to UTF-8, but I do... | call UnicodeString::extract(...) to extract into a char*, pass NULL for the converter to get the default converter (which is in the charset which your OS will be using).
|
3,150,700 | 3,151,243 | Need meta-programming magic to define a mother lode of bit fields in an error-free way | The goal is to control which types of users are allowed to perform which operations at the UI level. This code has been in place for a while; I just want to improve it a bit.
The file which I am trying to improve should probably be auto-generated, but that would be too big of a change, so I seek a simpler solution.
A f... | Tested example using Boost.PreProcessor:
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/comparison/greater.hpp>
#include <boost/preprocessor/comparison/less.hpp>
#include <boost/preprocessor/debug/assert.hpp>
#include <boost/preprocessor/seq/size.hpp>
#define CHECK_SIZE(size) \
BOOST_P... |
3,150,844 | 3,150,925 | strange object serialization problem in file parsing | I have a strange problem with object serialization.
in the file documentation it states as following
The lead in starts with a 4-byte tag
that identifies a TDMS segment
("TDSm"). The next four bytes are used
as a bit mask in order to indicate
what kind of data the segment
contains. This bit mask is referred... | You seem to be just reading and writing the binary data in the struct directly.
Generally the compiler will align structure data for performance, so when it's a single struct there's a hidden 32-bit pad between vernum and nextSegmentOff to align nextSegmentOff. When it's split into two structures there's no such extra ... |
3,150,942 | 3,150,965 | Is "delete this" allowed in C++? | Is it allowed to delete this; if the delete-statement is the last statement that will be executed on that instance of the class? Of course I'm sure that the object represented by the this-pointer is newly-created.
I'm thinking about something like this:
void SomeModule::doStuff()
{
// in the controller, "this" obje... | The C++ FAQ Lite has a entry specifically for this
https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
I think this quote sums it up nicely
As long as you're careful, it's OK for an object to commit suicide (delete this).
|
3,150,961 | 3,151,137 | Yet another Dynamic Array vs. std::vector, but | ...well, I got strange results!
I was curious about the performance of std::vector vs. that of a dynamic array. Seeing as there are many questions on this subject already, I wouldn't have mentioned it if I didn't constantly get these 'contradictory' results: vector<int> is somehow faster than a new int[]! I always thou... | My wild guess is that the OS isn't allocating physical memory until it's first accessed. The vector constructor will initialise all the elements, so the memory will be allocated by the time you've started timing. The array memory is uninitialised (and possibly unallocated), so the time for that might include the alloca... |
3,151,002 | 3,151,175 | Detect DVD Burners in Windows | Is there anyway to dectect available DVD burners in a windows system using c++? I know how to detect all available drives but I would like to be able to detect which ones have the ability to burn DVD media.
| What you want is the Image Mastering API (IMAPI). To list the available devices you can use IDiscMaster::EnumDiscRecorders.
|
3,151,114 | 3,151,266 | Text Editing Question | I'm traversing a text file line by line adjusting the text so that the file eventually will match the syntax required to be run on a MIPS simulator (MARS). My issue is that whenever I see a line with the string "blezl" in it, I want to do several things. First I need to insert some lines of text following the line cont... | 80k lines isn't large enough that you can't load it into RAM. Searches are fairly fast once you have data in ram.
If you are concerned about performance, you could make a b-tree to store lines based on label. This would give you log(n) search time for each line you need to find.
|
3,151,276 | 3,151,289 | Cyclical Linked List Algorithm | I have been asked recently in a job interview to develop an algorithm that can determine whether a linked list is cyclical. As it's a linked list, we don't know its size. It's a doubly-linked list with each node having 'next' and 'previous' pointers. A node can be connected to any other node or it can be connected to i... | The general solution is to have 2 pointers moving at different rates. They will eventually be equal if some portion of the list is circular. Something along the lines of this:
function boolean hasLoop(Node startNode){
Node slowNode = startNode;
Node fastNode1 = startNode;
Node fastNode2 = startNode;
whi... |
3,151,320 | 3,151,364 | can not count array elements after passing as argument | I am having issues counting the array elements after passing it into an arguement
void GXDX::LoadMesh(GXVector vertices[], UINT indices[] = NULL)
{
D3D10_BUFFER_DESC bufferDesc;
UINT numVerts = sizeof(vertices)/sizeof(GXVector);
bufferDesc.Usage = D3D10_USAGE_DEFAULT;
bufferDesc.ByteWidth = sizeof(GXV... | Yes, you are passing the array correctly; however, in C (and C++), arrays don't contain their size. So you need to pass the size of the array as a separate parameter. Arrays effectively decay into pointers when passed as a parameter into a function, so sizeof(vertices) will give you the size of the pointer type, not th... |
3,151,393 | 3,151,405 | Unclear about `delete` and pointers | Say we have a piece of code:
//...
class A
//...
A* myA = new A();
A* myPointerToMyA = myA;
delete myA;
delete myPointerToMyA; // this is wrong, no?
//...
The last line does the exact same thing as the one above it, correct? So I would now be deleteing an invalid/NULL pointer?
I understand this may be a stupid questio... | You are correct.
So I would now be deleteing an invalid/NULL pointer?
Well, technically it's only invalid, because nothing was set to NULL. It's ok to delete a NULL pointer.
|
3,151,440 | 3,151,520 | OpenMP, C++ and Iterators | To loop over elements of a container, I would typically use an iterator, like so:
container<type> myContainer;
// fill up the container
container<type>::iterator it;
for(it=myContainer.begin(); it!=myContainer.end(); ++it) {
//do stuff to the elements of the container
}
Now, if I want to parallelize the loop using ... | Parallelization for STL iterators is allowed only in OpenMP 3.0. Which version of OpenMP does your compiler supports?
|
3,151,464 | 3,151,498 | Why is the code printing the last std::cout? | using namespace std;
template<typename T>
int f(vector<T> &v){
return v.size();
}
template<typename T>
class B{
public:
int size(){
return v.size();
};
private:
vector<T> v;
};
int main(int argc, char** argv) {
B<string> b;
vector<string> v;
for(int i=0; i<f<string>(v)-1; i++)
... | vector's size() function returns a value of type size_t which is unsigned. So, if size() returns 0 and you subtract 1 from it, you're going to get a very large number rather than -1. That very large number will be greater than 0 and the condition i < v.size() - 1 will therefore be be true since i is 0.
EDIT:
I should p... |
3,151,495 | 3,151,574 | Why doesn't auto_ptr<T> have operator!() defined? | The Title pretty much sums up my question. Why can't the following be done to check for a null pointer?
auto_ptr<char> p( some_expression );
// ...
if ( !p ) // error
This must be done instead:
if ( !p.get() ) // OK
Why doesn't auto_ptr<T> simply have operator!() defined?
| Seems to be there was an error in its design. This will be fixed in C++0x. unique_ptr (replacement for auto_ptr) contains explicit operator bool() const;
Quote from new C++ Standard:
The class template auto_ptr is deprecated. [Note: The class template unique_ptr (20.9.10) provides a
better solution. —end note ]
So... |
3,151,649 | 3,151,787 | Processing command line argument | I've been working with OpenCV, and some of the example code I've seen uses the following to read in a filename. I understand that argc is the number of command line arguments that were passes, and argv is a vector of argument strings, but can someone clarify what each part of the following line does? I've tried searchi... | The example shows the use of the ternary operator.
const char* imagename = argc > 1 : argv[1] : "lana.jpg"
By ternary you can say that this expression has three members.
First member is a condition expression
Second member is the value that could be assigned to imagename if conditional expression is true.
Third member ... |
3,151,728 | 3,205,136 | Unresolved external symbols in compiling 32 bit application in Windows 64 | So I am trying to compile legacy app from 32 bit to 64 bit..
I re-compiled all of the libs it used and made it look into WIN SDK6.0A x64 bit for libs..
I am using:
Visual Studio Professional Edition 2008
Visual C++
dotNet Framework 3.5 SP1
Windows Server 2008R2
Windows SDK is 6.0A
Everythings finally coming up but I ... | So I finally figured it out, kinda...
It wasnt finding psapi.lib
In Project->Linker->Additional dependencies instead of just saying psapi.lib
I gave full path to it and it worked...
not really sure why it failed to find it before but oh well...
|
3,151,729 | 3,152,802 | boost program_options multiple values problem | So I'm working off one of the examples for Boost program_options library, and I wanted to try setting a default value for one of the multiple-values/ vector-values, but it doesn't seem to work. As I think is suggested here to work.
What I've modified is on about line 40:
po::options_description config("Configuratio... | For the "default_value" method, the first parameter is the real value that you wish your option to be, the second value being only the textual representation (for display in --help) when boost cannot infer it.
So, the solution to your problem is to write:
po::value< vector<string> >()->default_value(
vector<strin... |
3,151,790 | 3,151,825 | Why isn't the dropdown arrow drawn for an CMFCMenuButton? | I ran into this issue when trying to add a CMFCMenuButton to an existing MFC application. It worked properly, and even resized the button to accommodate the dropdown arrow. But it didn't draw the dropdown arrow, and when I hovered over the button, I saw the following debug output:
> Can't load bitmap: 42b8.GetLastErr... | The reason I posted this question is because I couldn't find any answers via Google. The closest I came when researching it was a couple hacks that didn't seem to be the real solution. After pouring over the NewControls example, I finally found the culprit.
At the bottom of the default .rc file for a project, there i... |
3,151,801 | 3,151,824 | Compare 2 elements of two arrays in C++ | I have two arrays each array has some values for instance:
int a[] = {1, 2, 3, 4};
int b[] = {0, 1, 5, 6};
now I need to compare the elements of the array (a) with elements in array (b)..
if is there any match the program should return an error or print "error there is a duplicate value" etc..
in the above situation... | If the arrays are this small, I would just do a brute force approach, and loop through both arrays:
for (int i=0;i<4;++i)
{
for (int j=0;j<4;++j)
{
if (a[i] == b[j])
{
// Return an error, or print "error there is a duplicate value" etc
}
}
}
If you're going to be dealing... |
3,151,851 | 3,151,897 | C++ template instantiation restrictions | I have a method foo in class C which either calls foo_1 or foo_2.
This method foo() has to be defined in C because foo() is pure virtual in BaseClass and I actually
have to make objects of type C. Code below:
template <class T>
class C:public BaseClass{
void foo() {
if (something()) foo_1;
else foo_2;
}
... | you could use boost.enable_if. something like this:
#include <boost/utility/enable_if.hpp>
#include <iostream>
struct T1 {
static const bool has_bar = true;
void bar() { std::cout << "bar" << std::endl; }
};
struct T2 {
static const bool has_bar = false;
};
struct BaseClass {};
template <class T>
class ... |
3,151,963 | 3,152,140 | Static check const char* contains spaces | Is there a way to check (assert) at compile time wether a const char* contains spaces or not?
Something like:
const char* cstr1 = "ok";
const char* cstr2 = "very bad";
check( cstr1 ); //OK
check( cstr2 ); //Fail to compile
The type is the same, but it may be possible to define some tricky template metaprogramming tec... | You can't use ordinary strings since their characters cannot be accessed by templates, but you can use MPL strings:
#include <boost/mpl/char.hpp>
#include <boost/mpl/string.hpp>
#include <boost/mpl/contains.hpp>
#include <boost/utility/enable_if.hpp>
typedef boost::mpl::char_<' '> space;
typedef boost::mpl::string<'o'... |
3,152,035 | 3,152,202 | Why are heaps in c++ implemented as algorithms instead of containers? | I was wondering why the heap concept is implemented as algorithms (make_heap, pop_heap, push_heap, sort_heap) instead of a container. I am especially interested is some one's solution can also explain why set and map are containers instead of similar collections of algorithms (make_set add_set rm_set etc).
| STL does provide a heap in the form of a std::priority_queue. The make_heap, etc., functions are there because they have uses outside the realm of the data structure itself (e.g. sorting), and to allow heaps to be built on top of custom structures (like stack arrays for a "keep the top 10" container).
By analogy, you ... |
3,152,241 | 3,152,296 | Case insensitive std::string.find() | I am using std::string's find() method to test if a string is a substring of another. Now I need case insensitive version of the same thing. For string comparison I can always turn to stricmp() but there doesn't seem to be a stristr().
I have found various answers and most suggest using Boost which is not an option in ... | You could use std::search with a custom predicate.
#include <locale>
#include <iostream>
#include <algorithm>
using namespace std;
// templated version of my_equal so it could work with both char and wchar_t
template<typename charT>
struct my_equal {
my_equal( const std::locale& loc ) : loc_(loc) {}
bool opera... |
3,152,265 | 3,152,425 | Why isn't this thread reading all data from the pipe consistently? | Anything wrong with this in general?
CallingFunction()
{
CreatePipe()
CreateMutex()
CreateThread( ThreadFunction )
while(there is data left to send)
{
WriteFile(send data in 256 byte chunks)
}
WaitForSingleobject() //don't return until ReadThread is done
return 0;
}
ThreadFunction()
{... | Expecting us to debug such an issue from pseudo code is not realistic. Use FlushFileBuffers to ensure all data in the pipe is written.
|
3,152,326 | 3,250,880 | Google Test: Parameterized tests which use an existing test fixture class? | I have a test fixture class which is currently used by many tests.
#include <gtest/gtest.h>
class MyFixtureTest : public ::testing::Test {
void SetUp() { ... }
};
I would like to create a parameterized test which also uses all that MyFixtureTest has to offer, without needing to change all my existing tests.
How do I... | The problem is that for regular tests your fixture has to be derived from testing::Test and for parameterized tests, it has to be derived from testing::TestWithParam<>.
In order to accommodate that, you'll have to modify your fixture class in order to work with your parameter type
template <class T> class MyFixtureBase... |
3,152,330 | 3,152,342 | Ambiguous pow() function | I am trying to make a simple call to the pow() function from math.h someihing similar to..
#include<math.h>
int main()
{
float v,w;
w=3.0;
v=pow(w,0.5);//i think this is 'float pow(float,float)'
return 0;
}
but visual studio says it's an error
1>c:\users\user\documents\visual studio 2008\projects\deo\d... | In the line:
v=pow(w,0.5);
w is a float and 0.5 is a double. You can use 0.5f instead.
|
3,152,372 | 3,158,286 | Boost : Error : 2 overloads have similar conversions | I'm basically brand new to using Boost. I'm trying to use a ptr_vector to handle some objects that I created.
Specifically I have defined a class Location which defines a particular node on a map (simple 2D game layout). I defined a ptr_vector to hold a set of Locations that have value to the calling function (nodes w... | That's not reproducible when using Boost 1.43 and VC2005. In order to try it out I added a dummy class Location (you didn't provide it with your code):
struct Location { Location(int, int) {} };
That makes me believe it's an issue with your class Location. Could you provide its definition?
|
3,152,567 | 3,152,602 | In C++ how can you create class instance w call to either a struct or nothing? | I'm creating a Class.
This class stores user preferences in a Struct.
When creating an instance of the class, I want the client to have the option of creating an instance with no preferences passed in or with a preferences struct passed in.
I can do this with pointers, but I wanted to know how I could do it by passing... | You point out the advantage of pointers over references, and how well pointers fit your situation, then announce you don't want to use them.
You can still get what you want. Write two overloads for your constructor. One takes a reference, the other takes no parameters and does what the other constructor did when it go... |
3,152,577 | 3,152,864 | A form that writes to excel | I was wondering what the easiest way to write a simple form program or web page that will output to a text file that can be opened in excel easily. I know how to write in C++ but I dont know any GUI and I wanted a simple form. I was thinking I could just write an HTML/PHP page but it has to be able to run without the i... | If you want a Windows based application, and you can code in C++, then possibly the simplest route is to get hold of Visual Studio (you can get the Express versions for free), and write something using your language of choice.
Basic GUI stuff in Visual Studio is simple enough. You can then write your output either to ... |
3,152,664 | 3,152,705 | C++ cast to array of a smaller size | Here's an interesting question about the various quirks of the C++ language. I have a pair of functions, which are supposed to fill an array of points with the corners of a rectangle. There are two overloads for it: one takes a Point[5], the other takes a Point[4]. The 5-point version refers to a closed polygon, wherea... | I don't think it's a good idea to do this by overloading. The name of the function doesn't tell the caller whether it's going to fill an open array or not. And what if the caller has only a pointer and wants to fill coordinates (let's say he wants to fill multiple rectangles to be part of a bigger array at different of... |
3,152,734 | 3,153,041 | Problem either adding to or traversing a linked list | I have a problem either adding to or traversing a linked list. The main item class is used by another class but I can add the correct number of these but it looks like when I add more data to the list the app no longer works.
I am not sure exactly where the error is. I know that when I try to traverse the list the appl... | It's very hard to tell what your code is trying to do. Unfortunately, the hard truth is, it's pretty far away from "working".
Here's a few hints:
Reconsider your classes. What is Item and ItemOccurrence? A linked list is a list. It has items. You should probably name it List and Item. If you want, you can do thi... |
3,152,927 | 3,152,959 | What's the most interesting wrong view people have on the difference between structure and class in C++? | What's the most interesting wrong view people have on the difference between structure and class in C++?
| For those who are interested in what the actual difference is, the default access specified for structs is public, and for classes it is private. There is no other difference.
See this related answer.
Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords ... |
3,153,001 | 3,153,100 | question about std::vector::end() | I recently finished fixing a bug in the following function, and the answer surprised me. I have the following function (written as it was before I found the bug):
void Level::getItemsAt(vector<item::Item>& vect, const Point& pt)
{
vector<itemPtr>::iterator it; // itemPtr is a typedef for a std::tr1::sh... | When you call erase(), that iterator becomes invalidated. Since that is your loop iterator, calling the '++' operator on it after invalidating it is undefined behavor. erase() returns a new valid iterator that points to the next item in the vector. You need to use that new iterator from that point onwards in your lo... |
3,153,012 | 3,153,044 | String handling in C++ | How do I write a function in C++ that takes a string s and an integer n as input and gives at output a string that has spaces placed every n characters in s?
For example, if the input is s = "abcdefgh" and n = 3 then the output should be "abc def gh"
EDIT:
I could have used loops for this but I am looking for concise a... | Copy each character in a loop and when i>0 && i%(n+1)==0 add extra space in the destination string.
As for Standard Library you could write your own std::back_inserter which will add extra spaces and then you could use it as follows:
std::copy( str1.begin(), str1.end(), my_back_inserter(str2, n) );
but I could say t... |
3,153,098 | 3,153,129 | C++ control order of static member's deallocation | I have a C++ program with a reference-counting smart pointer class. This class works by mapping pointers to reference counts in a static map:
map<ValueIntern*,unsigned int>& ValueRetainMapGetter(){
static map<ValueIntern*,unsigned int> m;
return m;
}
The issue that I've been having is that some static variable... | I'd recommend using boost::shared_ptr (or std::tr1::shared_ptr if it's in your tool chain) instead of rolling your own.
|
3,153,114 | 3,153,183 | How do I install and build against OpenSSL 1.0.0 on Ubuntu? | You can consider this a follow-up question to How do I install the OpenSSL C++ library on Ubuntu?
I'm trying to build some code on Ubuntu 10.04 LTS that requires OpenSSL 1.0.0.
Ubuntu 10.04 LTS comes with OpenSSL 0.9.8k:
$ openssl version
OpenSSL 0.9.8k 25 Mar 2009
So after running sudo apt-get install libssl-dev and ... | Get the 1.0.0a source from here.
# tar -xf openssl-1.0.0a.tar.gz
# cd openssl-1.0.0a
# ./config
# sudo make install
Note: if you have man pages build errors on modern systems, use make install_sw instead of make install.
This puts it in /usr/local/ssl by default
When you build, you need to tell gcc to look for the hea... |
3,153,141 | 3,153,309 | Defining a byte in C++ | In http://www.parashift.com/c++-faq-lite/intrinsic-types.html#faq-26.6, it is wriiten that
"Another valid approach would be to define a "byte" as 9 bits, and simulate a char* by two words of memory: the first could point to the 36-bit word, the second could be a bit-offset within that word. In that case, the C++ compil... | I think this is what they were describing:
The PDP-10 referenced in the second paragraph had 36-bit words and was unable to address anything inside of those words. The following text is a description of one way that this problem could have been solved while fitting within the restrictions of the C++ language spec (tha... |
3,153,155 | 3,155,944 | When setting the WA_DeleteOnClose attribute on a Qt MainWindow, the program crashes when deleting the ui pointer | I have set the WA_DeleteOnClose widget attribute in a MainWindow.
setAttribute(Qt::WA_DeleteOnClose);
However, whenever I close that main window, I get a segfault in its destructor, which only has delete ui;
In a nutshell, created a Qt4 GUI Application in Creator, added the setAttribute(Qt::WA_DeleteOnClose); to const... | Are you getting a segfault in its destructor the first time, or the second time? Remember that your main window destructor should run only once. That is to say that it should run either because of a stack unwind, or because of WA_DeleteOnClose, not both.
IIRC, Creator will put the main window on the stack of main(). T... |
3,153,169 | 3,153,197 | C++: new, memory understanding question | why doesn't this work:
Snippet 1:
int *a = new int[6];
(*a)[0]=1;
while this is working
Snippet 2:
int myint = 0;
int *ptr = &myint;
*ptr=1;
I know that if i use a[0]=1 in snippet 1 it will work. But for me that makes no sense, cos for me it looks that a[0]=1 means: put value 1 to adress a[0]. In other words I put ... | You should just be using *a not (*a)[0].
Remember 'a' is a pointer. A pointer is an address.
*a = a[0] or the first integer
*(a + 1) = a[1] or the second integer
'a' is not a pointer to an array. It is a pointer to an integer. So, *a does not hand an array back to you for the [ ] to operate on.
What is confusing yo... |
3,153,385 | 3,160,259 | Controlling the work of worker threads via the main thread | Hey I am not sure if this has already been asked that way. (I didn´t find anwsers to this specific questions, at least). But:
I have a program, which - at startup - creates an Login-window in a new UI-Thread.
In this window the user can enter data which has to be verified by an server.
Because the window shall still be... | I don´t know wether this is good style or not (anwsering Your own question):
But I think I go with Event Objects and two queues (one for the connection between Client and Connection, and one to communicate Client and UI)...
|
3,153,426 | 3,153,488 | OpenGL pausing problems | I have the following function that is used as the glutKeyboardFunc function parameter:
void handleKeypress(unsigned char key, //The key that was pressed
int x, int y) { //The current mouse coordinates
switch (key) {
case 27: //Escape key
exit(0); //Exit the program
}
... | Create a boolean variable for each key (preferably an array). Then use KeyDown/KeyUp instead of KeyPress (i believe in GLUT its something like KeyboardUpFunc and KeyboardFunc, but cant remember now). On KeyDown, set the appropriate variable to true, on KeyUp, set it to false. Now you probably have an Idle function or s... |
3,153,548 | 3,153,588 | C++: Struct initialization and maps | This works fine:
#include <iostream>
#include <map>
using namespace std;
struct Bar
{
int i;
int f;
};
int main()
{
map<int, Bar> m;
Bar b;
b.i = 1;
b.f = 2;
m[0] = b;
}
But if I want to make it a little more concise, I get errors:
int main()
{
map<int, Bar> m;
m[0] = {... | You can add a constructor:
In this situation I would say it is better than the fancy new initializer as it actually lets the maintainer see what type is being put in the map without having to go and look for it.
struct Bar
{
Bar(int anI,int aJ)
:i(anI), j(aJ)
{}
int i;
int j;
}
.....
m[0] = Bar(... |
3,153,725 | 3,153,802 | typedef struct : Default Initialization | typedef struct foo
{
bool my_bool;
int my_int;
} foo;
In the example above I understand that my_bool will be initialized randomly to either true or false but what about my_int? I assumed that my_int would be default initialized to 0 but that seems not to be the case.
Defining structs in this way appears to be... | Types don't get "initialized". Only objects of some type get initialized. How and when they get initialized depends on how and where the corresponding object is defined. You provided no definition of any object in your question, so your question by itself doesn't really make much sense - it lacks necessary context.
For... |
3,153,939 | 3,154,143 | Properly writing to a nonblocking socket in C++ | I'm having a strange problem while attempting to transform a blocking socket server into a nonblocking one. Though the message was only received once when being sent with blocking sockets, using nonblocking sockets the message seems to be received an infinite number of times.
Here is the code that was changed:
return :... | I do not believe that this code is really called only once in the "non blocking" version (quotes because it is not really non-blocking yet as Maister pointed out, look here), check again. If the blocking and non blocking versions are consistent, the non blocking version should return total_sent (or size). With return 0... |
3,154,095 | 3,154,178 | Techniques to prevent overdraw (OpenGL) | I'm drawing lots of semi transparent polygons. My scene is 2D and uses 2f verticies. I can't use the depth buffer since it wont help because of alpha blending. What are some other techniques to reduce overdraw since this is what is crippling my application, not polygon counts since I use VBO's.
| First off, how have you determined that overdraw is your problem? Without more information about what exactly you are drawing, it is quite hard to guess how to draw it faster. Speaking generally, the key to avoiding over draw is to avoid drawing anything that isn't required. So, if you have a 2D side scroller game ... |
3,154,170 | 3,154,256 | Combine two constant strings (or arrays) into one constant string (or array) at compile time | In C# and Java, it's possible to create constant strings using one or more other constant strings. I'm trying to achieve the same result in C++ (actually, in C++0x, to be specific), but have no idea what syntax I would use to achieve it, if such a thing is possible in C++. Here's an example illustrating what I want t... | In C++0x you can do the following:
template<class Container>
Container add(Container const & v1, Container const & v2){
Container retval;
std::copy(v1.begin(),v1.end(),std::back_inserter(retval));
std::copy(v2.begin(),v2.end(),std::back_inserter(retval));
return retval;
}
const std::vector<int> v1 = {1,2,3... |
3,154,506 | 3,154,912 | Best way to make a QToolBar of "checkable" QToolButtons where only one of the buttons can be checked at a time? | I'm looking to make a QToolBar with a few actions in it, each of which is "checkable" (that is, I call setCheckable(true) on each action after creating it, which leaves the button in the down state after clicking it).
The only way I can think of "unchecking" the other buttons is to hook into each button's triggered sig... | Create a QActionGroup and let it be the parent of your actions. This QActionGroup will maintain the states of its children.
QActionGroup *anActionGroup = new QActionGroup(yourParentWidget);
QAction* action1 = new QAction("Action 1", anActionGroup);
QAction* action2 = new QAction("Action 2", anActionGroup);
QAction* act... |
3,154,620 | 3,154,707 | How to find out DC's dimensions? | Let's say I have a handle to device context (naturally, in Windows environment):
HDC hdc;
How can I get the width and height of it?
| A device context (DC) is a structure that defines a set of graphic objects and their associated attributes, and the graphic modes that affect output.
By width and height I'm guessing you are referring to the bitmap painted ?
If so then i guess you can try the following :
BITMAP structBitmapHeader;
memset( &structBitma... |
3,154,636 | 3,155,449 | Zooming into the mouse position with a translation? | To zoom into the mouse position I was using:
glTranslatef(current.ScalePoint.x,current.ScalePoint.y,0);
glScalef(current.ScaleFactor,current.ScaleFactor,current.ScaleFactor);
glTranslatef(-current.ScalePoint.x,-current.ScalePoint.y,0);
so basically I translate to the new origin (the mouse position) then scale ... | It is more safe (and also for code reuse) to un-project the mouse coordinate point (from window coordinates to model coordinates) first even though you know how projection is done.
You can use the following function:
void unProject(int ix, int iy, int &ox, int &oy)
{
// First, ensure that your OpenGL context is the s... |
3,154,672 | 3,154,766 | How to get parent node of element using tinyxml | Is there a way to get a parent node from a TiXmlElement? For example...
TiXmlElement *parent = child->ParentElement( "someName" );
If you can't do this in tinyxml, are there any other xml parsers that allow this?
| TinyXML's TiXmlElement is derived from TiXMLNode which contains a method called Parent().
|
3,154,730 | 3,154,886 | How does char *blah = "hello" work? | When you make a string out of char pointers how does this work?
char *name = "ben";
Is this 'hidden' pointer arithmetic?
| There isn't any hidden pointer arithmetic, but I suspect you want a more detailed answer than that.
If you have a function:
void foo() {
char * bar = "Hello World";
}
There are actually two chunks of memory that come in to play:
The first is where the 12 bytes are used to store "Hello World" (1 byte for each lett... |
3,154,759 | 3,155,531 | Getting the points from wglUseFontOutlines? | I'm making a vector application for Windows. Right now i'm using wglUseFontOutlines to generate display lists which wrks well, except I would like to be able to let the user remodel the font. I would also like to use VBO's instead of DL's for this. Does Microsoft provide a way to get the points for this, or atleast the... | You may use the Win32 API GetPath , it works really nice and it returns lines and bezier pieces.
|
3,155,021 | 3,155,035 | Consistenty header file names between C++ libraries | In my project I use two libraries, v8 and boost. Boost uses the .hpp extension for its headers, while v8 uses the .h extension for its headers.
In the end of day, my source code starts like that:
#include "v8.h"
#include "boost/filesystem.hpp"
...
In other question I asked about this subject, the general answer was th... | Don't worry about the inconsistency, it doesn't matter. Too much time is often spent obsessing about such details, and everyone is guilty of it.
Just be consistent with your own coding standards.
You'll eventually use some 3rd party library or several that use different conventions than you. There's nothing you can ... |
3,155,044 | 3,155,068 | sorting strings in a file | I need a solution for sorting of unix pwd file using C++ based on the last name. The format of the file is username, password, uid, gid, name, homedir, shell. All are seperated by colon delimiters. The name field contains first name follwed by last name both seperated by space I am able to sort the values using map an... | Since the format of the file is fixed
username, password, uid, gid, first name(space)lastname, homedir, shell
Maintain a std::map with key value as string (which will contain last name, and value as line number
Start reading the file line by line, extract the last name (Split the line by "," and then split fifth extra... |
3,155,054 | 3,155,085 | C++ User Input When Initializing Values | I'm a student in an introductory C++ course. For one of our past assignments we have had to create a simple program to add fractions. Each new lab is just an application of new skills learned to making the same program. Now I need to make one using objects from a class definition.
After tooling with a multiplying examp... | Renaming your Multi method Add would avoid a lot of potential confusion and is highly recommended.
As for input, what's wrong with (e.g.) std::cin >> numer >> denom (with numer and denom declared as integers) for example? Then of course you can pass them to the Init method, etc.
(You'll probably also want to do prompt... |
3,155,133 | 3,155,206 | Application crashing in WInXp and WIn2k3 but not in Vista or Win7 after applying KB981793 hot Fix from Microsoft | I have an existing application developed in VC++ 6.0 which has been installed in many customer sites throughout the world.
This application was working fine until sometime back when the Microsoft KB981793 hot fix was applied. This hotfix has changes related to Timezones and was crashing a crash due to an array overflo... | For XP and 2K3, Microsoft specifies minimum service pack levels as prerequisites. For Vista and 7 they don't require prerequisites even though service packs exist for Vista.
|
3,155,224 | 3,155,308 | C++ Can I print the content of 1 or 2 dim array using Visual Studio's Command window? | C++ Can I print the content of 1 or 2 dim array using Visual Studio's Command window? I guess it comes down to whether a "command window" support some kind of loop and print (?) syntax or not.
| The visual studio command window is used to enter commands to the development environment, not for code execution. For example you could type 'open' so that VS shows the Open Dialog.
|
3,155,257 | 3,155,357 | GDB - What is the mysterious Assembly code? | Dump of assembler code for function main:
0x0804833e <+0>: push %ebp
0x0804833f <+1>: mov %esp,%ebp
0x08048341 <+3>: sub $0x8,%esp
0x08048344 <+6>: and $0xfffffff0,%esp
0x08048347 <+9>: mov $0x0,%eax
0x0804834c <+14>: add $0xf,%eax
0x0804834f <+17>: add ... | Allow me to comment this for you.
0x0804833e <+0>: push %ebp ; Establish standard
0x0804833f <+1>: mov %esp,%ebp ; stack frame record
0x08048341 <+3>: sub $0x8,%esp ; Make room for locals
0x08048344 <+6>: and $0xfffffff0,%esp ... |
3,155,277 | 3,155,287 | Cannot dynamic_cast void* to templated class | The exact error I'm getting is:
Cannot dynamic_cast 'object' (of type 'void*') to type 'class udDator(int)*'
(source is not a pointer to a class)
This is happening inside an overridden operator delete. I'm attempting to create a templated memory management class that can inherit into any other class, managing memory t... | Dynamic cast requires polymorphic behavior, which void does not have. Use a static_cast instead.
|
3,155,377 | 3,155,385 | Equivalent asm code for C/C++ codes |
Possible Duplicate:
How do you get assembler output from C/C++ source in gcc?
Hello out there!
I have a C and C++ source code that I wanted to see in assembly code. How can I produce an equivalent asm codes for those? What tools should I use? Or is it already possible in using tools such as the gcc compiler? Then wh... | gcc -S x.c
This should produce the assembly that gcc thinks is equivalent to your code. Beware though, the optimizer can do some very tricky things which may be hard to see are functionally equivalent to your code. Especially in c++ where the optimizer is so dependent on inlining and stuff like that.
From the gcc man ... |
3,155,448 | 3,155,607 | Eclipse plugin for generating UML diagram from c++ code | Is there any eclipse plugin that can generate UML/Class Diagram from C++ source code?
| From the list of UML tools, I only see commercial UML editors (with C++ as one of the language reverse engineered), like:
Enterprise Architect
Magic Draw
Modelio
In other word, I don't know of a open-source project offering C++ reverse engineered UML diagrams.
nrs mentions in the comments, from the Modelio Wikipedia... |
3,155,680 | 3,155,706 | Is there a way to free only a part of the dynamically allocated array in C\C++ (shrink existing array)? | In a program I allocate a huge multidimensional array, do some number-crunching, then only the first part of that array is of further interest and I'd like to free just a part of the array and continue to work with the data in the first part. I tried using realloc, but I am not sure whether this is the correct way, giv... | Yes, if you allocate with malloc, you can resize with realloc.
That said, realloc is allowed to move your memory so you should be prepared for that:
// Only valid when shrinking memory
my_array = realloc(my_array, *new_size);
Note that if you are growing memory, the above snippet is dangerous as realloc can fail and r... |
3,155,743 | 3,155,980 | Good IMAP library for a Mac application | I am looking for a nice library that can talk to GMail from a Mac application. Really, I am thinking about writing a GMail application for the Mac. Thunderbird and Mail.app just don't cut it for me.
Anyway, the library should be written in C, C++ or Obj-C or at least have interfaces for those languages. Of course, anyt... | I think vmime should work for this.
|
3,155,782 | 3,155,879 | What is the difference between WM_QUIT, WM_CLOSE, and WM_DESTROY in a windows program? | I was wondering what the difference between the WM_QUIT, WM_CLOSE, and WM_DESTROY messages in a windows program, essentially: when are they sent, and do they have any automatic effects besides what's defined by the program?
| They are totally different.
WM_CLOSE is sent to the window when it is being closed - when its "X" button is clicked, or "Close" is chosen from the window's menu, or Alt-F4 is pressed while the window has focus, etc. If you catch this message, this is your decision how to treat it - ignore it, or really close the window... |
3,156,125 | 3,163,833 | Is there any reliable API to Get Windows Folder in Windows? | Is there any reliable API to Get Windows Folder in Windows in C++?
I am using the following way, however it failed.
BOOL CQUserInfoHelper::GetWindowsPath(CString& strWindowsPath)
{
TCHAR windowsPathTemp[MAX_PATH];
int nSize = MAX_PATH;
::GetWindowsDirectory(
windowsPathTemp,
... | Try This -
const DWORD dwBufferLength = 65537;
CStringW strBuffer;
if (!::GetCurrentDirectory( dwBufferLength ,
strBuffer.GetBuffer(dwBufferLength)) )
return L"";
...
strBuffer.ReleaseBuffer();
|
3,156,455 | 3,156,529 | Difference in memory allocation in WIn 7/Vista compared to WinXP/Win2k3 in following code | I have the following piece of code. This is written for getting the list of timezones from registry and populating into an array. This piece of code works fine in Win7 and Vista OS but not in WinXp and Win2k3.
The reason is because of the size of array getting overflown. I have defined only 100 elements. However there... | Exception is raised when application tries to read/write a piece of memory that is not in it's address space. In one case after the array there was addressed memory, in other there wasn't. This is random. And yes, various allocation algorithm will lead to various results but this is only one element causing randomness.... |
3,156,501 | 3,156,535 | Make any class reference counted with inheritance? | In my new project I wish to (mostly for to see how it will work out) completely ban raw pointers from my code.
My first approach was to let all classes inherit from this simple class:
template
class Base
{
public:
typedef std::shared_ptr ptr;
};
And simple use class::ptr wherever I need a ... | You may want to take a look at enable_shared_from_this.
On another note, when using shared_ptr, you need to be aware of the possibility of circular references. To avoid this, you can use weak_ptr. This means you will need some way to distinguish between the two of them, so simply having a typedef class::ptr may not suf... |
3,156,597 | 3,156,660 | Override or remove an inherited constructor | Here is some C++ code:
#include <iostream>
using namespace std;
class m
{
public:
m() { cout << "mother" << endl; }
};
class n : m
{
public:
n() { cout << "daughter" << endl; }
};
int main()
{
m M;
n N;
}
Here is the output:
mother
mother
daughter
My problem is that I don't want the m's... | AFAIK, you cannot remove inherited constructor.
The problem in your example comes from incorrect class design.
Constructor is normally used for allocating class resources, setting default values, and so on.
It is not exactly suitable to be used for outputting something.
You should put
n() { cout << "daughter" << endl;... |
3,156,623 | 3,156,695 | Software product pricing/cost estimation | I always had trouble with estimating cost/price of finished software (or programming work), so here are two questions about it.
question 1:
You're asked to write a piece of code for cash (all rights to the code belongs to buyer once you're done). You know approximate number of hours it will take (+-25%), and approxim... | You can find some interesting insights gathered in a (free) book of Neil Davidson: http://www.neildavidson.com/dontjustrollthedice.html
|
3,156,778 | 3,156,822 | No matching function for call to operator new | I'm trying to wrap a class from a library I'm using in Lua. Specifially, I'm trying to wrap the color class from SFML. The full source for the color class can be seen here and here.
This is the function that's that I'm failing in.
int SFColor_new(lua_State* L)
{
// omitting part where I set r, g, b, and a
new... | To use the standard placement form of new you have to #include <new>.
The form of new that you are using requires a declaration of void* operator new(std::size_t, void*) throw();.
You don't have to #include <new> to use non-placement new.
|
3,156,841 | 3,158,112 | boost::filesystem::rename: Cannot create a file when that file already exists | I'm renaming a file using boost::filesystem, and sometimes the target file will exist. According to the boost documentation here:
http://www.boost.org/doc/libs/1_42_0/libs/filesystem/doc/reference.html#Non-member-functions
template
void rename(const Path1& from_p, const
Path2& to_p); Requires:
Path1::external_s... | Looks like it was fixed, but only in the sandbox "V3" version of Boost.Filesystem, which is not in the mainline Boost releases yet.
I tested on Boost 1.43.0 on Linux with the same results - in fact the bug report points out the offending code, which explicitly checks for existence on POSIX and throws the exception. It... |
3,156,852 | 3,156,884 | Why would I want to start a thread "suspended"? | The Windows and Solaris thread APIs both allow a thread to be created in a "suspended" state. The thread only actually starts when it is later "resumed". I'm used to POSIX threads which don't have this concept, and I'm struggling to understand the motivation for it. Can anyone suggest why it would be useful to create a... |
To preallocate resources and later start the thread almost immediately.
You have a mechanism that reuses a thread (resumes it), but you don't have actually a thread to reuse and you must create one.
|
3,157,098 | 3,157,112 | Whats the right approach to return error codes in C++ | I'm using error codes for handling errors in my c++ project. The problem is how to return error codes from a function which is supposed to return some variable/object.
consider this:
long val = myobject.doSomething();
Here, myobject is an object of some class. If doSomething function encounters some error condition t... | You can pass variable as reference and return error code in it.
|
3,157,126 | 3,157,149 | The inner depths of PHP | I've been studying Visibility issue in PHP (public, private, protected) and wondered how is this sort of "dom-building" is implemented in PHP? I mean there should be some kind of algorithm that PHP uses to go through all your classes and establish relations between them. Not sure if it is called "dom-building" though, ... | PHP does not pass through all your classes and establish relations between them. Only at run-time, when you call a method on another class, PHP checks whether that method is accessible (i.e. public or in some cases protected).
|
3,157,212 | 25,965,304 | WH_JOURNALRECORD hook in Windows (C++) - Callback never called. | The following code has been giving me some troubles for the past few hours.
I'm trying to write a small program (based on some tutorials from the web), that uses a WH_JOURNALRECORD windows hook to log keystrokes.
Main code:
#include "StdAfx.h"
#include <tchar.h>
#include <iostream>
#include <windows.h>
using std::cout... | The answer, as per the link in the edited question:
http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx
The application needs to run with administrative privileges.
The application must be run from (a sub... |
3,157,323 | 3,157,377 | How can I simplify this binary-tree traversal function? | template<typename T>
void traverse_binary_tree(BinaryTreeNode<T>* root,int order = 0)// 0:pre, 1:in , 2:post
{
if( root == NULL ) return;
if(order == 0) cout << root->data << " ";
traverse_binary_tree(root->left,order);
if(order == 1) cout << root->data << " ";
traverse_binary_tree(root->right,o... | No.
Kidding. I think it looks pretty efficient.
I would enum the order values, for readability.
...
enum TOrder {ORDER_PRE, ORDER_IN, ORDER_POST};
template<typename T>
void traverse_binary_tree(BinaryTreeNode<T>* root,TOrder order = ORDER_PRE) {
...
|
3,157,347 | 3,157,664 | Visual Studio solutions in Qt Creator | I am using Qt 4.5 and having Qt Creator as the IDE. I am quite comfortable with it. I know we can open the .pro files (from the Qt Creator) in the Visual Studio IDE. But how about the reverse? i.e How can I open a visual studio Qt solution (.sln) in Qt Creator? Is it possible or I have to create a pro file again for th... | You can install Visual Studio Add-in of Qt, then in Visual Studio, Qt menu will appear.There is an export option to create .pro files.
Edit: Detailed Information
|
3,157,454 | 3,157,541 | C++: Fill array according to template parameter | Essentially, the situation is as follows:
I have a class template (using one template parameter length of type int) and want to introduce a static array. This array should be of length length and contain the elements 1 to length.
The code looks as follows up to now:
template<int length>
class myClass{
static int ar... | Use "static constructor" idiom.
// EDIT 2
#include <iostream>
template<int length>
class myClass {
public:
typedef int ArrayType[length];
static struct StaticData {
ArrayType array;
StaticData()
{
for (int i = 0; i < length; i++) array[i] = i;
}
}
static_da... |
3,157,684 | 3,157,761 | C++ char * pointer passing to a function and deleting | I have a the following code:
#include <iostream>
using namespace std;
void func(char * aString)
{
char * tmpStr= new char[100];
cin.getline(tmpStr,100);
delete [] aString;
aString = tmpStr;
}
int main()
{
char * str= new char[100];
cin.getline(str,100);
cout<< str <<endl;
func(str);
... | Because the second cout will print what is pointed by str. And str, the pointer, in your main function will have the same value before and after the call to func.
Indeed, in the func function, you are changing the value of the aString variable. But this is another variable than str in main.
If you want the value of str... |
3,157,786 | 3,158,607 | QGraphicsView/QGraphicsScene rendering question | I am using QGraphicsScene/QGraphicsView pair in my application.
I had subclassed them for my purpose. The code snippet that generate the pair is below:
itsScene = new QGraphicsScene;
itsView = new QGraphicsView;
itsView->setParent(itsCanvas);
itsView->setGeometry(20,20,1700,720);
itsView->setBackgroundBrush(Qt::black)... | The negative coordinates may be the cause. QGraphicsScene calculates its bounding rect from combining the bounds of all items in it.
If you know your scene bounds, call setSceneRect to fix it down to a known rect. This way graphics items placed out of the bound will not cause the scene to expand beyond what you want.
|
3,157,938 | 3,158,027 | in gcc how to force symbol resolution at runtime | My first post on this site with huge hope::
I am trying to understand static linking,dynamic linking,shared libraries,static libraries etc, with gcc. Everytime I try to delve into this topic, I have something which I don't quite understand.
Some hands-on work:
bash$ cat main.c
#include "printhello.h"
#include "printb... | Any linker (gcc, ld or any other) only resolves links at compile-time. That is because the ELF standard (as most others) do not define 'run-time' linkage as you describe. They either link statically (i.e. lib.a) or at start-up time (lib.so, which must be present when the ELF is loaded). However, if you use a dynamic... |
3,158,280 | 3,160,439 | Why do I get segfaults when declaring a struct globally or extern? | I have a struct defined in a header as follows:
#define LC_ERR_LEN 300
typedef struct dLC_ERRMSG {
short nr;
short strategy;
char tx[LC_ERR_LEN];
} LC_ERRMSG;
Which I use in my code as such:
LC_ERRMSG err;
char *szError;
szError = strerror(sStatus);
snprintf(err.tx,LC_ERR_LEN," %s - %s",szFilename,szError);
/... | Your linker can simply throw away the symbols, which it believes are not used (the GNU linker does so). In this case you can explicitly link the object file with that symbol.
With C++ you can not control the order of initialization of global objects defined in other compilation units without any additional efforts (see... |
3,158,833 | 3,158,866 | C++: how can I write a program to read integers from a file? | When I use the code recommended in the book, I get an error. I am using NetBeans 6.8 for Mac.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
int number;
inputFile.open("MacintoshHD/Users/moshekwiat/Desktop/random.txt");
inFile >> number;
co... | Replace inFile with inputFile.
|
3,158,922 | 3,158,955 | Reverse iterator won't compile | I'm trying to compile a reverse iterator but my attempts to do so give a horrid mess. The minimal example of the code is...
#include <iostream>
#include <vector>
#include <algorithm>
class frag {
public:
void print (void) const;
private:
std::vector<int> a;
};
void frag::print (void) const
{
... | You need to use const_reverse_iterator (print is a const function so a is const) and a.rbegin() and a.rend() rather than begin() and end().
|
3,159,225 | 3,159,482 | What's the language for Socket Server | What’s the best language and IDE to develope socket server?
I want a language I can learn quickly that will work on an
enterprise level. Please set me up with some good resources:)
Thanks
RECOMMENDED LANGUAGES
'I only know Flash and scripting languages'
• JAVA
• C languages and VB++
• PHP
I’m tring to get my Flash ani... |
What’s the best language and IDE to
develope socket server?
Any language that supports sockets programming (almost anything). The question is a bit simplistic.
I want a language I can learn quickly
that will work on an enterprise level.
You can learn quickly most languages, but to become proficient in them may ... |
3,159,332 | 3,159,365 | Windows Service with GUI monitor? | I have a C++ Win32 application that was written as a Windows GUI project, and now I'm trying to figure out to make it into a Service / GUI hybrid. I understand that a Windows Service cannot / should not have a user interface. But allow me to explain what I have so far and what I'm shooting for.
WHAT I HAVE NOW is a w... | You can't do this as a service.
You'll need to make your Windows Service as a normal service application. This will startup on system startup, and run the entire time the system is up.
You'd then make a completely separate GUI application, which "talks" to the service. This can be set to run when a user logs in, in t... |
3,159,357 | 3,161,706 | 3rd party header file confliction - need solution | I have to use the windows.h file in my code but it conflicts with other legacy include files on my project that I can not modify. This is in c++. How do I get around this problem, since I can not modify any of the header files in question? I thought about using a namespace but I would think you can not wrap a include i... | Thank you, my solution was to remove the windows.h file from the header and make everything generic, LPSTR, LPWSTR and even the HINSTANCE (made void* and cast back in cpp file). I guess the rest of my problem was just me being an idiot!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.