question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,561,262 | 5,561,350 | Checking for input "0" (zero) with cin | I'm trying to have a program loop, accepting input and producing output until the user enters "0" as the input.
The problem is, my program accepts two values for input, like this:
cin >> amount >> currency;
So, I tried to have a while statement like this:
while (amount != 0 && currency != "") {
cin >> amount >> cu... | You could use the fact that the right side of && is not executed if the left is false:
#include <iostream>
#include <string>
int main()
{
int amount;
std::string currency;
while (std::cin >> amount && amount != 0 && std::cin >> currency)
{
std::cout << "You entered " << amount << " " << currency... |
5,561,301 | 5,606,154 | Suggestions for properly iterating through a vector | I wrote a program to determine the game tree for tic-tac-toe.
I believe most of the code is in good order.
I wrote a function that compares elements of a vector to determine if any elements are duplicates.
Duplicate items can either be truly identical or they can be symmetrical.
Duplicate elements are deleted from the ... | Thanks for all the comments. In the end I simplified my function that had the two confusing loops and determined that instead of adding all games to a move and then check for duplicates/symmetry, I could add a single game and compare it to the current list. This has two advantages: simpler coding that is easy to unders... |
5,561,365 | 5,561,378 | STL-Container styles and iterators that point to a specific type (C++) | I have a container class (called Atom) that I want to store objects of type Term in. Many STL container constructors have the form Container(Iterator first, Iterator last) to initialize the container with some set of elements.
Now, I'd like to be able to use this form for my Atom class, but I'm unsure how to untie the... | Whenever you need to generalize on types, think templates:
class Atom {
public:
template <typename ForwardIterator>
Atom(std::string str,
ForwardIterator start,
ForwardIterator end);
Now just iterate over the range, whatever it may be.
|
5,561,710 | 5,561,943 | Does Qt QSettings keeps the key/value in memory once loaded? | im using QSettings to write to ini file and loading the configuration in application start
my question is once i load value by key does QSettings object keeps the key value in memory
or its reads the value from the ini file ?
| The values are handled in memory, so changing the file doesn't change the QSettings object you have in memory and vice versa.
edit:
Call sync to update to/from file.
It saves values you have modified and reads any values you didn't modify but were modified in the file.
example
// settings.ini contains keys Hello and Hi... |
5,561,869 | 5,561,883 | Why semicolon is not required after a curled bracket? | I know that a semicolon is required after a statement (I'm talking about Java, C++, and similar languages), but is not required after a curled bracket. Why so?
if (a > b)
printf("hello!"); // semicolon is mandatory
if (a > b) {
printf("hello!");
} // semicolon is not required
What is the reason? I mean, what is ... | Because curly brackets are used for grouping statements, but they are not statements themselves.
|
5,561,889 | 5,562,871 | C++0X memory_order without fences, applications, chips that support | As a followup from my previous question, the atomic<T> class specifies most operations with a memory_order parameter. In contrast to a fence this memory order affects only the atomic on which it operates. Presumably by using several such atomics you can build a concurrent algorithm where the ordering of other memory is... | The memory ordering parameter on operations on std::atomic<T> variables does not affect the ordering of that operation per se, it affects the ordering relationships that operation creates with other operations.
e.g. a.store(std::memory_order_release) on its own tells you nothing about how operations on a are ordered wi... |
5,562,230 | 5,786,113 | Cannot set pointer location to that of another pointer's location in C++ | I have a method that takes in a reference to a vector that contains pointers to objects as the first parameter, and a reference to a pointer to an object of the same type as the second parameter. Within the method, I want to change the location referenced by the second argument to an object within the vector. Then have... | I was able to solve this problem by storing a reference to the pointer in a vector and updating that stored reference. I do not know why setting it directly did not work, but this hack got the job done.
|
5,562,231 | 5,562,314 | In c++ how can I make class to recognize structures without including the header? | Hello
I have class AA.h and inside I have defined structure:
#include "BB.h"
Struct foo{
};
Class AA
{
…
void funa()
{
BB bb;
foo f;
bb.func(f);
}
….
};
My question is do I have to include the AA.h also in the BB.h file so it will recognize the foo struct or there is something else I can do ?
| Seems simplest is to create a header for your struct then include it in both your AA and BB.
#ifndef __FOO__H__
#define __FOO__H__
struct foo {
};
#endif
|
5,562,297 | 5,562,475 | Fast search in compressed text files | I need to be able to search for text in a large number of files (.txt) that are zipped. Compression may be changed to something else or even became proprietary.
I want to avoid unpacking all files and compress (encode) the search string and search in compressed files. This should be possible using Huffman compression w... | Most text files are compressed with one of the LZ-family of algorithms, which combine a Dictionary Coder together with an Entropy Coder such as Huffman.
Because the Dictionary Coder relies on a continuously-updated "dictionary", its coding result is dependent on the history (all codes in the dictionary that is derived ... |
5,562,356 | 5,563,198 | Data Hiding,Data Encapsulation? practical application | Hi I am a newbie to C++ reading the C++ concepts...............and I am unable to comprehend the data hiding in the sense how it would be used practically or in real time.
question : As I know data hiding would implemented in C++ to hide the actual data being used
behind the scenes in a programm suppose by declaring so... | Data hiding is a way of controlling dependency of code in one part of an application on code in another part of the application. That is, when one bit of code changes, should one or more other bits of code consequently need updating too? As much as possible, you want the answer to that to be "no", because otherwise e... |
5,562,377 | 5,562,426 | Passing a vector<vector<int> > pointer to a argument? | Okay, so I'm trying to pass a pointer to a argument like this.
void function(vector<vector<int> > *i){
vector<int> j;
j.push_back(5);
i->push_back(j);
}
And call it with function(&i)
But when I do it says i[0][0] is 0 and not 5.
Why is this happening?
Edit:
int main(){
vector<vector<int> > test;
function(&test);
... | You can try this code:
void f(vector<vector<int> > *i)
{
vector<int> j;
j.push_back(5);
i->push_back(j);
}
vector<vector<int> > i;
f(&i);
cout << i[0][0];
Output:
5
Demo: http://ideone.com/hzCtV
Or alternatively, you can also pass by reference as illustrated here : http://ideone.com/wA2tc
|
5,562,448 | 5,562,766 | c++ class object as an instance variable in obj-c class | I have a c++ class IPoint and want to use an instance of IPoint as an instance variable for an obj-c class.
But when compiling it gives me the error: "expected specifier-qualifier-list before 'Ipoint'"
However I have included the desired header that is "IPoint.h".
But when I use the cpp object in my class just by initi... | If you want to be able to #import your Objective-C class interface into both Objective-C and Objective-C++ code, you can use an #ifdef to declare the instance variable as void* for the former:
@interface MyClass : NSObject {
#ifdef __cplusplus
IPoint *point;
#else
void *point;
#endif
}
Unfortunatel... |
5,562,502 | 5,562,953 | Explain the following C++ method | #define XL 33
#define OR 113
#define NOR 313
#define TN 344
int to_bits(int critn,char *mask)
{
unsigned int x;
int begin;
if (critn < XL) begin = 1;
else if (critn < OR) begin = XL;
else if (critn < NOR) begin = OR;
... | In C++, just like most programming languages, you can only return one value. To "return" two values, it's a common C/C++ practice to return one and pass a pointer to an object and modify that object via the pointer (mask in this case).
The object that mask point to will be assigned a bitmask with exactly one bit set. T... |
5,563,000 | 5,563,131 | Implicit type conversion rules in C++ operators | I want to be better about knowing when I should cast. What are the implicit type conversion rules in C++ when adding, multiplying, etc. For example,
int + float = ?
int * float = ?
float * int = ?
int / float = ?
float / int = ?
int / int = ?
int ^ float = ?
et cetera...
Will the expression always be evaluated as the ... | In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).
if:
either is long double other is promoted > long double
either is ... |
5,563,676 | 5,563,888 | Compile C++ online in a Rails Application | I am looking for a compiler to compile C++ source code in a rails application. My idea is to get the source code as input, compile it and give the output back to the browser. Of course it should be secure and not really forwarded to the system C++ compiler. Is there maybe a ruby library which already do this job?
Best ... | The problem is not the compiler. You're problem is safely executing the code, which is VERY (yes, caps and bold) hard with something as low as C/C++.
In fact, it's almost impossible, your best bet would be a complete sandbox in which the code is going to be executed. There is no ruby library for this AFAIK, and I high... |
5,563,861 | 5,563,896 | Struct member initialisation | Whilst reading through the DirectWrite source code I came across the following struct:
/// <summary>
/// Line breakpoint characteristics of a character.
/// </summary>
struct DWRITE_LINE_BREAKPOINT
{
/// <summary>
/// Breaking condition before the character.
/// </summary>
UINT8 breakConditionBefore : ... |
Notice the strange " : " after each
member declaration. I'm going to
assume it's a default initialisation
value for the member variable.
It's not default initialization. It means breakConditionBefore is just 2 bit integer, isWhitespace is a 1 bit integer. And so on.
In DWRITE_LINE_BREAKPOINT, one 8-bit integer... |
5,563,906 | 5,563,980 | Compiling C++ into portable linux binaries | Ok, this question is about portable as in no dependencies (i.e. "I can put the binaries in a USB key and bring it with me everywhere, e-mail them to friends etc").
I have heard of static linking but I'm confused to what are exactly the consequences of it; what can and what can't be static linked (i.e. what about Qt, Op... | Static linking works for most libraries, but not those that use dynamically loaded modules. Just try and see if it works. You may still have issues with kernel compatibility; your program may be using system calls not available in older kernels.
The Linux Standard Base is supported by some Linux distros, but on Debian ... |
5,563,920 | 5,564,011 | Initializing a bidemensional array and change its values later | How can I initialize a bidimensional array first and change its values later?
I've tried using the following code:
class foo
{
public:
foo()
{
bar = {
{2, 2},
{2, 2}
};
}
private:
... | This syntax only works when initializing an array. Inside your constructor body, the array has already been initialized. The only way to do that now is to use a loop:
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; i++)
bar[i][j] = 2;
If you have the values in a global array or something, you can just cop... |
5,563,952 | 5,564,097 | Why there is no pop_front method in C++ std::vector? | Why there is no pop_front method in C++ std::vector?
| Because a std::vector has no particular feature regarding inserting elements at the front, unlike some other containers. The functionality provided by each container makes sense for that container.
You probably should be using a std::deque, which is explicitly good at inserting at the front and back.
Check this diagram... |
5,563,955 | 5,563,997 | C++ Copy Constructor | I have the next question:
If I have a class which containts for instance
Class A {
public:
A();
~A();
...
protected:
//Data
std::string str;
std::vector<char> vctChar;
std::vector<std::string> vctString;
}
and I use the DEFAULT C.Ctor and assignement. Suppose I know declare the object and use ... |
I use the DEFAULT C.Ctor and
assignement. Suppose I know declare
the object and use it for another
object as C.Ctor, will the new object
will have it own copy of data (string
and vectors
If your class doesn't has pointers, then the default copy-constructor and operator= generated by the compiler would make ... |
5,563,987 | 6,364,690 | Packaging C++ library into a Rails application for Heroku use | asked the next thing from Heroku support the other day:
I have an app that will
require a client library written in
C++. I
have doubts can that be done with
Heroku. Is it possible at all, any
alternatives how can a C++ library be
installed and used by an app with
Heroku?
And I got the next answer:
We ... | To wrap the C++ library in Ruby, you want Rb++.
Alternately, you can wrap the C++ library in C and then wrap that with Ruby-FFI.
I'm not sure what, if anything, one can do to get the native extensions compiled on Heroku. I'd contact their support and ask.
|
5,564,636 | 5,564,736 | Writing dynamically loadable components in c++ | I'm currently working on a program which should perform calculations on a home brewed data structure.
I want to build it in a way that it would be easy to add supported calculations (say, as source files which conform to a predetermined structure).
The problem is that I don't want to load all calculations in advance, b... | Using dlopen() is the most widely used way to load executable code dynamically in an application on POSIX-compatible operating systems. It allows using a modular architecture where optional or rarely used code is only loaded on-demand, which sounds pretty much like what you need.
I would certainly use this method - if ... |
5,564,697 | 5,564,802 | Virtual functions versus Callbacks | Consider a scenario where there are two classes i.e. Base and Derived. If the Base class wants to call a function of the derived class, it can do so by either making a virtual function and defining that VF in the derived class or by using callbacks. I want to know in what should be preferred out of the two? Choosing am... | I think this comes down to a decision about whether or not the behaviour you're talking about is something that belongs in the heirarchy that 'Base' knows about and child implements.
If you go with a callback solution, then the callback method (depending on signature) doesn't have to be implemented in a child of Base. ... |
5,564,767 | 5,565,094 | boost::filesystem: Updating from 1.34.1 to current | I've got some legacy code here that makes use of boost::filesystem in version 1.34.1. I've isolated it into a little test program:
#include <iostream>
#include <boost/filesystem/path.hpp>
int main()
{
// note the second parameter
boost::filesystem::path p( "/tmp/foo", boost::filesystem::native );
std::cou... | boost::filesystem defines two formats for filenames: native, which differs from system to system, and generic which is identical across systems. Under POSIX (which appears to be what you are using) the two are identical. Under Windows the native format allows backslashes whereas the generic format does not. Under VMS (... |
5,564,872 | 5,566,934 | Enable clang for project | I decided to test clang in my project. There is CMake build system so, I run such command:
cmake ../ -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++
MAKE_C_COMPILER= clang
CMAKE_CXX_COMPILER= clang++
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang
-- Check for working C co... | Clang has not implemented __is_trivial, so it seems like you're out of luck for now.
Link to bug report
|
5,565,062 | 5,565,093 | Are there a free Heap corruption detection tools for windows? |
Possible Duplicate:
Is there a good Valgrind substitute for Windows?
I need to debug and fix my heap corruption error. THere is one for linux - valgrind, but are there analogue for windows? I do not search for memory leaks. Memory corruption.
| Sure. Check out this list, and this SO question.
|
5,565,082 | 5,565,104 | comparing a character with a set of characters c++ | is there a way to compare a single character with a set of characters?
eg:
char a;
if(a in {'q','w','e','r','t','y','u'})
return true;
else return false;
i need something like this.
| std::string chars = "qwertyu";
char c = 'w';
if (chars.find(c) != std::string::npos) {
// It's there
}
Or you could use a set - if you need to lookup often that's faster.
std::set<char> chars;
char const * CharList = "qwertyu";
chars.insert(CharList, CharList + strlen(CharList));
if (chars.find('q') != chars.end()) ... |
5,565,199 | 5,565,231 | How do I get the handle to a brush, Win32 C++ | I'm creating a Dialog window with some button controls. I want the buttons to be coloured individually. I've searched and found something that I think I should use, the WM_CTLCOLORBTN Message.
As stated the return value should be a "handle to a brush".
I can create a brush, for example like this:
HBRUSH blueBrush=Creat... | I'm pretty sure the value returned by CreateSolidBrush is the handle (the H in HBRUSH stands for 'handle').
|
5,565,206 | 5,565,326 | How to draw rectangle using Qt to Xlib window | Let say that i have id of another Xlib window and i want to draw over this window rectangle.
Is there way to to draw it using Qt? I found on solution but it doesn't work for me:
QPixmap pix = QPixmap::fromX11Pixmap(wId, QPixmap::ExplicitlyShared);
pix.fill(QColor::fromRgb(255,255,255));
I expect it'll fill window with... | You could embed this window, place an invisible window on top and render into this invisible window. The effect would be the same : a rectangle over the window.
|
5,565,228 | 5,568,253 | Quantile functions in boost (C++) | Judging from the documentation boost seems to offer quantile functions (inverse cdf functions) for both normal and gamma distributions, but its not clear for me how can I actually use them. Could someone paste an example please?
| The quantile calculation is implemented as a free function. Here's an example:
#include <boost/math/distributions/normal.hpp>
boost::math::normal dist(0.0, 1.0);
// 95% of distribution is below q:
double q = quantile(dist, 0.95);
You can also get the complement (quantile from the right) using:
// 95% of distribution... |
5,565,522 | 5,565,706 | Can anyone explain this paragraph of the current C++0x standard draft? | Can anyone explain this statement from ISO N3242 §3.2, 2nd point
An expression is potentially evaluated unless it is an unevaluated operand
(Clause 5) or a subexpression thereof. A variable or non-overloaded
function whose name appears as a potentially-evaluated expression is
odr-used unless it is a... | "unevaluated operand" replaces "is the operand of the sizeof operator (5.3.3), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (5.2.8)". It has the same basic purpose, but doesn't try to list all the cases in the C++0x standard of operators whose operan... |
5,566,027 | 5,566,054 | What to do when two shared libraries depend on the same version of a third-party compiled differently? | My application depends on a certain version of xerces (compiled with specific flags):
$ ldd actimize_intelligence_server | grep xerces
libxerces-c.so.28 => ./libxerces-c.so.28 (0x00002b3c1518f000)
A shared library (received from a client) also depends on xerces (apparently compiled with different flags):
$ ldd lib... | You can't do that at all. Do not mess with binary compatibility like this- if you want to dynamically link to the same library, it must be compiled identically.
|
5,566,103 | 5,567,704 | how to use setDataBuffer from OCCI for array fetches | I have a query that I'm executing on a database that returns an array of records, I read in the Oracle OCCI documentation you have to use the ResultSet::setDataBuffer() function to fetch array's of data from the db.
I just don't get what I'm supposed to give as the first two args when a database row contains multiple ... | As per our comments, I provide a simple example using the getString(),... functions:
// Statement -> stmt
// ResultSet -> res
// Connection -> con
// pseudo code ahead !
stmt = con->createStatement(MY_SELECT, MY_TAG);
stmt->setPrefetchRowCount(NUMBER_OF_PREFETCHES); // enable bulk collect
res = stmt->executeQuery();
... |
5,566,192 | 5,571,829 | boost-spirit numeric parsers and getting the desired synthesised attributes | --edit -- Solved the question : a comment on the last sidenote would be helpfull. Also comments on phoenix::bind overload handling would be helpfull (in my answer).
I'm working on a system with strict typing requirements, I want to ensure that I am parsing integers that meet the constraints of int32_t and int64_t, I wa... | 1) Qi parsers already check for overflow conditions. The parser component will fail if the input is not representable by the type the component is supposed to match. For instance, int_parser<int32_t, 10> will fail for numbers not fitting into a signed 32 bit integer.
You can use the long_long parser (i.e. the predefine... |
5,566,245 | 5,566,463 | Why same types are different? | Why this (char is signed on my implementation):
cout << std::is_same< char,signed char>::value;
outputs false?
| The three types were introduced at different times.
From the C99 Rational:
Three types of char are specified:
signed, plain, and unsigned. A plain char may be represented as either signed or unsigned
depending upon the implementation, as in prior practice. The type signed char was
introduced in C89 to make availa... |
5,566,452 | 5,566,624 | Macro function with several lines for the parameter? | In C++,
I need to defined a macro.
That macro would take as parameter a "block" of code.
Can we safely use several lines of code as parameter of a macro function?
I was asking myself if :
is the following code valid, defined as valid by the standard, as in "cross-platform"?
is there a better way to do the same (I can'... | 16.3/9:
Within the sequence of preprocessing
tokens making up an invocation of a
function-like macro, new-line is
considered a normal white-space
character.
So the multi-line macro invocation in general is fine. Of course if DOSOMETHING and DOANOTHERTHING don't introduce braces for scope, then your particular... |
5,566,795 | 5,568,371 | Portable library to play samples on individual 5.1 channels with C/C++? | I'm looking for a free, portable C or C++ library which allows me to play mono sound samples on specific channels in a 5.1 setup. For example the sound should be played with the left front speaker whereby all other speakers remain silent. Is there any library capable of doing this?
I had a look at OpenAL. However, I ca... |
I had a look at OpenAL. However, I can only specify the position from which the sound should come, but it seems to me that I cannot say something like "use only the front left channel to play this sound".
I don't think this is quite true. I think you can do it with OpenAL, although it's not trivial. OpenAL only doe... |
5,567,201 | 5,567,254 | c++ Service is stopping with error "this application has requested the runtime to terminate it an unusual way" | I have a c++ NTservice which is being accessed by SAP modules through rfc calls. Now this service is getting stopped with a message that "this application has requested the runtime to terminate it an unusual way" and then showing some IE script error that points to url "res://C:\WINDOWS\System32\mmcndmgr.dll/views.htm"... | That error message (at least usually) means you had an uncaught exception. You could start by adding a try/catch(std::exception const &e)/catch(...) to your ServiceMain, in an attempt at catching the exception and if it is a derivative of std::exception, printing out its what() to see what it has to say for itself...
|
5,567,271 | 5,578,635 | how can iterate foreach item in QListWidget | i just can find any example in the internet how to loop and get each item in the QListWidget
| int count = listWidget->count();
for(int index = 0;
index < count;
index++)
{
QListWidgetItem * item = listWidget->item(index);
// A wild item has appeared
}
The foreach thing is totally different, I think.
If you want more info on that, look at this
http://doc.qt.digia.com/4.2/containers.html#the-fore... |
5,567,287 | 5,567,313 | What causes std::bad_function_call? | I've seen a few questions that refer to the std::bad_function_call exception, but haven't been able to find out any by Googling about what causes this exception.
What kind of behavior is supposed to cause this exception? Can you give me minimal examples that don't have other semantic problems also going on?
| Sure- the easiest is where you try to call a std::function that's empty.
int main() {
std::function<int()> intfunc;
int x = intfunc(); // BAD
}
|
5,567,342 | 5,567,548 | Unary and Binary Negation | The C++1x standard has deprecated the old STL binder functions in favor of the more universal std::bind. However, it seems that std::not1 and std::not2 are not deprecated in favor of a universal std::not_ or something. The reality is that the <functional> part of the STL, prior to C++1x, was really cumbersome to work... |
You didn't miss it.
Compelling reason? It depends on who you ask. The lack of this functionality was discussed, but not until very late in the process. Hmm... I can't find the paperwork on that at the moment, there may not be any.
The best solution for this (imho) is to add operator!() to bind. But by the time thi... |
5,567,529 | 5,567,571 | What makes a static variable initialize only once? | I noticed that if you initialize a static variable in C++ in code, the initialization only runs the first time you run the function.
That is cool, but how is that implemented? Does it translate to some kind of twisted if statement? (if given a value, then ..)
void go( int x )
{
static int j = x ;
cout << ++j <... | Yes, it does normally translate into an implicit if statement with an internal boolean flag. So, in the most basic implementation your declaration normally translates into something like
void go( int x ) {
static int j;
static bool j_initialized;
if (!j_initialized) {
j = x;
j_initialized = true;
}
... |
5,567,555 | 5,567,678 | How does OPENCV calculate eigenvalues and eigenvectors? | Does anyone know what algorithm is used for eigenvalue and eigenvector computation in the OPENCV library? Is it a suitable library for computing large scale eigenvalue problems?
| There seems to be a function called cvEigenVV, which can be used to calculate eigenvectors and corresponding eigenvalues of symmetric matrices.
It looks like this:
double cvEigenVV(CvArr* mat, CvArr* evects, CvArr* evals, double eps = 0);
more info here
hth
|
5,567,562 | 5,568,044 | How to check an empty space (NULL) in double pointers | I am trying to use an 'if' condition to check whether a location for an object is empty or not. I am using double pointers for this. Please see the code below:
void show_room :: buy_car(int clmn, int row)
{
int row = row;
int clmn = clmn;
string car_door_col;
string temp1;
float temp2;
int temp3... | Assuming you've already initialized the elements of HBM to 0, and you're remembering to reset them to 0 after deleting the objects they point to, you can simply do:
if(this->HBM[clmn][row]) {
// ...
}
|
5,567,992 | 5,568,353 | Address of static const isn't const expression? | I though address-of-static was a constant expression as in the example below but I get a compiler error (or is this new to C++0x?)
class X {
static const int x;
enum { y = &x };
};
| Reading the 1998 standard, 5.19(1): "In several places, C++ requires expressions that evaluate to an integral or enumeration constant...as enumerator initializers (7.2)...."
Further, "An integral constant-expression can involve only....In particular, except in sizeof expressions, functions, class objects, pointers, or... |
5,567,995 | 5,568,296 | line of intersection: error in vector functions | i want to compute intersection line, given by 2 planes. my main program gives me, plane parameters a,b,-1,d (my equation is ax+by-z+d=0). so, my function for computing equation of intersection line is as;
vector<double> LineofIntersection(vector<double> plane1,vector<double> plane2) {
double a1=plane1.at(0); do... | Fundementally, your problem is that you are assigning to locations in the point vector without first allocating them. Additionally, pointout serves no purpose, and you have a syntax error. Here are my recommendations:
vector <double> point; vector <double> pointout;
This line appears twice. Delete the line the first ... |
5,568,377 | 5,568,431 | Debugging c++ core files for released software | I'm trying to find a way to debug core files sent to me from released versions of my software (c++ code compiled with gcc). Ideally, I'd like to be able to deploy release builds, and keep debug builds on hand to use for debugging, so I have symbol tables, etc.
My problem is that (as I understand it) the debug and relea... | You can compile and link with optimization turned on and still generate debug symbols (-O3 -g) and then extract the debug symbols. This way you'd have the debug symbols around but can ship without them, and you won't have a performance penalty or something. See How to generate gcc debug symbol outside the build target?... |
5,568,793 | 5,568,971 | C++ Vector Math and OpenGL compatible | I've been doing lots of vector math stuff and wrote my own template for it.
My requirements are lots of vector maths (addition, subtraction, scale, cross prod, and dot prod) also I need to be able to pass my vector as a float[] so that openGL can make use of it.
I've been using this quite happily for sometime, today a ... | You may want to consider using GLM instead. It does all that you've described (though I found the documentation lacking) including integration with OpenGL.
|
5,568,979 | 5,569,139 | Why chdir("~/dev/") returns -1? | In my c++ application I want to change working directory to specified one. But when I specifying "~/dev/" as working directory chdir() fails and returns -1. Instead it works when I'm specifying "/home/myusername/dev". Why this happens? How can I solve this problem (except of checking if string first charachter is ~ and... | The expansion of tilde (~) to HOME environment variable is done by bash. That expansion is done before that is passed to chdir command. The bottom line is ~ is handled by bash, not by chdir command. So you can not use it in chdir() function call.
In order to find other kind of expansions (and the details of ~ expansio... |
5,568,982 | 5,569,086 | How do I statically link external libraries into my executable? | I don't want to have the end use have to have the libraries installed, so, having the libraries packaged in my exec would be preferred.
this is the relevant line in the make file:
hPif : src/main.o src/fann_utils.o src/hashes.o src/Config.o
g++ -o hPif src/main.o src/fann_utils.o src/hashes.o src/Config.o -stati... | The -static flag is correct, but you need to make sure your libraries are static libraries without dependencies. If they are built as shared (or have shared dependencies), gcc will not link them statically (and/or you will still have library dependencies).
You may need to rebuild your Boost libraries to achieve this.
|
5,568,997 | 5,569,155 | Unitialized int value always the same (C++) | Given this code:
void main()
{
int x;
cout << x;
system("pause");
}
When I debug this piece of code, it always prints -858993460A. I read that its because VS set this as default value for Unitialized vars. But I also read that in release mode, this should get random value. But everytime I run this code in release mod... | The main is not the real entrypoint of the executable, in general the real entrypoint is taken by the runtime library (and in VC++ is definitely like that), which performs some CRT initialization tasks and then calls your main. That value is probably a leftover of one of the function calls performed by the initializati... |
5,569,004 | 5,569,056 | Is it possible to access member name from parameter | Please consider this class:
class A
{
public: //public in this example
string a1;
string a2;
string a3;
string a4;
int a5;
double a6;
(...) plus other 50 member names
multiset<string> getAttrib(const vector(A)& va, string attr)
{
for (vector<string>::const_iterator ci = va.begin; ci != va.e... | There's not a direct way to do what you want in C++, although there are some reasonable attempts at reflection frameworks out there. You might also look here: How can I add reflection to a C++ application? for additional commentary about reflection. I would suggest, however, that instead of having 50 member variables... |
5,569,115 | 5,569,183 | c++ abstract base class private members | Just wanted some clarification.
Should abstract base classes never have private members? For example
class abc{
public:
virtual void foo()=0;
private:
int myInt;
}
you can never access myInt since you cannot create an instance of abc and it will not be in a derived class since its private.
Is there any situation w... | In C++ you can have an abstract class that has non pure virtual methods. In that case, and depending on the design it can make sense to have private members:
class base {
std::string name;
public:
base( std::string const & n ) : name(n) {}
std::string const & getName() const { return name; }
virtual void f... |
5,569,127 | 5,570,824 | c++ on low memory systems. Standard libs are using all the memory! | I need to shave off as much memory as possible. I am using standard C++ with STL. The program does not do much (yet) and it still takes 960Kb [according to top]! The executabe size is only 64KB.
The code is 3000 lines long, I am not going to post obviously. I believe the problem is not with my code, but with the system... | Start stripping out functionality until the memory usage goes down. Go extreme first -- if you can replace main with sleep(1000); and your memory use is still high, look to code and static data -- anything initialized at global scope or static inside a class or function, along with template instantiations of different... |
5,569,317 | 5,569,519 | MSVC generates strange/slow binary for some multiplications and divisions | I use MSVC 2010 SP1 and I have the following line of C++ code:
int32_t c = (int64_t(a)*int64_t(b))>>2;
When a and b are not constants, MSVC correctly generates a 32 bit imul and shrd instructions. But when a or b are constants it generates a call to _allmull instead of the imul instruction. Could there be any reason f... | Partially related: if you want to be sure to exploit the imul capability of performing 32x32=>64 bit multiplication, you can use the Int32x32To64 "fake API" (actually a macro):
Multiplies two signed 32-bit integers, returning a signed 64-bit integer result. The function performs optimally on 32-bit Windows.
This funct... |
5,569,416 | 5,572,086 | How can Duff's device code be compiled? | I understood why Duff's device is faster than normal loop code which can be unrolled but is not optimized. But I can't understand how the code can be compiled yet.
I guess it's a trick about the switch syntax. But not anymore.
How can do while sentence exist in switch sentence? Very weird.
Is there anyone who can exp... | A simple explanation of why Duff's Device compiles is that the syntax of the switch statement isn't particularly specific about the form that the switch statement block might need to take. There are a few restrictions, and a couple of things permitted in the controlled statement that aren't permitted outside a switch ... |
5,569,423 | 5,569,643 | Strange behavior with QT and OpenGL | When trying to draw on an OpenGL widget with QT, the window display ends up rather distorted.
All that's being done is the screen is cleared.
#include "glwidget.h"
// Mainwidget is a sub-class of GLWidget
GLWidget::GLWidget(QWidget *parent) :
QGLWidget(parent)
{
}
void GLWidget::resizeGL(int width,int height)
... | Try clearing the color buffer occasionally. Note glClearColor() just latches some state and doesn't actually clear any buffers.
|
5,569,453 | 5,569,713 | C++ - Output all possible DNA kmers of a given length | A "kmer" is a DNA sequence of length K. A valid DNA sequence (for my purposes) can only contain the 4 following bases: A,C,T,G. I am looking for a C++ algorithm that simply outputs all possible combinations of these bases in alphabetical order into a string array. For example, if K = 2, The program should generate t... | You would need to use recursion to be flexible (i.e. so that you could change K easily).
void populate(int depth, string base, string* kmers, int* kmers_offset)
{
if(depth == K)
{
kmers[*kmers_offset].assign(base);
(*kmers_offset)++;
}
else
{
static char bases[] = { 'A', 'C',... |
5,569,490 | 5,577,551 | How to implement this type specific object generator without using C++0x auto | I have a templated function where the templated parameter is a functor. I want to generate some internal variables, specific to a particular quality function, to be used by other template functions called from this functor. so I have experimented with the auto keyword and it seems to work
template<typename QF>
float ... | This should work out of the box:
template<typename QF>
float find_optimal_partition_louvain_with_gain(QF quality_function) {
return do_some_work(gen(quality_function));
}
If you need internal_variables to be around longer than for just one call, you can use another small function to deduce the type:
template<typen... |
5,569,644 | 5,569,677 | Is there a downside to leaving in debug symbols in release builds? | I'm trying to determine whether there are any downsides to building release binaries with debug symbols left in. For our release builds, we compile with -O3 at the moment and if there are any crashes, the cores are next to useless.
So, what I would like to do is modify the build to leave in debug symbols, i.e. -O3 -g, ... | Separate symbols from binary.
g++ -ggdb -o target obj1.o obj2.o ...
strip target --only-keep-debug -o target.dbg
strip target
Then in gdb, use symbol-file target.dbg
EDIT: On the actual question:
The downsides are:
Easier reverse engineering (if that worries you)
Larger binaries
Execution speed is not affected - Deb... |
5,569,765 | 5,570,911 | Download and instantiate COM control | I am using ff-activex-host to host a .NET ActiveX control in Firefox and Chrome. It will instantiate a registered COM control, or download one in a cab file, register it, then instantiate the COM control. Unfortunately, the first means that I can't update the control's dll with changes from the server, and the second o... | Unfortunately, the COM DllRegisterServer entry point is usually hard coded to install component registrations into the HKEY_CLASSES_ROOT hive, which will result in them being created in HKEY_LOCAL_MACHINE\Software\Classes, making it impossible to install without administrator access.
If you know ahead of time what COM ... |
5,569,868 | 5,569,921 | forwarding parameters from variadic function to fixed argument function | I have a function which takes a variable number of arguments. From this function I want to call functions that take fixed number of arguments,
void log(int level, const char* format, ...)
{
va_list args;
va_start(args, fmt);
int count = 0;
void *navigator[10] = NULL;
while ((navigator[count] = va_... | Your va_start needs to be va_start(args, format); // Note change to "format".
EDIT: Even with this according to the manpage fro va_arg you can't do what you want.
If there is no actual next argument,
or iftype is not compatible with the type of the actual next
argument (as promoted according to the defa... |
5,569,943 | 5,947,180 | Qt unit test dependency problem | Hee,
I'm kinda new to Qt and i started to add UnitTests to my Qt project. Qt demands that i put my unit tests in another project, so i did.
But now i have dependent source files in my first project. I made my 'main project' a dependency of my 'test project'.
I cannot seem to include any of the '.h' files from my 'main ... | Did you try to include your dependencies to .pro file of your test project?
HEADERS += ../MyHeader.h
SOURCES += ../MyHeader.cpp \
tst_myUnitTestName.cpp
|
5,570,131 | 5,570,190 | C++: how do I pass a variable for multiple arguments? |
Possible Duplicate:
Passing Variable Number of Arguments with different type - C++
I have a function that takes n arguments.
And I want to call it like, function_name(number_args - 1, input, args_from_console[], output)
How do I do that?
*the function that takes n arguments already is written and works... I just don... | Rewrite the function so it doesn't need that. Have it take a vector, instead of an array, then the number of arguments can be retrieved from the size() function.
If I understand you correctly, the function you want to call looks something like this(Ignore the argument types, I'm just using all ints for simplicity's sa... |
5,570,303 | 5,570,324 | Scope Resolution::Nested Template Typename | My overloaded prefix operator is having issues finding the scope.
#ifndef LIST_H
#define LIST_H
#include <iostream>
using namespace std;
template <typename T>
struct node
{
T data;
node* next;
node* prev;
};
template <typename T>
class list
{
public:
class iterator
{
public:
... | The function name is not properly qualified and the return type has an extra iterator:
template <typename T>
typename list<T>::iterator::iterator& iterator<T>::operator ++()
This needs to be:
template <typename T>
typename list<T>::iterator& list<T>::iterator::operator++()
Note also that using using namespace std; an... |
5,570,386 | 5,570,413 | Square bracket arrays |
Possible Duplicate:
Is array name a pointer in C?
So, I usually declare arrays using pointers.
However, you can also declare arrays using square brackets notation:
char a[] = "ok" ;
char b[] = "to" ;
char *pa = a ;
cout << "a " << sizeof( a ) << endl ; // 3
cout << "pa " << sizeof( pa ) << endl ; // 4
The peculi... |
Why is that? It seems as though a is the array and not a pointer to the array ("left operand must be l-value" is the error for a = b above).
a is indeed an array type and not a pointer type.
You cannot assign to an array because it is a non-modifiable lvalue.
BTW Array decays to pointer to the first element when it i... |
5,570,447 | 5,570,557 | C++: How do I pass N arguments to a function where N can be any number > 0? (The function already exists as part of an external library) | This is the way I currently call the function:
struct fann *ann = fann_create_standard(
num_layers,
num_in,
optional_num_1,
optional_num_2,
num_out);
the function above can have at leas... | can't you use fann_create_standard_array to do what you want? Arrays can be dynamically created, whereas argument lists should be specified during compilation.
|
5,570,514 | 5,570,554 | Incremental number using the "Curiously Recurring Template Pattern" | I want to implement a class Address that, when created, initializes its field addr to a unique value. That value has to increment by one every time I create an Address instance.
Let's make an example. After the following code has been executed:
Address x;
Address y;
x.addr should be 1, while y.addr should be 2.
To acc... | You don't really need it here, because you don't need to capture destruction of the object. You'll note that the example on that Wikipedia page keeps a running total of how many objects exist of the type, so CRTP has two handy features:
because it's a base class, its destructor is called (a member would also achieve t... |
5,570,752 | 5,695,311 | Google Test C++: Is there a way to read the current console output in a test? | Let us assume I have a to be tested class that has the following method:
void
MyClass::sayHello()
{
std::cout << "Hello";
}
Now, within my google test I would like to verify that this output has been made. What would be the lastConsoleOutput equivalent be as used in my pseudo code below?
// Tests if sayHello() outp... | In this case I would avoid redirecting or testing for values in stdout or stderr, since the access to those streams is not threads-safe in a way that output buffer may not be appended and flushed as possibly predicted.
From a testing perspective I would suggest refactoring the method to be stateless and keep the state ... |
5,570,975 | 5,571,012 | File compression with C++ | I want to make my own text file compression program. I don't know much about C++ programming, but I have learned all the basics and writing/reading a file.
I have searched on google a lot about compression, and saw many different kind of methods to compress a file like LZW and Huffman. The problem is that most of the... | Most of the algorithms are pretty complex. But they all have in common that they are taking data that is repeating and only store it once and have a system of knowing how to uncompress them (putting the repeated segments back in place)
Here is a simple example you can try to implement.
We have this data file
XXXXFGGGJ... |
5,571,072 | 5,573,673 | How to add an extra button to the window title bar, so it will be work as standard? | Firstly I want mention that I have already read all articles on SO on subject, but still have no answer for my question. Also my question slightly different than others.
Today a I have a look on Skype window. There is one extra button on it's title bar. But this button acts as native system button. Just look on glowing... | In Vista and Windows 7 there is a new thing called the Desktop Window Manager. This is used to draw the "Aero glass" window titlebars, and do the glow effects. The old Windows XP approach of implementing WM_NCPAINT handlers doesn't work with this new system, so you have to use a whole new API.
I'm sure I've seen some a... |
5,571,103 | 5,571,400 | Display Name=Value of all environment variables in C++ | Newbie question:
I want to print the name and value of every environment variable of my process to stdout. The following example prints the value of every environment variable but not the name. How can I additionally print the name ?
int main(int argc, char **argv, char** envp) {
char** env;
for (env = envp; *env !... | Just in case this doesn't get closed and people wind up here. Usually, each value pointed to by *envp would be a string of the form:
<EnvironmentVariableName>=<EnvironmentValue>
Such as (taken from ideone.com):
TMPDIR=/home/Cat5sW
PATH=/usr/local/bin:/usr/bin:/bin
PWD=/home/Cat5sW
LANG=en_US.UTF-8
SHLVL=0
HOME=/hom... |
5,571,137 | 5,571,209 | Can I use Eclipse as a framework for a new cross-platform GUI? | I want to develop a new powerful GUI for an existing C++ application. I planned to do it as a standalone project in C++/QT, and it would communicate client-server with the existing application.
Recently I've been told that there is another possibility, to create such GUI using Eclipse. I mean that Eclipse can serve no... | Yes, absolutely, the Eclipse "Rich Client Platform" is an application framework comparable to Qt, in some ways, and superior in other ways. RCP's frameworks are generally more sophisticated and more powerful than anything in Qt. Yes, I realize I'm inviting flames, because people do have religious wars over this. I don'... |
5,571,187 | 5,571,197 | Operator precedence, which result is correct? |
Possible Duplicate:
Undefined behavior and sequence points
What is the value of x after this code?
int x = 5;
x = ++x + x++;
In Java, the result is 12, but in C++, the result is 13.
I googled the operator precedence of both Java and C++, and they look the same. So why are the results different? Is it because of the... | In Java it's defined to evaluate to 12. It evaluates like:
x = ++x + x++;
x = 6 + x++; // x is now 6
x = 6 + 6; // x is now 7
x = 12 // x is now 12
The left operand of the + (++x) is completely evaluated before the right due to Evaluate Left-Hand Operand First. See also this previous answer, and this one, on similar... |
5,571,393 | 5,571,527 | How to set parent members when creating inherited struct in C++ | I have a struct type A, which I could instantiate with A(p_a1, p_a2) and a struct type B, which inherits from A, that I can instantiate with B(p_b1, p_b2, p_b3).
Is there a standard way to create a B instance while also setting p_a1 and p_a2? Would I just set them after creating the B instance with b.p_a1 = v_a1; b.p_a... | What you intend to do is achievable using initialization lists and can be done as follows:
struct A
{
A(int _a):a(_a){}
};
struct B : public A
{
B(int _a, int _b):A(a), b(_b){}
} ;
In the sample code which you have provided, what you are doing in these lines b.p_a1 = v_a1; b.p_a2 = v_a2 is cal... |
5,571,847 | 5,571,946 | Problem with declaration of an array of pointers | When i execute this code
#include<stdio.h>
int main() {
int (*x)[5];
printf("\nx = %u\nx+1 = %u\n&x = %u\n&x + 1 = %u",x,x+1,&x,&x+1);
}
This is the output in C or C++:
x = 134513520
x+1 = 134513540
&x = 3221191940
&x + 1 = 3221191944
Please explain. Also what is the difference between:
int x[5] and int (*x)[5] ?
|
int x[5] is an array of 5 integers
int (*x)[5] is a pointer to an array of 5 integers
When you increment a pointer, you increment by the size of the pointed to type. x+1 is therefore 5*sizeof(int) bytes larger than just x - giving the 8048370 and 8048384 hex values with a difference of 0x14, or 20.
&x is a pointer to... |
5,571,973 | 13,982,141 | SetWindowLongPtr doesnt work properly | I want to subclass RichEdit in my program (here is c++ code: http://dumpz.org/46182/). _native_log is a hwnd of richedit. At first all works fine and LogWindow::wndProc callback called normal, but if i set some text in RichEdit or click on them LogWindow::wndProc stops work (there no any further calls of it). Is there ... | Starting with Common Controls version 6 the procedure of subclassing windows has been revised to eliminate the issues with previous versions. In particular it is no longer a problem if a control is subclassed more than once.
A comparison between subclassing pre-v6 Common Controls and the v6 way of doing things can be f... |
5,572,002 | 5,572,046 | C++ integer type: special meaning for certain values | We are warned against magic numbers in code with good reason, but is there a good, expressive and type-safe way to solidify constants which have special meaning? I can think of two possible ways:
Method 1:
typedef int NumberOfThreads;
const NumberOfThreads automaticNumberOfThreads = 0;
Method 2:
class NumberOfThreads... | I don't agree with what you do in method 1. There is no need for NumberOfThreads type. That is a constant actually, "number of threads" and the number is an integer. So this is enough and more readable in my opinion.
const int NumberOfThreads = 0;
|
5,572,164 | 5,572,298 | Refer to derivative function | I have a base class and a few derivative. I have to 'register' some static function from each of them. Here is the example:
class Base
{
// Some interface...
};
class Der1 : Base
{
static void Do();
};
class Der2 : Base
{
static void Do();
};
void processStatic()
{
SomeFunc(Der1::Do);
SomeFunc(Der2::Do... | EDIT: Completely replacing previous answer due to clarified requirements.
You could use the CRTP to declare a specialized base class that does nothing more than call your registration function:
#include <iostream>
void SomeFunc(void(*fp)()) {
(*fp)();
};
template <class D>
struct ExtraBass {
ExtraBass() {
stat... |
5,572,309 | 5,572,920 | Call order refer to some information | now I have std::map<std::string, Object> myMap. Class Object has funcions: int getPriority() and void Work(). Now I go through the map and want to call Work due to the priority of object.
I wrote very crazy idea: the clone of that map, but it stores in the key it's priority, for example:
myMap["3_key1"] = Object();
my... | Use Boost.MultiIndex:
// your class
#include <iostream>
#include <string>
class foo
{
public:
foo(std::string name, unsigned priority, std::string msg) :
mPriority(priority)
{
mName.swap(name); // primitive std::move :)
mMsg.swap(msg); // (default-construct & swap)
}
const std::str... |
5,572,559 | 5,572,594 | C++ string of a specific length | I'm trying to write a function that has a concept of a "serial number". It has a specific length. I'm hoping to simplify the constructors by creating a new type called SerialNumber that wraps this concept of a 13-byte number. For instance, I don't want a Product(const char* m) or Product(const std::string& str) that... | The easiest way would be to create a constructor which accepts a std::string, and then within your constructor verify that the length is indeed 13. If it's not, simply throw an exception -- that's why they exist. Keep in mind that a char[13] won't guarantee that the string is 13 characters long, after all it could be "... |
5,572,658 | 5,572,738 | Is this a valid way to take a list of digit characters and use them to create a long integer? | Is this a valid way to take a list of digit characters and use them to create a long integer?
LongInt operator+(const LongInt& x, const LongInt& y)
{
int xCount = 1;
long int xValue = 0;
list<char>::iterator it;
//x.val is a list<char> that contains the digits needed to create the long int
for(it =... | No, and I explained how to do it in your previous thread, except that I was wrong with the reverse iterator. You have to start from the beginning not the end. Sorry about that confusion.. This should be enough:
list<char> digits;
digits.push_back('1');
digits.push_back('2');
digits.push_back('3');
long ... |
5,572,726 | 5,586,694 | How is it possible to lock a GMutex twice? | I have a test program that I wrote to try and debug a GMutex issue that I am having and I cannot seem to figure it out. I am using the class below to lock and unlock a mutex within a scoped context. This is similar to BOOST's guard.
/// @brief Helper class used to create a mutex.
///
/// This helper Mutex cl... | What was happening in my case was there was another thread that was calling g_cond_timed_wait function with the same mutex, but with the mutex unlocked. In this case, g_cond_timed_wait function unlocks a mutex that is not locked and leaves the mutex in an undefined state, which explains why I was seeing the behaviour ... |
5,572,946 | 5,572,978 | exact mechanics of istream::operator>> to string | I'm just not seeing this:
std::istringstream stream(somestring);
string temp;
stream >> temp;
In the last line, what is the exact function called? I can't find it in the list on cplusplus.com. Thanks!
| If memory serves, it's a non-member function overload -- have a signature something like:
std::istream &operator>>(std::istream &is, std::string &s);
(For the moment I've left out the fact that both istream and string are really typedefs of template instantiations).
|
5,573,058 | 5,573,452 | Can't run programs on my mac | I've been programming on windows for about three months now and when my computer finally died I bought a mac. I'm really happy with it except I can't figure out how to run my c++ programs.
On windows it would open up in command prompt so I figured it would do the same thing except with terminal.
After I write my progra... | Assuming that you're trying to write a program that you interact with on the command line, you want to create a "Command Line Tool" project, found under "Application" in the Mac OS X section of the New Project dialog. Choose "C++ stdc++" from the "Type" dropdown, as well. This will give you a main.cpp that should look ... |
5,573,318 | 5,573,406 | C++ syntax ambiguity | Consider:
void f(std::pair<bool,bool> terms = std::pair<bool,bool>(1,1)) {}
gcc 4.4 is ok, gcc 4.3 complains error: expected ',' or '...' before '>' token. The fix is:
void f(std::pair<bool,bool> terms = (std::pair<bool,bool>(1,1))) {}
What's the reason? Is it a bug in 4.3?
| This was a known issue. It thinks that the second comma separates parameter declarations. This comes from the fact that in a class definition, function default arguments are first only tokenized, and then only later parsed when the full class body has been read. As it thus doesn't really parse the default argument, it ... |
5,573,346 | 5,573,403 | Is it too much to allocate 16kb on the stack? | I need to instantiate a char[16384] buffer before calling a c function. After the function returns I will read some parts of it and discard it.
Is it ok to allocate it on the stack or should I use the heap?
EDIT: I'll add some information. The code will run on several platforms, from PC to iPhone, where I guess the sta... | It's hard to give a definitive yes or no to this question because the answer is highly dependent on your environment and at what point in the program the function which allocates the memory is invoked.
Personally though if I saw this in a code review I'd raise a red flag. That's a lot of memory to be using for a sta... |
5,573,532 | 5,573,991 | UAC, requireAdministrator and files access | I have a problem with UAC on Vista/7. My installer with UAC Execution Level = requireAdministrator installs and runs my app. App UAC Execution Level = asInvoker. So first time app runned by installer -- it runs as administrator. Then, app creates some files to store self state. Later -- if app launched by user, not as ... | Are your installing application for current user only or for all users on the machine?
For per-user installation it makes sense for the installer to create initial application state in the user's AppData folder. MSI runs per-user installations NON-elevated, so there is no problem with files in AppData folder your appl... |
5,573,547 | 5,573,608 | Problem with Euler 27 |
Euler published the remarkable quadratic formula:
n² + n + 41
It turns out that the formula will produce 40 primes for the consecutive
values n = 0 to 39. However, when n =
40, 40^(2) + 40 + 41 = 40(40 + 1) + 41
is divisible by 41, and certainly when
n = 41, 41² + 41 + 41 is clearly
divisible by 41.
Using c... | Your isprime method is inefficient -- but also wrong:
for (test = c; test > 1; test--) {
if (c % test == 0) {
return false;
}
}
in the first iteration of the for loop, test = c, so c % test is just c % c, which will always be 0. So your isprime method claims everything is non-prime (other than 2, 3, 5... |
5,573,676 | 5,573,723 | Invalid Null pointer - C++ - VS2010 | I am getting an Assertion failed error stating Expression: invalid null pointer and it points to c:\program files\microsoft visual studio 10.0\vc\include\xstring line:930.
Here is my code:
void main(void)
{
// fillMap() fills map with data from txtfile and returns map<char,int>
map<char, int> myMap = fillM... | Based on the fact that the crash happens in a function named assign, my suspicion is that MyClass (directly or indirectly) contains a pointer member but you haven't defined the assignment operator (and possibly neither the copy constructor and the destructor) properly. In fact, you write
it won't let me create new obj... |
5,573,752 | 5,573,779 | Inheritance without containing? | I have class A. And I have class B. And I have many-many classes derived from class B.
I want to achieve this: derivatives of B should have access to the protected variables of A. Whithout each of them containing an instance of A, which would need a lot of memory.
So I guess public inheritance is not a good idea this t... | You could do it with friend and accessor functions. This does trust B to stay off A's privates - don't see a good way to let only B and subclasses access only protected members of A unless there's an inheritance relationship between A and B.
class A {
friend class B;
protected:
int X;
};
class B {
protected:
stat... |
5,573,964 | 5,573,974 | Using multiple headers and cpp files help | I'm making an app with DragonFireSDK and I want to organize my multi thousand line app with .cpp and .h files
I get tons of errors when trying to do stuff though
So my app.cpp (main, required one) looks like this
Code:
#include "DragonFireSDK.h"
#include "SaveData.h"
#include "Structures.h"
#include "Definitions.h"
#i... | Don't #include the .cpp files.
The C compilation model is that each function is defined precisely once, i.e. in exactly one compilation unit (i.e. one object file). You compile each source file independently into a separate object file (#include-ing header files so that the compiler knows e.g. the prototype of functio... |
5,574,407 | 5,600,018 | VMR9 vs EVR : How to use ImageCompositor with EVR? | I've coded a PixelShader compiler/tester that works live on the Image or Video source that is playing using DirectShow.Net + VMR9.
And it was all good until I decided to give it a go as a real video player, and started adjusting every bit of it to work as it should (titles,etc).
Then I found out that video is very pixe... | Since nobody had suggestions I dig up a little and think I have found out what could be the solution:
http://msdn.microsoft.com/en-us/library/bb530107(v=vs.85).aspx
This should be now done in the custom presenter...
|
5,574,432 | 5,575,270 | polynomial linked list with two structs and its problems | #include <iostream>
using namespace std;
struct Term;
struct Node;
typedef Term* termPtr;
typedef Node* list;
list cons(int degree,int coeff, list p);
struct Term
{
int degree;
int coeff;
};
struct Node
{
termPtr term;
list link;
};
class polynomial
{
private:
list poly;
static const int VARIABL... | The reason poly == NULL is not true is that poly is uninitialized. The initialization poly(NULL) only occurs in the other constructor, which is not used.
Probably it is best to eliminate the list type in favor of std::list (actually, it is a very bad idea to use list as an identifier in conjunction with using namespace... |
5,574,451 | 5,574,500 | Grayed-out class methods in Visual Studio drop-down menu | What does it mean when a class method is grayed out in the drop-down menu above the text editor? I'm working in VS 2008.
| It means that the method is defined in a file other than the one you're working in.
|
5,574,469 | 5,574,562 | Are there any fully conforming C++ implementations? | So I was trying out some features of C++0x using GCC, but I also wanted to make sure the code could be compiled with a standard C++ compiler. So I was playing around with the __cplusplus macro with ifdefs to exclude C++0x code when it wasn't asked for.
I found that the value of __cplusplus wasn't 199711L, it was 1! Aft... | It is unlikely that any compilers other than Comeau will be fully compliant in the near future due to the prohibitive complexity of implementing the export keyword. For reasons why, see Why We Can't Afford Export.
|
5,574,499 | 5,574,534 | How can I avoid the LNK2005 linker error for variables defined in a header file? | I have 3 cpp files that look like this
#include "Variables.h"
void AppMain() {
//Stuff...
}
They all use the same variables inside them so they have the same headers but I get stuff like this
1>OnTimer.obj : error LNK2005: "int slider" (?slider@@3HA) already defined in AppMain.obj
Why is that?
| Keep in mind that a #include is roughly like cutting and pasting the included file inside the source file that includes it (this is a rough analogy, but you get the point). That means if you have:
int x; // or "slider" or whatever vars are conflicting
in the header file and that header file is included by three sour... |
5,574,528 | 5,576,036 | error: ambiguous default type conversion (c++) | I have a class which wraps an enum for easy printing, serialization, etc.
I want to be able to use it in a switch statement as the traditional enum, hence I was using a int() overloader till gcc-4.3. However my code breaks now with gcc-4.5.1.
enum E { consta, constb };
class Wrap {
private:
E e;
public:
operator ... | If you're specifically working around compiler bugs, just use conditional compilation to create a workaround and keep it as self-contained as possible.
#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) <= 40300
typedef int E; // workaround
# define ENUM_TYPE // do not define an enum type as it's... |
5,574,570 | 5,574,716 | Rename() function not working when attempting to add an extension to a file | I have an extension-less file and I want to add an .avi extension to it. So I call this function after selecting the file via openfile dialog (I want to have the file opened after renaming):
int RenameVidAddExt(HWND hWnd, char oldname[MAX_PATH])
{
int filenamesize=0, n=0;
char extension [] = ".avi";
char* n... | Since you are using C++, consider also using std::string:
int RenameVidAddExt(HWND hWnd, char oldname[MAX_PATH])
{
char extension [] = ".avi";
std::string newname = oldname;
newname += extension;
rename(oldname, newname.c_str());
return 0;
}
Some side notes:
Remember, when you use new or new[],... |
5,574,732 | 5,574,810 | Compilation fails with "expected unqualified-id" on "using" | I need some help making this program for class. We are working with g++ (linux? its through putty on a server) I am having a lot of issue with this linked list. The current error that it is giving me is
queue.cpp:2: error: expected unqualified-id before âusingâ
Wondering if anyone could help me figure it out. A lit... |
Don't include your implementation file from the header. Include the header from the implementation file.
I don't see you say "using namespace std" in the header in your code, but you say in your comment that you do that. Don't. Never say using namespace in a header file.
Place all template definitions in the header.
Y... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.