question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,631,926 | 2,631,977 | C++ iostream not setting eof bit even if gcount returns 0 | I'm developping an application under windows, and i'm using fstreams to read and write to the file.
I'm writing with fstream opened like this :
fs.open(this->filename.c_str(), std::ios::in|std::ios::out|std::ios::binary);
and writing with this command
fs.write(reinterpret_cast<char*>(&e.element), sizeof(T));
closing ... | Try this:
while(is.read(reinterpret_cast<char*>(&e.element), sizeof(T))) {}
Also you should open the istream with the binary flag as well:
is.open(filename, std::ios::in | std:ios::binary);
If it reads forever, what does it read? What type is T?
|
2,632,021 | 2,632,075 | Can sizeof return 0 (zero) | Is it possible for the sizeof operator to ever return 0 (zero) in C or C++? If it is possible, is it correct from a standards point of view?
| In C++ an empty class or struct has a sizeof at least 1 by definition. From the C++ standard, 9/3 "Classes": "Complete objects and member subobjects of class type shall have nonzero size."
In C an empty struct is not permitted, except by extension (or a flaw in the compiler).
This is a consequence of the grammar (which... |
2,632,309 | 2,632,334 | Never ending function problem | Im trying to run a function that will never end (until the program is killed)
How would i start such a function and be able to continue on past that function, because at the moment the program will not run past the never ending function.
Regards
Paul
| You'd need to start a new thread. A given thread can only execute one function at a time. So, if you want to have two separate functions executing at the same time, you need multiple threads. You'll need to look into multi-threaded programming. If you're on linux or another unix-based system, then the library to look a... |
2,632,430 | 2,632,440 | Running for loop depending on size of string vector | I have made a string vector
vector<string> actor_;
and then added elements in it using push_back.
I now want to display all of them, for which I need to run a loop according to the number of elements in the vector. For that, I need to run the following loop:
for (int i = 0; i < (int)actor_.size; i++)
{
}
but this ret... | size is a member function; you mean:
for (unsigned int i = 0; i < actor_.size(); i++) { }
(it's a good idea to use std::size_t instead of unsigned int as well)
|
2,632,466 | 2,632,491 | What does binding mean exactly? | I always see people mention that "Python binding" and "C Sharp binding" etc. when I am actually using their C++ libraries. What does binding mean? If the library is written in C, and does Python binding means that they use SWIG kind of tool to mock a Python interface?
Newbie in this field, and any suggestion will be we... | When someone talks about something like a "C# binding" of a library, they are indicating that you and API is being provided in C# for a library written in a different language. This may or may not involve an autogeneration tool like SWIG.
|
2,632,503 | 2,632,512 | m.find(...) == m.end() - which is used, iterator or const_iterator | std::map find/end both provides const_iterator and iterator, e.g.
iterator end ();
const_iterator end () const
Out of curiosity,if I have a std::map , which will be called/compared here, an iterator or a const_iterator ? :
if(m.find(key) != m.end()) {
...
}
And should I care ?
| If m is const, then a const_iterator will be returned; otherwise an iterator will be returned.
If all you are doing is testing for existence of an element in the map, then it doesn't really matter which one is used.
|
2,632,601 | 2,632,676 | Why are forward declarations necessary? |
Possible Duplicate:
Should C++ eliminate header files?
In languages like C# and Java there is no need to declare (for example) a class before using it. If I understand it correctly this is because the compiler does two passes on the code. In the first it just "collects the information available" and in the second o... | The short answer is that computing power and resources advanced exponentially between the time that C was defined and the time that Java came along 25 years later.
The longer answer...
The maximum size of a compilation unit -- the block of code that a compiler processes in a single chunk -- is going to be limited by th... |
2,632,741 | 2,632,997 | Targeting .NET Framework 4.0 | I just downloaded MSVS 2010 from university MSDN AA. The IDE itself is wonderful, I can't complain, but...
I'm developing project that combines C#, C++/CLI and C++ (native core, cli bridge DLL and c# GUI). But the VS 2010 seems NOT TO support targeting .NET for C++/CLI projects unless VS 2008 is installed. Requiring b... | I don't see why it's too soon, users can download it easily and they're gonna have to download it eventually anyway right?
|
2,632,846 | 2,632,979 | understanding z buffer formats direct x | A z buffer is just a 3d array that shows what object should be written in front of another object. each element in the array represents a pixel that holds a value from 0.0 to 1.0. My question is if that is all a z buffer does, then why are some buffers 24bit, 32bit, and 16 bit ?
| A Z-Buffer is not a 3D array. It's a 2D array that has a value at each pixel. That value represents the depth of the last pixel written to that position.
If the pending pixel has a depth that's behind the current value on the Z-Buffer, the pixel is not visible and so it is skipped. This is what allows objects to be ren... |
2,632,895 | 2,637,627 | is XULRUNNER suitable as a replacement for other C++ desktop applications frameworks such as QT? | XulRunner/Gecko seems to be really interesting for developing GUI-intensive applications (by using widely used technologies such as HTML / CSS / SVG / XUL / Javascript). But the underlaying C++ APIS (XPCOM, NECKO, ...) looks so old and complex. Moreover the general lack of documentation/developper tools is really frigh... | There aren't actually that many applications built using XulRunner, as far as I'm aware. And I should know, as I was Tech Lead for one of them and we tried to hire experienced people. In hindsight, this doesn't surprise me. Our decision to use XulRunner was made by a non-developer, against my advice. Many things took t... |
2,633,085 | 2,633,175 | implement the URL match in C++ | Given a list of URLs, such as a/b/e/f, b/c/d/k/g, s/e/c/d, how to match an input URL to the one in the list, for example, an input c/d should be matched to s/e/c/d, not b/c/d/k/g
| Why not b/c/d/k/g? Are the "Url"s simply strings? If so simply search it using strstr or one of its derivative (wcsstr, _mbsstr, _mbsstr_l).
|
2,633,092 | 2,633,127 | istringstream in C++ | I'm sure I'm just doing something stupid here, but I can't quite figure out what it is. When I try to run this code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
string s("hello");
istringstream input(s, istringstream::in);
string s2;
input >>... | Works for me.
But I have never done this:
istringstream input(s, istringstream::in);
Try
istringstream input(s);
|
2,633,302 | 2,633,356 | Google Bot information? | Does anyone know any more details about google's web-crawler (aka GoogleBot)? I was curious about what it was written in (I've made a few crawlers myself and am about to make another) and if it parses images and such. I'm assuming it does somewhere along the line, b/c the images in images.google.com are all resized. ... | Officially allowed languages at Google, I think, are Python/C++/Java.
The bot likely uses all 3 for different tasks.
|
2,633,314 | 2,635,384 | Pattern for UI configuration | I have a Win32 C++ program that validates user input and updates the UI with status information and options. Currently it is written like this:
void ShowError() {
SetIcon(kError);
SetMessageString("There was an error");
HideButton(kButton1);
HideButton(kButton2);
ShowButton(kButton3);
}
void ShowS... | I would recommend Observer Pattern and State Pattern, when an validation happens to be successful or unsuccessful, attached buttons can change their state according to information provided in "notify" method. Please refer to GoF's book for further details, or just google them. Hope it helps.
|
2,633,330 | 2,634,467 | Microsoft C++ Language Reference | Whenever any question is asked, and a reference text is needed, I never see MSDN C++ Language Reference being referred.
I was browsing through it and I personally feel that it is extremely well written.
Is there some specific reason it is not used as often as a standard?
Is it because it contains some VC++ specific fea... | The answer is fairly simple: The MSDN reference is not authoritative. It tells you how Microsoft's compiler behaves, and yes, it usually happens to coincide with what the standard says. But when someone asks how the C++ language deals with some situation, only one text has any authority: the ISO standard.
So when answe... |
2,633,400 | 2,633,413 | C/C++ efficient bit array | Can you recommend efficient/clean way to manipulate arbitrary length bit array?
Right now I am using regular int/char bitmask, but those are not very clean when array length is greater than datatype length.
std vector<bool> is not available for me.
| boost::dynamic_bitset if the length is only known in run time.
std::bitset if the length is known in compile time (although arbitrary).
|
2,633,670 | 2,633,748 | High Precision Constants for Templated Code | I am writing a template class which takes a floating-point-like type (float, double, decimal, GMP) as a parameter. However, my class requires various numeric constants. Some of these are rational numbers (int/int) while others are irrational and available to 30 or so decimal places.
What is the best way to go about ini... | I think the easiest way to do this is to create a specialized container class that holds the constants, something like this:
template<class T>
class Constants
{
public:
static const T pi = T(3.1415);
};
//Example specialization:
template<>
class Constants<double>
{
public:
static const double pi = 3.1415926535... |
2,633,702 | 2,633,807 | Templates --> How to decipher, decide if necessary and create? | I have a few classes in a project that I inherited that are really old, last I knew they compiled with CodeWarrior 8. I am now in XCode 3.2
Here is an example of what I struggle with:
template <class registeredObject>
typename std::vector<registeredObject>::iterator FxRegistry<registeredObject>::begin(void)
{
retu... | typedef std::vector<registeredObject>::iterator iterator;
typedef std::vector<registeredObject>::const_iterator const_iterator;
std::vector<registeredObject>::iterator begin(void);
std::vector<registeredObject>::const_iterator begin(void) const;
std::vector<registeredObject>::iterator end(void);
std::vector<registe... |
2,633,787 | 2,633,822 | Compile time type determination in C++ | A coworker recently showed me some code that he found online. It appears to allow compile time determination of whether a type has an "is a" relationship with another type. I think this is totally awesome, but I have to admit that I'm clueless as to how this actually works. Can anyone explain this to me?
template<typen... | It declares two overloaded functions named test, one taking a Base and one taking anything (...), and returning different types.
It then calls the function with a Derived and checks the size of its return type to see which overload is called. (It actually calls the function with the return value of a function that ret... |
2,633,795 | 2,633,905 | Need to make sure value is within 0-255 | This is probably really easy, but I'm lost on how to "make sure" it is in this range..
So basically we have class Color and many functions to implement from it.
this function I need is:
Effects: corrects a color value to be within 0-255 inclusive. If value is outside this range, adjusts to either 0 or 255, whichever is... | I agree with the other answers, with one modification; this should be an else-if statement. There is no need to test if the value is over 255 if you already know it is less than 0
static unsigned char correctValue(int value)
{
if(value<0) value=0;
else if(value>255) value=255;
return value;
}
|
2,633,999 | 2,634,030 | Using a map with set_intersection | Not used set_intersection before, but I believe it will work with maps. I wrote the following example code but it doesn't give me what I'd expect:
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
struct Money
{
double amount;
string currency;
bool operator< (... | MoneyMap map2;
map1.insert( MoneyPair( 3, mn[3] ) ); // (3)
map1.insert( MoneyPair( 4, mn[4] ) ); // (4)
map1.insert( MoneyPair( 5, mn[5] ) );
map1.insert( MoneyPair( 6, mn[6] ) );
map1.insert( MoneyPair( 7, mn[7] ) );
Unless this is a typo, you are just reinserting stuff into map1 instead of inserting into map2. I... |
2,634,278 | 2,635,399 | How to compile Microsoft Silverlight for Symbian as .SIS (stand alone) application? | So in nokia we can have sort of Microsoft Silverlight installed to system. We can see Silverlight apps in browser, interact with them.
But how to compile that silverlight application into .SIS applications?
| http://www.silverlight.net/getstarted/devices/symbian/
Sounds like it is still a beta, so you may try its beta forum where experts are available.
|
2,634,279 | 2,634,303 | Assigning a vector of one type to a vector of another type | I have an "Event" class. Due to the way dates are handled, we need to wrap this class in a "UIEvent" class, which holds the Event, and the date of the Event in another format.
What is the best way of allowing conversion from Event to UIEvent and back? I thought overloading the assignment or copy constructor of UIEvent ... | There are two simple options that I can think of.
The first option would be the one you describe: create a constructor that takes an object of the other type:
struct UIEvent
{
UIEvent(const Event&);
};
and use std::copy to copy elements from a vector of one type to a vector of the other:
std::vector<Event> even... |
2,634,558 | 2,634,566 | converting string to int in C++ | I am trying to convert a string I read in from a file to an int value so I can store it in an integer variable. This is what my code looks like:
ifstream sin;
sin.open("movie_output.txt");
string line;
getline(sin,line);
myMovie.setYear(atoi(line));
Over here, setYear is a mutator in the Movie class (myMovie i... | myMovie.setYear(atoi(line.c_str()));
|
2,634,580 | 2,634,720 | string parsing to double fails in C++ | Here's a fun one I've been trying to figure out. I have the following program:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
string s("5");
istringstream stream(s);
double theValue;
stream >> theValue;
cout << theValue << endl;
... | Perhaps this is the problem you're having: stringstream question
See the accepted answer and the link therein. An example in the Apple discussion link sounds very much like what you're experiencing.
|
2,634,636 | 2,634,641 | Properties declared beside the constructor | I am very very new to C/C++ and not sure what the method is called. But thats why I am here trying to find the answer. let me show you an example
MyClass::MyClass() : valueOne(1), valueTwo(2)
{
//code
}
Where valueOne and valueTwo are class properties that are assigned values outside of the body, what method is ... | That is an initializer list. You can initialize your member variables using an initializer list after the constructor.
By default the constructor will automatically create the objects that are member variables by calling their default constructors. By using an initializer list you can specify to use other constructor... |
2,634,661 | 2,634,729 | C++ detecting end of file | I have a C++ program that is reading in info from a file, that stores info seperated by "$$$$". An example of how the file looks is:
abc
bcd
$$$$
def
$$$$
qwe
gfh
$$$$
How can I detect the file has ended, without using the eof() function?
I have it set like this,
getline(sin,temp)
if (temp=="$$$$")
{
}
After reading ... | while (getline(sin, temp))
{
// use temp.
}
You will come out of loop once you are end of file.
|
2,634,690 | 2,634,715 | Good hash function for a 2d index | I have a struct called Point. Point is pretty simple:
struct Point
{
Row row;
Column column;
// some other code for addition and subtraction of points is there too
}
Row and Column are basically glorified ints, but I got sick of accidentally transposing the input arguments to functions and gave them each ... | Following the technique is given in Effective Java (2nd edition), and quoted from there in Programming in Scala. Have a prime constant (we'll say 53 but you may find something larger will give more even distribution here), and perform multiplication and addition as follows:
(53 + int_hash(row)) * 53 + int_hash(col)
Fo... |
2,634,732 | 2,634,757 | Find number of differences in 2 strings | int n = string.numDifferences("noob", "newb"); // 2
??
| The number you are trying to find is called the edit distance. Wikipedia lists several algorithms you might want to use; the Hamming distance is a very common way of finding the edit difference between two strings of the same length (it's often used in error-correcting codes); the Levenshtein distance is similar, but ... |
2,634,800 | 2,634,961 | Can I use Visual Studio's testing facilities in native code? | Is it possible to use Visual Studio's testing system with native code? I have no objection to recompiling the code itself under C++/CLI if it's possible the code can be recompiled without changes -- but the production code shipped has to be native code.
The Premium Edition comes with code coverage support which I might... | Well, I hate to answer my own question, but the answer is no:
This is not going to fly, you cannot use any unmanaged code when compiling safe. That prevents use of any of the unmanaged CRT headers.
Unit testing requires /clr:safe. In other words, no, this is not supported. sigh
|
2,634,978 | 2,634,994 | Is it possible to reinterpret pointer as dimensioned array reference? | Suppose I have some pointer, which I want to reinterpret as static dimension array reference:
double *p;
double (&r)[4] = ?(p); // some construct?
// clarify
template< size_t N> void function(double (&a)[N]);
...
double *p;
function(p); // this will not work.
// I would like to cast p as to make it appear as double... | It's ugly:
double arr[4];
double* d = arr;
double (&a)[4] = *static_cast<double(*)[4]>(static_cast<void*>(d));
Be sure the array type matches what the pointer originally came from.
|
2,635,036 | 2,635,110 | C++ meta Programming to create a new typelist with remove_const applied to each element | Hi Could anyone give me a sample program to "Create an ApplyRemoveConst template that
constructs a new typelist with remove_const applied to each element"
For example:
typedef TYPELIST_3(A, const B, B) TL;
typedef ApplyRemoveConst<TL>::Result TL2;
// TL2 is the same as TYPELIST_3(A, B, B)
//Typelist Definition:
temp... | I think what you want is something like this:
template <typename, template <typename> class>
struct transform;
template <template <typename> class Func>
struct transform<NullType, Func>
{
typedef NullType type; // nothing to do
};
template <typename T, typename U, template <typename> class Func>
struct transform<... |
2,635,123 | 2,635,143 | activate RTTI in c++ | Can anybody tell me how to activate RTTI in c++ when working on unix.
I heard that it can be disabled and enabled.
on my unix environment,how could i check whether RTTI is enabled or disabled?
I am using the aCC compiler on HPUX.
| Are you using g++ or some other compiler?
In g++ RTTI is enabled by default IIRC, and you can disable it with -fno-rtti. To test whether it is active or not use dynamic_cast or typeid
UPDATE
I believe that HPUX's aCC/aC++ also has RTTI on by default, and I am unaware of a way to disable it. Check your man pages.
|
2,635,272 | 6,412,333 | fastest (low latency) method for Inter Process Communication between Java and C/C++ | I have a Java app, connecting through TCP socket to a "server" developed in C/C++.
both app & server are running on the same machine, a Solaris box (but we're considering migrating to Linux eventually).
type of data exchanged is simple messages (login, login ACK, then client asks for something, server replies). each me... | Just tested latency from Java on my Corei5 2.8GHz, only single byte send/received,
2 Java processes just spawned, without assigning specific CPU cores with taskset:
TCP - 25 microseconds
Named pipes - 15 microseconds
Now explicitly specifying core masks, like taskset 1 java Srv or taskset 2 java Cli:
TCP, same... |
2,635,373 | 2,635,517 | parse localtime in c++ | Is there an easy "beginner" way to take the current time using <ctime> to a Date object that has
int month
int day
int year
for it's member variables? Thanks.
| time_t tt = time(NULL); // get current time as time_t
struct tm* t = localtime(&tt) // convert t_time to a struct tm
cout << "Month " << t->tm_mon
<< ", Day " << t->tm_mday
<< ", Year " << t->tm_year
<< endl
The tm struct ints are all 0-based (0 = Jan, 1 = Feb) and you can get various day measures, d... |
2,635,609 | 4,117,427 | Error while Trying to Hook "TerminateProcess" Function. Target Process crashes. Can anyone help me? | Debugging with visual studio 2005 The following Error Displayed :
Unhandled exception at 0x00000000 in procexp.exe: 0xC0000005: Access
violation reading location 0x00000000.
And Thread Information:
2704 Win32 Thread 00000000 Normal 0
extern "C" VDLL2_API BOOL WINAPI MyTerminateProcess(HANDLE hProce... | What is VDLL2_API defined as? It may be interfering with the calling convention (which is meant to be WINAPI for this function, as you write it later on the same line).
Stack problems on exit (ESI, ESP) usually indicate that you have your calling conventions mixed up. You appear to have used FARPROC consistently every... |
2,635,720 | 2,635,833 | log4j/log4cxx : exclusive 1 to 1 relation between logger and appender | Using the xml configuration of log4cxx (which is identical in configuration to log4j).
I want to have a certain logger output exclusively to a specific appender (have it the only logger which outputs to that appender).
I found that it's possible to bind a logger to a specific appender like this:
<logger name="LoggerNam... | You use the following piece of configuration for this:
<logger name="TRACER" additivity="false">
<level value="Debug" />
<appender-ref ref="DebugAppender" />
</logger>
All loggers with a name that starts with TRACER will log to the appender DebugAppender. For more info, check here or here.
Additivity="false" m... |
2,635,724 | 2,635,738 | Size of abstract class | How can I find the size of an abstract class?
class A
{
virtual void PureVirtualFunction() = 0;
};
Since this is an abstract class, I can't create objects of this class. How will I be able to find the size of the abstract class A using the 'sizeof' operator?
| You can use the sizeof operator:
int a_size = sizeof(A);
|
2,635,882 | 2,636,897 | RAII tutorial for C++ | I'd like to learn how to use RAII in c++. I think I know what it is, but have no idea how to implement it in my programs. A quick google search did not show any nice tutorials.
Does any one have any nice links to teach me RAII?
| There's nothing to it (that is, I don't think you need a full tutorial).
RAII can be shortly explained as "Every resource requiring cleanup should be given to an object's constructor."
In other words:
Pointers should be encapsulated in smart pointer classes (see std::auto_ptr, boost::shared_ptr and boost::scoped_ptr fo... |
2,636,303 | 2,636,338 | How to initialize a private static const map in C++? | I need just dictionary or associative array string => int.
There is type map C++ for this case.
But I need only one map forall instances(-> static) and this map can't be changed(-> const);
I have found this way with boost library
std::map<int, char> example =
boost::assign::map_list_of(1, 'a') (2, 'b') (3, 'c')... | #include <map>
using namespace std;
struct A{
static map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
static const map<int,int> myMap;
};
const map<int,int> A:: myMap = A::create_map();
int main() {
}
|
2,636,314 | 2,636,355 | How can I get identity of a disk? | I want to identify disk in c++ in my windows application.
For example:
I have a disk on E:\
Then I changed the disk, and replace it with another one. the name is still E:\
How can I know the disk is changed, it is not the original one?
If I have no administrator priority in win7, Can I still use some method to identy d... | Probably the relevant methods are:
GetLogicalDrives()
BOOL WINAPI GetVolumeInformation(
__in_opt LPCTSTR lpRootPathName,
__out LPTSTR lpVolumeNameBuffer,
__in DWORD nVolumeNameSize,
__out_opt LPDWORD lpVolumeSerialNumber,
__out_opt LPDWORD lpMaximumComponentLength,
__out_opt LPDWORD lpFileSy... |
2,636,320 | 2,636,348 | Read multiple strings from a file C++ | I need to read different values stored in a file one by one. So I was thinking I can use ifstream to open the file, but since the file is set up in such a way that a line might contain three numbers, and the other line one number or two numbers I'm not sure how to read each number one by one. I was thinking of using st... | Why not read them as numbers from the file?
double temp;
vector<double> vec;
ifstream myfile ("file.txt");
if (myfile.is_open()) {
while ( myfile >> temp) {
vec.push_back(temp);
}
myfile.close();
}
|
2,636,479 | 2,644,164 | HTML file: add annotations through IHTMLDocument | I need to add "annotations" to existing HTML documents - best in the form of string property values I can read & write by name.
Apparently (to me), meta elements in the header seem to be the common way - i.e. adding/modifying elements like
<head>
<meta name="unique-id_property-name" content="property-value"/>
...
... | I do not have enough experience working with HTML using C++.
I am not sure if this answers your question, but you could do the following
enum all elements using doc->all
for each IHtmlElement you can compare the tagname to meta (use IHtmlElement::get_tagName)
for these meta tags you can get and set property using IHt... |
2,636,563 | 2,636,596 | Question about compilers and how they work | This is the C code that frees memory of a singly linked list. It is compiled with Visual C++ 2008 and code works as it should be.
/* Program done, so free allocated memory */
current = head;
struct film * temp;
temp = current;
while (current != NULL)
{
temp = current->next;
free(current);
current = temp;
}
... | The second program is invoking undefined behavior. It is not a difference in the compiler, but rather a difference in the implementation of the C standard library and the function free(). The compiler will store the pointer current as a local variable, but it will not store a copy of the memory that it references.
When... |
2,636,594 | 2,637,105 | Microsoft Detours - DetourUpdateThread? | I have a few quick questions about the Microsoft Detours Library. I have used it before (successfully), but I just had a thought about this function:
LONG DetourUpdateThread(HANDLE hThread);
I read elsewhere that this function will actually suspend the thread until the transaction completes. This seems odd since most s... | How embaressing:
I forgot that the source was available!
DetourUpdateThread silently ignores the enlisting of the current thread. Otherwise, the given thread is suspended. I wonder why ALL code examples enlist the current thread anyway! This answers the first 2 questions.
As for the 3rd question:
I found another detour... |
2,636,846 | 2,637,495 | How to detect first or last element iterating over a container? | How to do the following in more stylish/short way?
for(i=container.begin(); i!=container.end(); ++i) {
if (i!=container.begin()) {
cout << ", ";
}
cout << *i;
j=i;
if (++j==container.end()) {
cout << "!" << endl;
}
}
Solutions like foreach are acceptable (actions on first and l... | Boost has next / prior which can sometimes help in such situations.
for(i=container.begin(); i!=container.end(); ++i) {
if (boost::next(i) == container.end()) {
std::cout << "!" << std::endl;
}
}
Although for this specific case, I'd simply output the first element, loop from second till last while alw... |
2,636,907 | 2,637,187 | how to generate String difference vectors? | a bit of a vague question but I am looking for pointers as to how can I generate String diff vectors in C++. The scenario is such that given a paragraph I want to store the various differences(Edit, cut copy paste etc.) it goes through in a draft mode to review Audit history.
Any hints in this regard will be really app... | An idea using C++ polymorphism:
class Action
{
public:
virtual void revert(std::string& base) = 0;
};
class InsertAction : public Action
{
private:
int pos, len;
public:
InsertAction(int pos, std::string& base, const std::string& in) : len(in.size()), pos(pos)
{
base.insert(pos, in)... |
2,636,958 | 2,637,085 | Create unmanaged c++ object in c# | I have an unmanaged dll with a class "MyClass" in it.
Now is there a way to create an instance of this class in C# code? To call its constructor? I tried but the visual studio reports an error with a message that this memory area is corrupted or something.
Thanks in advance
| C# cannot create class instance exported from native Dll. You have two options:
Create C++/CLI wrapper. This is .NET Class Library which can be added as Reference to any other .NET project. Internally, C++/CLI class works with unmanaged class, linking to native Dll by standard C++ rules. For .NET client, this C++/CLI ... |
2,637,235 | 2,637,288 | Problem Loading multiple textures using multiple shaders with GLSL | I am trying to use multiple textures in the same scene but no matter what I try the same texture is loaded for each object. So this what I am doing at the moment, I initialise each shader:
rightWall.SendShaders("wall.vert","wall.frag","brick3.bmp", "wallTex", 0);
demoFloor.SendShaders("floor.vert","floor.frag","... | Like you have to call glUseProgram(program) before using the shader for rendering, you also have to bind the right texture directly before rendering.
The code should look like this:
glUseProgram(program1);
glBindTexture(GL_TEXTURE_2D, texture1);
// render calls for object 1
glUseProgram(program2);
glBindTexture(GL_TEX... |
2,637,338 | 2,637,557 | class which cannot be derived | I found this code here
class Usable;
class Usable_lock {
friend class Usable;
private:
Usable_lock() {}
Usable_lock(const Usable_lock&) {}
};
class Usable : public virtual Usable_lock {
// ...
public:
Usable();
Usable(char*);
// ...
};
Usable a;
class DD : public Usable { };
DD dd; // ... | It's a property of virtual derivation.
The idea of virtual derivation is to solve the "Dreaded Diamond Pattern":
struct Base {};
struct D1: Base {};
struct D2: Base {};
struct TopDiamond: D1, D2 {};
The problem here is that TopDiamond has 2 instance of Base here.
To solve this problem, very peculiar "MultiInheritanc... |
2,637,546 | 2,638,257 | Python and C++ Sockets converting packet data | First of all, to clarify my goal: There exist two programs written in C in our laboratory. I am working on a Proxy Server (bidirectional) for them (which will also mainpulate the data). And I want to write that proxy server in Python. It is important to know that I know close to nothing about these two programs, I only... | You can receive the packet's 50 bytes with a .recv call on a properly connected socked (it might actually take more than one call in the unlikely event the TCP packet gets fragmented, so check incoming length until you have exactly 50 bytes in hand;-).
After that, understanding that C code is puzzling. The assignments... |
2,637,571 | 2,637,838 | Creating simple c++.net wrapper. Step-by-step | I've a c++ project. I admit that I'm a complete ZERO in c++. But still I need to write a c++.net wrapper so I could work with an unmanaged c++ library using it. So what I have:
1) unmanaged project's header files.
2) unmanaged project's libraries (.dll's and .lib's)
3) an empty C++.NET project which I plan to use as a ... | http://www.codeproject.com/KB/mcpp/quickcppcli.aspx#A8
This is general direction. You need to create C++/CLI Class Library project, add .NET class to it (StudentWrapper in this sample), create unmanaged class instance as managed class member, and wrap every unmanaged class function. Unmanaged library is added to C++/CL... |
2,637,671 | 2,637,687 | where does main() return its value? | I'm newly using CODE::BLOCKS+mingw compiler
If I don't type return 0 at the end of program,I can see that main() is returning some integer,I learnt that main() returning 0 infers program executes successfully.I don't find any flaw in my code, why is it returning some integer?
secondly
any function returns its value to ... | The C++ Standard says that if you don't explicitly return a value, the compiler must generate code as if you had typed:
return 0;
Exactly what the return value means and how it is returned is implementation specific. For most OSs, the return value becomes the exit code of the process.
|
2,637,700 | 2,637,823 | Is it possible to roll a significantly faster version of sqrt | In an app I'm profiling, I found that in some scenarios this function is able to take over 10% of total execution time.
I've seen discussion over the years of faster sqrt implementations using sneaky floating-point trickery, but I don't know if such things are outdated on modern CPUs.
MSVC++ 2008 compiler is being used... | Yes, it is possible even without trickery:
sacrifice accuracy for speed: the sqrt algorithm is iterative, re-implement with fewer iterations.
lookup tables: either just for the start point of the iteration, or combined with interpolation to get you all the way there.
caching: are you always sqrting the same limited ... |
2,637,975 | 2,637,990 | Zero out array sent as parameter in C++ | How do you make all elements = 0 in the array sent as a parameter?
int myArrayFunction(int p_myArray[]) {
p_myArray[] = {0};//compiler error syntax error: ']'
.
.
}
| No you can't. There's not enough information. You need to pass the length of the array too.
int myArrayFunction(int p_myArray[], int arrayLength) {
// --------------------------------------^ !!!
Then you can use memset or std::fill to fill the array with zero. (= {0} only works in initialization.)
std::fill(p_myAr... |
2,638,015 | 2,638,070 | How slow are bit fields in C++ | I have a C++ application that includes a number of structures with manually controlled bit fields, something like
#define FLAG1 0x0001
#define FLAG2 0x0002
#define FLAG3 0x0004
class MyClass
{
'
'
unsigned Flags;
int IsFlag1Set() { return Flags & FLAG1; }
void SetFlag1Set() { Flags |= FLAG1;... | The two examples should be very similar in speed because the compiler will have to end up issuing pretty much the same instructions for bit-masking in both cases. To know which is really best, run a few simple experiments. But don't be surprised if the results are inconclusive; that's what I'm predicting...
You might b... |
2,638,095 | 2,639,122 | Trouble compiling C/C++ project in NetBeans 6.8 with MinGW on Windows | I am learning C and because VC++ 2008 doesn't support C99 features I have just installed NetBeans and configure it to work with MinGW. I can compile single file project ( main.c) and use debugger but when I add new file to project I get error "undefined reference to ... function(code) in that file..". Obviously MinGW... | I found what was wrong. I was adding files in physical view not while I am in logical view.
|
2,638,100 | 2,638,165 | High memory usage for dummies | I've just restarted my firefox web browser again because it started stuttering and slowing down. This happens every other day due to (my understanding) of excessive memory usage.
I've noticed it takes 40M when it starts and then, by the time I notice slow down, it goes to
1G and my machine has nothing more to offer un... | Browsers are like people - they get old, they get bloated, and they get ditched for younger and leaner models.
Firefox is not just a browser, it's an ecosystem.
While I feel that recent versions are quite bloated, the core product is generally stable.
However, firefox is an ecosystem/platform for:
1) Badly written plu... |
2,638,329 | 2,638,969 | Detect a USB drive being inserted - Windows Service | I am trying to detect a USB disk drive being inserted within a Windows Service, I have done this as a normal Windows application. The problem is the following code doesn't work for volumes.
Registering the device notification:
DEV_BROADCAST_DEVICEINTERFACE notificationFilter;
HDEVNOTIFY hDeviceNotify = NULL; ... | Windows 7 supports "trigger started services". If you want to start your service, go around in a sleeping loop, and react whenever something is plugged in, I think you would be better off (assuming Windows 7 is an option) going with a trigger started service where the OS starts the service when a USB device is plugged ... |
2,638,361 | 2,638,438 | Porting Python algorithm to C++ - different solution | Thank you all for helping. Below this post I put the corrected version's of both scripts which now produce the equal output.
Hello,
I have written a little brute string generation script in python to generate all possible combinations of an alphabet within a given length. It works quite nice, but for the reason I wan... | I think the Python code is also broken but maybe you don't notice because the print is indented by one space too many (hey, now I've seen a Python program with a one-off error!)
Shouldn't the output only happen in the else case? And the reason why the output happens more often is that you call print/cout 4 times. I sug... |
2,638,409 | 2,638,485 | Just introducing myself to TMPing, and came across a quirk | I was just trying to learn the syntax of the beginner things, and how it worked when I was making this short bit of code in VS2008. The code below works in adding numbers 1 to 499, but if I add 1 to 500, the compiler bugs out giving me:
fatal error C1001: An internal error has occurred in the compiler.
And I was just w... | I assume with gcc (and by extension g++) the default maximum template recursion depth is 500 as at least on my machine I managed to reproduce your problems with a (slightly better) warning message. Compiling loop<500>::sum worked fine but trying to compile loop<501>::sum failed.
If you are using gcc (or g++) the soluti... |
2,638,443 | 2,638,465 | iPhone c++ development / compiler on a non-Mac PC? (Windows? Linux?) | According to the (in)famous iPhone Developer Program License Agreement change
3.3.1 — Applications may only use Documented APIs in the manner
prescribed by Apple and must not use
or call any private APIs. Applications
must be originally written in
Objective-C, C, C++, or JavaScript as executed by the iPhone OS... |
yes (XCode, though you'll still need a bit of Objective-C glue code to init your application)
no
because they don't want you to and you have to accept the license agreement
EDIT: here you go for restrictions on 3). Simply put, you agree to only use the SDK provided by Apple, in conditions restricted by Apple.
1.2 De... |
2,638,460 | 2,638,494 | Is it possible to simultaneously debug VB6 and a C++ COM dll? | I have a VB6 dll that is loaded by a VB6 frontend. This VB6 dll calls a C++ ATL dll via its COM interface. So, I can run from code in VB6 and I can debug in C++ also, however I can't seem to step through the VB6 code and then get into the C++ code. I feel that this should be possible. Currently I am doing the following... | You should be able to set vb6.exe as the startup program for your project in C++ and start debugging. Then in VB6, open the project and start debugging.
|
2,638,654 | 4,457,138 | Redirect C++ std::clog to syslog on Unix | I work on Unix on a C++ program that send messages to syslog.
The current code uses the syslog system call that works like printf.
Now I would prefer to use a stream for that purpose instead, typically the built-in std::clog. But clog merely redirect output to stderr, not to syslog and that is useless for me as I also ... | I needed something simple like this too, so I just put this together:
log.h:
#include <streambuf>
#include <syslog.h>
enum LogPriority {
kLogEmerg = LOG_EMERG, // system is unusable
kLogAlert = LOG_ALERT, // action must be taken immediately
kLogCrit = LOG_CRIT, // critical conditions
kLogE... |
2,638,664 | 2,641,084 | Is there any free OCaml to C translator? | So I have nice OCaml code (50000 lines). I want to port it to C. So Is there any free OCaml to C translator?
| This probably isn't what you want, but you can get the OCaml compiler to dump its runtime code in C:
ocamlc -output-obj -o foo.c foo.ml
What you get is basically a static dump of the bytecode. The result will look something like:
#include <caml/mlvalues.h>
CAMLextern void caml_startup_code(
code_t code, asi... |
2,638,781 | 2,638,924 | C++: conjunction of binds? | Suppose the following two functions:
#include <iostream>
#include <cstdlib> // atoi
#include <cstring> // strcmp
#include <boost/bind.hpp>
bool match1(const char* a, const char* b) {
return (strcmp(a, b) == 0);
}
bool match2(int a, const char* b) {
return (atoi(b) == a);
}
Each of these functions takes two a... | The return type of boost::bind overloads operator && (as well as many others). So you can write
boost::bind(match1, "a test", _1) && boost::bind(match2, 42, _2);
If you want to store this value, use boost::function. In this case, the type would be
boost::function<bool(const char *, const char *)>
Note that this isn't... |
2,638,843 | 2,639,602 | Should I use C++0x Features Now? | With the official release of VS 2010, is it safe for me to start using the partially-implemented C++0x feature set in my new code?
The features that are of interest to me right now are both implemented by VC++ 2010 and recent versions of GCC. These are the only two that I have to support.
In terms of the "safety" menti... | There are several items I've already discovered that are not written to the standard. For instance, this would not work:
struct test {
int operator()(int);
};
std::cout << typeid( std::result_of<test(int)>::type ).name() << std::endl;
According to the wikipedia site on C++0x it should. Apparently VS2010 uses th... |
2,638,911 | 2,638,937 | Trouble declaring and recognizing global functions | I've created some mathematical functions that will be used in main() and by member functions in multiple host classes. I was thinking it would be easiest to make these math functions global in scope, but I'm not sure how to do this.
I've currently put all the functions in a file called Rdraws.cpp, with the prototypes i... | Which compiler are you using? You need to first compile all of the source files into object files and then link all of the object files together.
Example:
g++ -c -Wall -O2 main.cpp
g++ -c -Wall -O2 Rdraws.cpp
And then to get the executable...
g++ -s main.o Rdraws.o
|
2,638,956 | 2,639,052 | C++ open() fails for no apparent reason | The following code:
char filename[64];
ifstream input;
cout << "Please enter the filename: " << endl;
cin >> filename;
input.open(filename);
if (!input.is_open())
{
cout << "Opening file " << filename << " failed." << endl;
exit(1);
}
fails, it enters the if() and exits. What could possibly be the cause for... | Can you make sure that the filename is what you think it is?
cin >> filename;
cout << filename;
ifstream myFile(filename);
if ( myFile.is_open() ) {
// ...
}
On Unix/Linux systems, remember that file names are case sensitive.
ThisIsMyFile
thisIsMyFile
Are two distinct and separate files.
[EDIT]
ifstre... |
2,638,986 | 2,639,025 | Can a Java class implement a C++ interface | Is it possible to a Java class to implement a C++ interface (interface meaning a full abstract class)?
Where can I read more about?
| Not directly, no. However, you can create a C++ implementation of that interface that simply delegates to a Java implementation via JNI. See the JNI Specification for more details.
|
2,639,017 | 2,639,071 | Calling assignment operator in copy constructor | Are there some drawbacks of such implementation of copy-constructor?
Foo::Foo(const Foo& i_foo)
{
*this = i_foo;
}
As I remember, it was recommend in some book to call copy constructor from assignment operator and use well-known swap trick, but I don't remember, why...
| Yes, that's a bad idea. All member variables of user-defined types will be initialized first, and then immediately overwritten.
That swap trick is this:
Foo& operator=(Foo rhs) // note the copying
{
rhs.swap(*this); //swap our internals with the copy of rhs
return *this;
} // rhs, now containing our old interna... |
2,639,049 | 2,639,080 | c++, when do you need/have to pass data as (*&) | I came across people passing data objects as:
declaration:
DataObject * data = 0;
calling it as:
SomeMethod( data );
definition of Somethod:
void SomeMethod(SomeObject * & object)
My obvious question is, when and why do you have to do this (& *)?
Is it passing the pointer as reference?
| Yes, exactly!
So, not only can your function SomeMethod refer to the same data as the caller, but it can actually change what the caller points to!
int main() {
SomeObject* data = new SomeObject(1);
cout << data << " -> " << *data; // "0xfffee314 -> 1"
SomeMethod(data);
cout << data << " -> " << *data; /... |
2,639,130 | 2,639,149 | accessing the hidden 'this' pointer | I have a GUI architecture wherein elements fire events like so:
guiManager->fireEvent(BUTTON_CLICKED, this);
Every single event fired passes 'this' as the caller of the event. There is never a time I dont want to pass 'this', and further, no pointer except for 'this' should ever be passed.
This brings me to a problem... | You could define
void Element::fireEvent(EVENT e) {
guiManager->fireEvent(e, this);
}
to save yourself a bit of writing each time. You're going to have to call it with this at some point, since the guiManager needs to know which Element called fireEvent.
|
2,639,144 | 2,639,587 | Delphi - Capture stdout and stderr output from statically linked MSVC++ compiled DLL | I have been trying to capture stdout and stderr output from a DLL compiled in MSVC++ that my Delphi app statically links to, but so far have been unsuccessful.
procedure Test;
var
fs: TFileStream;
begin
fs := TFileStream.Create('C:\temp\output.log', fmCreate or fmShareDenyWrite);
SetStdHandle(STD_OUTPUT_HANDLE, ... | If the DLL grabs the stdout handles when it is loaded, then you will need to dynamically load the DLL after you have changed the stdout handles in your code.
|
2,639,145 | 2,639,182 | look for evaluation function in tictactoe 3d game | I'm trying to apply minimax algorithm for the game tictactoe 3D in c++.
I'm struggling to find a good evaluation function for it.
Does anybody know where has good resource to find the evaluation function?
Thank you.
| Here's what I'd use:
Go over all rows (in all directions). For each row, if it has only one player's marks, award that player points based on how many marks there are. You can have a lookup table mapping number of marks to score, which can be adjusted to get the best results. The final result will be the difference bet... |
2,639,199 | 2,639,233 | int foo(type& bar); is a bad practice? | Well, here we are. Yet another proposed practice that my C++ book has an opinion on. It says "a returning-value(non-void) function should not take reference types as a parameter." So basically if you were to implement a function like this:
int read_file(int& into){
...
}
and used the integer return value as some so... | The advice is silly. A direct return value is much smaller and easier to type.
Direct return:
if (read_file(...)) {
... handle problem ...
}
Indirect return:
int status;
read_file(..., status);
if (status) {
... handle problem ...
}
Edit: a bigger issue is whether to use non-const reference parameters at al... |
2,639,255 | 2,639,268 | Return a "NULL" object if search result not found | I'm pretty new to C++ so I tend to design with a lot of Java-isms while I'm learning. Anyway, in Java, if I had class with a 'search' method that would return an object T from a Collection< T > that matched a specific parameter, I would return that object and if the object was not found in the collection, I would retur... | In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:
Attr *getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return &attributes[i];
//if not found
return nullptr;
}
Other... |
2,639,282 | 2,639,333 | opengl texture cube c++ | hello i create a cube and want on one side an texture.
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filterMode);
glBegin(GL_POLYGON); //Vorderseite
gl... | First of all this doesn't seem a cube but just a quad, a cube is made by 6 different quads.. (and you could use GL_QUADS instead that GL_POLYGON.
Second thing is that you are loading the texture but not mapping it to the vertices. You need to supply coordinates to map how the texture should fit onto the quad. You can d... |
2,639,300 | 2,639,322 | std::list or std::multimap | Hey, I right now have a list of a struct that I made, I sort this list everytime I add a new object, using the std::list sort method.
I want to know what would be faster, using a std::multimap for this or std::list,
since I'm iterating the whole list every frame (I am making a game).
I would like to hear your opinion, ... | std::multimap will probably be faster, as it is O(log n) per insertion, whereas an insert and sort of the list is O(n log n).
Depending on your usage pattern, you might be better off with sorted vectors. If you insert a whole bunch of items at once and then do a bunch of reads -- i.e. reads and writes aren't interleave... |
2,639,557 | 2,639,581 | Program to implement the is_same_type type trait in c++ | HI Could anyone give a sample program to implement the is_same_type type trait in c++?
| #include <iostream>
template< typename T1, typename T2 >
struct is_same_type { enum { result = false }; };
template< typename T>
struct is_same_type<T,T> { enum { result = true }; };
int main()
{
std::cout << is_same_type<int,float>::result << '\n'
<< is_same_type<char,char>::result << '\n';
... |
2,639,565 | 2,640,302 | Visual Studio 2005 to VS 2008 | I am a newbie in working on VS IDE and have not much experience in how the different libraries and files are linked in it. I have to build a OpenCV project which was made in VS2005 by one of my colleagues into VS2008. The project is for blob detection.
Following is what he has to say in readme :
Steps to use the libr... | I got confused by this at first as well as it's not very well explained by MSDN. Your best hope to learn it is to try linking to a library with VS2008 instructions (like boost).
Anyway, additional include directories is in Project->Properties->C++->General and additional libraries is in Project->Properties->Linker->Ge... |
2,639,710 | 2,639,795 | Can we write a portable include guard that doesn’t use the preprocessor in C++? | Can we write a portable include guard that doesn’t use the preprocessor in C++? If so how could that be done?
| No.
You cannot use #include without the preprocessor.
Without preprocessor directives, including the same file twice will always result in the same sequence of tokens.
There are a couple non-portable ways to do this (both use the preprocessor), such as:
#pragma once
and
#import "file.h"
But header guards work every... |
2,639,733 | 2,639,746 | C++ Vector of class objects | I have a class called Movie with the following private data members:
private:
string title_ ;
string director_ ;
Movie_Rating rating_ ;
unsigned int year_ ;
string url_ ;
vector<string> actor_;
It also contains the following copy constructor:
Movie::Movie(Movie& myMo... | My guess is that it's protesting against binding a temporary to a non-const reference. Try Movie::Movie(const Movie & myMovie) as the signature to your copy constructor.
|
2,639,848 | 2,639,972 | How do I link against Intel TBB on Mac OS X with GCC? | I can't for the life of me figure out how to compile and link against the Intel TBB library on my Mac. I've run the commercial installer and the tbbvars.sh script but I can't figure this out. I have a feeling it is something really obvious and it's just been a bit too long since I've done this kind of thing.
tbb_test.c... | Since you are using a framework instead of a traditional library, you need to use -framework, like:
g++ tbb_test.cpp -o tbb_test -framework TBB
Instead of:
g++ tbb_test.cpp -o tbb_test -I /Library/Frameworks/TBB.framework/Headers -ltbb
|
2,640,069 | 2,640,081 | Which cast am I using? | I'm trying to cast away const from an object but it doesn't work. But if I use old C-way of casting code compiles. So which casting I'm suppose to use to achieve this same effect? I wouldn't like to cast the old way.
//file IntSet.h
#include "stdafx.h"
#pragma once
/*Class representing set of integers*/
template<class... | There's a dedicated C++ casting operator for dealing with const: const_cast:
myData_[myIndex_++] = &const_cast<T>(obj);
|
2,640,101 | 2,640,116 | How do you compare two unknown numbers to see if they're equal in a special case template? | Here, is my code. Just trying to wrap my head around some of the basic things you can do with TMP. I'm trying to supply two numbers with which the compiler will add up that range of numbers. I'm just not sure how to write the syntax for the "constraint" template.
template < int b, int e >
struct add {
enum { sum = ... | template <int e>
struct add< e, e > { ...
And the result is 4 + 5 + 6 + 7 + 0 == 22, not 4 + 5 + 6 + 7 + 8 == 30. Once e==e in add<...>, add<...>::sum==0, not e.
|
2,640,424 | 2,640,443 | run a command in C++ program using "system" API | I want to run a DOS command in my C++ program. The point is that I want my program stops while the DOS command is executed. I have used "System" API. My question is "Does 'system' make a new thread/process to run the DOS command in it or it just stops the program until the command is done?"
If it creates a new process... | It creates a new process and waits for it to exit.
http://www.cplusplus.com/reference/clibrary/cstdlib/system/
|
2,640,446 | 2,640,505 | Why do some people prefer "T const&" over "const T&"? | So, I realize that const T& and T const& are identical and both mean a reference to a const T. In both cases, the reference is also constant (references cannot be reassigned, unlike pointers). I've observed, in my somewhat limited experience, that most C++ programmers use const T&, but I have come across a few people w... | I think some people simply prefer to read the declarations from right to left. const applies to the left-hand token, except when there is nothing there and it applies on the right-hand token. Hence const T& involves the "except"-clause and can perhaps be thought more complicated (in reality both should be as easy to un... |
2,640,476 | 2,806,636 | How does one port c++ functions to the internet? | I have a few years experience programming c++ and a little less then that using Qt. I built a data mining software using Qt and I want to make it available online. Unfortunately, I know close to nothing about web programming. Firstly, how easy or hard is this to do and what is the best way to go about it?
Supposing I a... |
Port the functions to Java, easily done from C++, you can even find some tools to help - don't trust them implicitly but they could provide a boost.
See longer answer below.
Wrap them in a web application, and deploy them on Google App-Engine.
Java version of a library would be a jar file.
If you really want to be ab... |
2,640,542 | 2,640,597 | Retrieving values of static const variables at a constructor of a static variable | I understand that the code below would result segmentation fault because at the cstr of A, B::SYMBOL was not initialized yet. But why?
In reality, A is an object that serves as a map that maps the SYMBOLs of classes like B to their respective IDs. C holds this map(A) static-ly such that it can provide the mapping as a ... | Use lazy initialization of s_A. This might work:
class C
{
public:
static A& getA() { static A s_A; return s_A; }
};
Or:
class C
{
public:
static A& getA()
{
if( ps_A == NULL) ps_A = new ps_A;
return *ps_A;
}
private:
static A* ps_A;
};
A* C::ps_A = NULL;
Neither solution is thread safe.
|
2,640,601 | 2,640,716 | Does using ReadDirectoryChangesW require administrator rights? | The MSDN says that using ReadDirectoryChangesW implies the calling process having the Backup and Restore privileges.
Does this mean that only process launched under administrator account will work correctly?
I've tried the following code, it fails to enable the required privileges when running as a restricted user.
voi... | I have used ReadDirectoryChangesW without requiring administrator rights, at least on Vista. I don't think you need to manually elevate the process in order to use it on a folder the user already has permissions to see.
It would be more helpful to see the actual code you are using to call ReadDirectoryChangesW, includi... |
2,640,642 | 2,640,756 | C++: Implementing Named Pipes using the Win32 API | I'm trying to implement named pipes in C++, but either my reader isn't reading anything, or my writer isn't writing anything (or both). Here's my reader:
int main()
{
HANDLE pipe = CreateFile(GetPipeName(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
char data[1024];
DWORD numRead = ... | You must use CreateNamedPipe() to create the server end of a named pipe. Be sure to specify a non-zero buffer size, zero (documented by MSDN as 'use system default buffer size') doesn't work. MSDN has decent samples for a multi-threaded client&server.
|
2,640,742 | 2,640,780 | C++ How to copy text in string (from i.e. 8 letter to 12 letter) | This is not homework, I need this for my program :)
I ask this question, because I searched for this in Google about 1 hour, and I don't find anything ready to run. I know that is trivial question, but if you will help me, you will make my day :)
Question:
How to copy text in string (from for
example 8 letter to 12 ... | I assume you're trying to get the 8th - 17th characters in a another string. If so you should use the substring method string::substr
string s = "RunnersAreTheBestLovers";
string other = s.substr(8, 9);
|
2,640,823 | 2,640,897 | Is it possible to create a CImageList with alpha blending transparency? | I would like to knwo if it is possible to create a CImageList with alpha blending transparency.
Sample code that creates a CImageList with ugly transparency (no alpha blending)
CGdiPlusBitmapResource m_pBitmap;
m_pBitmap.Load(IDB_RIBBON_FILESMALL,_T("PNG"),AfxGetResourceHandle());
HBITMAP hBitmap;
m_pBitmap.m_pBitmap-... | Don't use the ILC_MASK flag (from MSDN):
Using 32 Bit Anti-Aliased Icons
Windows XP imagelists, which are
collections of images used with
certain controls such as list-view
controls, support the use of 32-bit
anti-aliased icons and bitmaps. Color
values use 24 bits, and 8 bits are
used as an alpha channel... |
2,641,154 | 2,641,171 | TRY/CATCH_ALL vs try/catch | I've been using c++ for a while, and I'm familiar with normal try/catch. However, I now find myself on Windows, coding in VisualStudio for COM development. Several parts of the code use things like:
TRY {
... do stuff
} CATCH_ALL(e) {
... issue a warning
}
END_CATCH_ALL;
What's the point of these macros? Wh... | It's an MFC macro:
http://msdn.microsoft.com/en-us/library/t8dwzac0%28VS.71%29.aspx
This page says they're a remnant from MFC 1.0 - use normal C++ exceptions in new code:
MFC versions lower than 3.0 did not support the C++ exception mechanism. MFC provided macros to deal with exceptions.
|
2,641,560 | 2,641,577 | Unwanted SDL_QUIT Event on mouseclick | I'm having a slight problem with my SDL/Opengl code, specifically, when i try to do something on a mousebuttondown event, the program sends an sdl_quit event to the stack, closing my application.
I know this because I can make the program work (sans the ability to quit out of it :| ) by checking for SDL_QUIT during my ... | You're missing a break statement in the end of your SDL_MOUSEBUTTONDOWN event handler, resulting in unintentional fall-through to the SDL_KEYDOWN handler. Just add a break after the call to draw_polygon() and you're good to go; you should also add a break to the end of your SDL_KEYDOWN handler to avoid falling through... |
2,641,639 | 2,641,690 | Fstream's tellg / seekg returning higher value than expected | Why does this fail, it's supposed to be simple and work ?
fisier.seekg(0, ios::end);
long lungime = fisier.tellg();
This returns a larger value than that of the file resulting in a wrong
char *continut = new char[lungime];
Any idea what the problem could be ?
I also tried counting to the end of the file one char at ... | At a guess, you're opening the file in translated mode, probably under Windows. When you simply seek to the end of the file, the current position doesn't take the line-end translations into account. The end of a line (in the external file) is marked with the pair "\r\n" -- but when you read it in, that's converted to j... |
2,641,855 | 2,641,970 | standard rectangle class | I have a project that has a GUI (written in QT) and a command-line version. I made use of the rectangle class included in QT: QRect. I would like to break the command-line version's dependency on QT, so I need a drop-in rectangle class that supports intersection and union. I could write one, but I'd prefer including... | If you're going to find one to include, it's probably part of another dependency. So your best bet is to try to write your own. Now is a good time to practice making a template class. :)
template <typename T>
struct point
{
// or maybe you'd prefer to make these private
T x;
T y;
};
template <typename T>
s... |
2,641,907 | 31,479,261 | Do variable references (alias) incure runtime cost? | Maybe this is a compiler specific thing. If so, how about for gcc (g++)? If you use a variable reference/alias like this:
int x = 5;
int& y = x;
y += 10;
Does it actually require more cycles than if we didn't use the reference.
int x = 5;
x += 10;
In other words, does the machine code change, or does the "alias" happ... | I compared 2 programs on Gnu/Linux. Only GCC output is shown below, but clang results lead to identical conclusions.
GCC version: 4.9.2
Clang version: 3.4.2
The programs
1.cpp
#include <stdio.h>
int main()
{
int x = 3;
printf("%d\n", x);
return 0;
}
2.cpp
#include <stdio.h>
int main()
{
int x = 3;
... |
2,642,022 | 2,642,029 | abstract class in C++ | I have a derived derived class from an abstract class. The code is below. I have a FishTank class which is derived from an Aquarium and Aquarium is derived from item. My question is that should I put the definition of virtual int minWidth() const = 0; in aquarium again or is the code below sufficient?
class Item{
publi... | There's no reason to do it again. It only serves to waste space and give you the opportunity to get compile errors from typos. :) Once you inherit, it's just like it had been there anyway.
However, you don't actually ever implement it! Why? You're missing const in FishTank:
int minWidth() const; // <-- const!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.