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,284,025 | 5,284,045 | Can I mix Objective-C and C++ in a single application in Xcode? | I have some legacy code to reuse written in c++ with opengl but most of the examples online are written in objective c... so porting my code would be probably easier in a mixed env.
I would prefer to avoid a "library" solution with separated .so
| Yes you can. Just add your c++ code in a file called *.cpp
You can even mix C++ and objective-c code in the same file, but make sure the file is named *.mm (instead of *.m). That's a gotacha that a lot of people fall far.
Considering you want to use some legacy C++ code, this is probably exactly what you are looking f... |
5,284,194 | 5,284,290 | C/C++ Cross platform Library allowing the utilisation of GPU for floating point calculations | Does any one know of any cross platform c/c++ libraries which will utilise the GPU for the purposes of floating point calculations, not specifically graphics oriented calcs. Which ones are in common use, which ones recommended , which ones have you had experience of. Specifically it should be open source with a GPL lic... | I would very much doubt that you have a reasonable chance of finding something like this as open source, as "utilise GPU" usually implies "heftily hardware specific, top secret NDA driver stuff".
However, OpenCL is as cross platform as you can get (works with every major vendor and even has at least one software fallba... |
5,284,274 | 5,284,299 | Notification to a parent process | When using the fork system call, I have seen that many a times that the parent calls waitpid so that the child can finish.
My question here is does the child send a notification to the parent preocess. Without using any shared resource, how can a parent identify that the chils has been completed?
| The OS sends a SIGCHLD to the parent when the child exits. You can choose to poll waitpid() using WNOHANG, or to just check with wait() after receiving a SIGCHLD. The child process doesn't need to do anything in particular, this is all managed by the OS.
|
5,284,363 | 5,284,672 | Should every VCL form has its own message loop/pump for threading? | I'm attempting to implement a MVP pattern in my latest project. Currently using the VCL library that comes with C++ Builder 2007. My thinking is I don't need to do Application->Run(), or worse Application->CreateForm() which creates a main form and loop on that form. I don't want a main form, I want a main Presenter, i... | You don't put each form in its own thread. You put each form in the main thread.
A thread only has one message loop. The exception to this is the special message loop that is run when a form is shown modally.
pApplication->Run(); runs your message loop. When posted messages are processed they get dispatched to the appr... |
5,284,378 | 5,284,402 | "corrupted" at the end of program | Hey, My code after I execute it says that "accounts" has become corrupted...
What does this mean and how do I fix it?
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
private:
int accountNum;
double accountBal;
const static double annualIntRate;
public:
void enterAccount... | In enterAccountData(), you're using accounts[MAX_ACCOUNTS] when you should be using accounts[counter].
The MAX_ACCOUNTS index is outside the bounds of the array (by one), causing unpredictable behaviour when you retrieve it (it will read whatever is in memory immediately after the array and try to shoehorn it into a Ba... |
5,284,473 | 5,284,483 | C++ template/ostream operator question | trying to get the operator to work, but throwing me bunch of errors:
my header file
template <unsigned short n>
class Vector {
public:
std::vector<float> coords;
Vector();
Vector(std::vector<float> crds);
friend std::ostream& operator <<(std::ostream& out, const Vector& v);
};
template <unsigned short... | Please look at the error, it says,
friend declaration 'std::ostream&
operator<<(std::ostream&, const
Vector&)' declares a non-template
function|
That means you need to make the operator<< a template function.
So in the class, you've to declare it as:
template<unsigned short m> //<----note this: i.e make it temp... |
5,284,691 | 5,284,709 | std::string.find_first_not_of, unexpected return value | #include <stdio.h>
#include <string>
int main(void)
{
printf("%u\n", std::string("\n").find_first_not_of(" \t\n\v\f\r", 0, 1));
}
The following program prints 0, not std::string::npos as I expected. Why?
| Your call matches:
size_t find_first_not_of ( const char* s, size_t pos, size_t n ) const;
n is the number of chars in s, and you're passing 1. So, you're searching for the first char that is not space. The rest of your " \t\n\v\f\r" string is ignored.
Likely you simply want:
find_first_not_of(" \t\n\v\f\r")
|
5,284,862 | 5,284,875 | How to use complex numbers in c++? | may you tell me how to write a complex variable in C++ code please?
I do have separate real part psi_rl and imaginary part psi_im. Now I have to write psi = psi_rl + i psi_im. Do you have any idea how to accomplish this task?
Thanks.
| You should read the documentation for std::complex, it will give you answers to these questions and many more.
|
5,284,911 | 5,284,957 | Namespace using declaration (C++ Primer - Stanley Lipmann) | Anyone can help me to understand this statement found in chapter 3 (Library Types) by Stanley Lipmann?
"Using an unqualified version of a namespace name without a using declaration is an error, although some compilers may fail to detect this error"
I'm having such hard time understanding the semantics of his sentence... | Example:
cout is a name of the std namespace. The unqualified name is cout. The qualified name is std::cout. It is an error to use the unqualified name(cout) without a using declaration beforehand. You can use either one of the two following declarations:
// This brings in the entire std namespace
using namespace s... |
5,284,961 | 5,284,974 | Stuck in an if statement in a while loop | Can anyone spot my error in this loop? After i read in the reply I seem to be stuck in the If statements. Also, putting break in to exit the loop without the condition being true seems to throw an error: "Expected primary expression before else"
Code:
while (rowNum > (FC_Row))
{
cout << "That row is not located in ... | You need braces, and to replace = with == in the if condition:
if (reply == 'Y')
{
ticketType = 'E';
break;
}
else
{
cout << "Then choose a row numbered 1-" << (FC_Row) << endl;
cin >> rowNum;
}
|
5,285,155 | 5,285,379 | utility of #define in c++ | I just found out this code from a tutorial for matrix addition in c++ by reading the values from a file-
I wanted to ask what does #define does here? What is so special in it? And how is it different from separately declaring M and N as int or char in main?
code
#include <iostream>
#include <fstream>
using namespace st... | It is a preprocessor directive of the form
#define identifier token-sequence
The preprocessor runs before the compiler transforms your code for use in the compiler. The order is as follows:
Trigraph replacement
Line splicing
Macro definition and expansion
So with the #define you can have character manipulation (macr... |
5,285,527 | 5,288,293 | How do I assign a std::pair that have one of it's component typed const? | I'm trying to code an associative container compatible with std::map. To do so, I have to create an insert method that accept a new item in the form of an std::pair with the first component of a const type. For example : std::pair<const int, int> p.
The problem I have is that such an object can't be assigned to another... | As you say, you cannot assign to a const object.
The standard containers solve this by allocating raw memory and construct the object in place. Copy construction still works.
Also, the associative containers store each element in a separate memory block, so that they don't have to be copied later.
|
5,285,606 | 5,285,633 | Opening Unicode text files in C++ and displaying their contents | Currently I am attempting to open a text file that was saved in Unicode format, copy it's contents to a wstring, and then display it on the console. Because I am trying to understand more about working with strings and opening files, I'm experimenting with it in a simple program. Here is the source.
int main()
{
... | That's a byte order mark. If you find one at the beginning of the file, just strip it.
And the spaces in between letters are probably because the console isn't very wide char friendly.
|
5,285,665 | 5,285,740 | headnode of singly Linked list has default value? | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node * next;
};
void Append(Node * head, int newdata){
Node * n = head;
if(n->next != NULL)
{
n = n->next;
}
n->data = newdata;
cout<<"data-> "<<newdata<<" inserted!"<<endl;
}
void D... | Besides the comments, the problem here is that you are sending a pointer to a Node in your append function without initializing the data and the pointer that it contains.
On the if(n->next != NULL) inside append, n->next will also be random data, meaning that you will assign the value 20 not to the "head" but to the ... |
5,285,970 | 5,286,027 | Use of a functor on for_each | Why does the for_each call on functor doesn't update sum::total at the end?
struct sum
{
sum():total(0){};
int total;
void operator()(int element)
{
total+=element;
}
};
int main()
{
sum s;
int arr[] = {0, 1, 2, 3, 4, 5};
std::for_each(arr, arr+6, s);
cout << s.total << ... | for_each takes the functor by value - so it is copied. You can e.g. use a functor which is initialized with a pointer to an external int.
struct sum
{
sum(int * t):total(t){};
int * total;
void operator()(int element)
{
*total+=element;
}
};
int main()
{
int total = 0;
sum s(&total)... |
5,285,983 | 5,286,069 | Synchronization in one producer + multiple consumer model with shared memory | I want to implement a one-producer, multiple-consumer model with shared memory in Unix
Producer: put the data frame(~char[1024]) in a memory segment
Consumers: memcpy the data into its own private memory and do some processing
Some relevant info:
It is okay for consumer to miss some data frame
Consumers are indepe... | Are you sure the problem is in the synchronization model used?
I am thinking about something else: Maybe the producer "keep the token" too long. For instance, the produced should produce the 1024 bytes in a private memory and keep the shared memory just for writing down the new data?
Be sure the critical section is as ... |
5,286,026 | 5,358,782 | printf() intermittently ceasing to print during debugging in Xcode 4 | I have just upgraded to Xcode 4 and am working in C++ project. I am finding that printf() intermittently fails to complete printing (mid-line) to the Xcode console, and from there on printf() ceases to print anything - even though the application continues to run in debugger.
I suspect Xcode 4's console window is at fa... | This behavior seems to be intermittent and reportedly pre-exists Xcode 4. As a work-around I did something like this to the main() function. There are some advantages to this approach when Xcode's Debug Console is misbehaving.
#define REDIRECT_STDOUT_TO_FILE 1
int main(int argc, char ** argv)
{
#if REDIRECT_STDOUT_TO_... |
5,286,183 | 5,286,265 | Undefined reference when attempting to pass 2d array as parameter | I am having trouble figuring out how to pass a 2d array as a parameter. The C++ manual and other examples i'm finding aren't helping me much so maybe someone can help me understand more if they take a look at my code. Thanks
header:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
#include <iom... | If you need to pass a 2D array -
void extern readFile(ifstream&, int&, int&, int&, int&, int[][6]);
void readFile(ifstream&, int&, int&, int&, int&, int[][6])
{
// ....
}
And the call should be -
readFile(inFile, FC_Row, FC_Col, EconRow, EconCol, airplane);
When you say -
readFile(inFile, FC_Row, FC_Col, EconR... |
5,286,340 | 5,288,295 | Problem with combination boost::exception and boost::variant | I have strange problem with two-level variant struct when boost::exception is included. I have following code snippet:
#include <boost/variant.hpp>
#include <boost/exception/all.hpp>
typedef boost::variant< int > StoredValue;
typedef boost::variant< StoredValue > ExpressionItem;
inline std::ostream& operator << ( st... | I don't think it has anything to do with the boost::exception. It's the output stream "operator <<". But I haven't used the variant as you're using it - only one type; I thought you were supposed to have at least 2 types as this is a "union on steroids", but maybe there's something implicit ... I'll revisit the docs.
I... |
5,286,453 | 5,286,461 | How to return a pointer as a function parameter | I'm trying to return the data pointer from the function parameter:
bool dosomething(char *data){
int datasize = 100;
data = (char *)malloc(datasize);
// here data address = 10968998
return 1;
}
but when I call the function in the following way, the data address changes to zero:
char *data = NULL;
if(do... | You're passing by value. dosomething modifies its local copy of data - the caller will never see that.
Use this:
bool dosomething(char **data){
int datasize = 100;
*data = (char *)malloc(datasize);
return 1;
}
char *data = NULL;
if(dosomething(&data)){
}
|
5,286,467 | 5,286,489 | Unable to catch exceptions from a stack object | hope you're having a good day.
I'm working on a class to wrap the Berkley C Networking API, so far I've only gotten a TCP server/client going.
The issue I'm having ironically is not with the networking, but with the stack and heap. Perhaps I simply don't understand it fully, but when I use something like:
ClientSocke... | To me this sounds like an exception being thrown for a legitimate reason, and during stack unwinding some object's (possibly the ClientSocket's?) destructor throws. Since the runtime cannot resolve this situation in any meaningful way (two exceptions "thrown" at the same time), the terminate function is called and the ... |
5,286,760 | 5,286,845 | How to build libevent version 2.0.10 with Visual Studio 2008 | Does anyone have clear instructions on building libevent-2.0.10 with Visual Studio 2008?
| Use the Visual Studio Command Prompt, then
cd \where\you\put\it
nmake -f makefile.nmake
Or if you prefer the IDE, then File + New + Project, Visual C++, General node, pick the Makefile Project template. Name = libevent-2.0.10-stable, Location = parent directory (\where\you\put). OK. Next. Build command = nmake -f... |
5,286,782 | 5,288,406 | qmake on a mac missing for qt-creator | I am working on Mac OS X at the moment, and wanted to start building apps using Qt Creator.
Unfortunately i can't build any applications as it gives me an error saying that qmake's path is not found or qmake is missing.
I tried using netbeans, which works perfectly with simple c/c++ programs, but for qt apps it then g... | It is not enough to just download the Qt Creator, you need to download the complete sdk: http://qt.nokia.com/downloads (almost 1GiB)
|
5,286,922 | 5,286,946 | g++ template parameter error | I have GetContainer() function as follows.
template<typename I,typename T,typename Container>
Container& ObjCollection<I,T,Container>::GetContainer()
{
return mContainer;
}
When I use this method as follows
template<typename I,typename T>
T& DynamicObjCollection<I,T>::Insert(T& t)
{
GetContainer().insert(&t);... | I noticed that the GetContainer function is a method of ObjCollection, while Insert is a member of DynamicObjectCollection. From this, I'm going to assume that DynamicObjectCollection inherits from ObjectCollection.
If this is indeed the case, the problem is that when you write a template class that inherits from a te... |
5,287,011 | 5,287,034 | C++ string array scope problem | In the below code, cout is outputting the correct string arrays. Unfortunately, in other places in the code (still in the same function and thus not a scope error) cout << rs[i] where 0<i<5 and i is an int, outputs a blank space. Help would be appreciated.
int N;
inp >> N;
string a[N]; //For matchee
string b[N]; //Fo... | The line rs[i][j] = a[i][N-1-j]; is incorrect. It is potentially writing out of bounds of the allocated string. Things seem ok when you print it right after writing there, but later on, other code will have used the space for other things. Because you're writing single characters in order to the string, you can use pus... |
5,287,086 | 5,287,119 | Multiply defined structure error | I had a big main .cpp file with everything in it .I needed to break the code and so I created a helper.h where I moved all the typedefs, function declarations etc.Now I am trying to move some of the functions from main .cpp into helper.cpp .I had a global called mypoint* originalpoint[mypoint is a stucture I defined ... | You put the creation of a variable into the .h file, so it's being created in both .cpp files.
The way to fix this is to declare it as extern in the .h file, and duplicate it without the extern in one of the .cpps.
|
5,287,108 | 5,287,181 | C vs C++ numerical recipes | I started to read the book "numerical recipes in C"... I try make my programs more efficients and faster... So, is the same thing, to use C or C++? I know that C++ is a super-set of C... But, are there differences between "cmath" library (c++) with "math.h" library(c)? It will intervene in the velocity of execution?...... | First off, C++ is not a superset of C. Though there are many similarities, there are also differences, and neither is a subset of the other.
Now that we have that out of the way, Numerical Recipes uses an especially simple subset of C, and you should not encounter many difficulties in using the code in a C++ program. ... |
5,287,170 | 5,287,613 | What to do with .mdump/.hdump files? | I am working on a MySQL user-defined function (UDF) that is basically a wrapper for a Windows system function. My problem is that the UDF works as intended for certain inputs, but causes mysqld to crash for others.
The UDF itself takes a single integer argument that is passed unmodified as a ULONG parameter to the WinA... | I believe you can open crash dumps in Visual Studio. Windbg is (IMO) the preferred method as it is more powerful, but if all you need is a simple stack trace then Visual Studio would be sufficient.
|
5,287,380 | 5,287,560 | I need help with classes. (C++) | Well I am trying to do an exercise in my programming book and it's difficult for me to grasp exactly what it wants.
My "enterAccountData()" function is suppose to ask the user for an account number and a balance neither of which can be negative and the account number cannot be less than 1000
The second one is the one I... | The constant field is easy enough:
class BankAccount
{
...
const static double annualIntRate = 0.03;
...
}
(Does your debugger complain about that? I'm using gcc 4.2.1) But there are other troubling things in your code, like the way computeInterest tries to set rate to zero, and the while loop... needs work.
EDI... |
5,287,566 | 5,287,909 | constexpr and deprecated conversion warning | I'm writing a function as part of an experiment with Boost.Interprocess. In the function I assign a string literal to a variable declared constexpr char*. When I do this, I get:
warning: deprecated conversion from string constant to char* [-Wwrite-strings].
My understanding of constexpr is that in a variable declaratio... | The const from constexpr would make your variable char* const.
You still have the problem that the string literal is const char and that converting its address to char* is allowed, but deprecated.
|
5,287,938 | 5,288,078 | C++ Visual Studio 2010 Exclude file from project/build | I have a C++ project originally developed under Linux (Eclipse). Since I wanted my app to run under Windows as well I extracted the non-portable portion of the code into a separate NonPortable.hpp(cpp) file. My plan was to share the code in a Visual Studio project while excluding the Linux non-portable stuff and includ... | If some of the other headers include NonPortable.hpp, they will first look for it in their own directory.
I would have put the system dependent code in two separate directories, one for Windows and one for Linux. Then you can use slightly different include paths on each system, just as you started to do here.
|
5,287,939 | 5,287,964 | function's return type's need | //we all always specify the return type of a function because it is in the syntax.....but can anyone tell me what basic objective is served by us by specifying the function's return type..........means why did the syntax have to be made like this.....it could be that we could just return the value..
| You have to specify the type in a function declaration because not all function declarations are definitions. For example, consider the following declaration that we could have if a return type wasn't required:
f(int x);
What is the type of f(42)? There's no way to know from this declaration, hence the return type i... |
5,288,007 | 5,288,017 | How do you find height of mesh object? | I need a way to find height of object(.x). Is there simple way without using some complex math, E.g con or sin.
|
Is there simple way without using some complex math
For each vertex, store the min and max value of the dimension that represents height (For example, y). If this is still "complex math", then you can use D3DXComputeBoundingBox.
|
5,288,027 | 5,288,042 | C++ implement generic class | I am trying to create a generic class in C++ but I am getting the error "expected constructor, destructor, or type conversion before '<' token " on lines 6, 16, 19...
I am just creating a simple class and pretty sure I can go on from there. Here is the sample code I am dealing with:
using namespace std;
//line 6
ge... | If this is ordinary C++ the keyword isn't generic but template. You are defining a template for a class or function, that is later instantiated when used.
|
5,288,036 | 5,288,044 | How to clear ostringstream |
ostringstream s;
s << "123";
cout << s.str().c_str() << endl;
// how to clear ostringstream here?
s << "456";
cout << s.str().c_str() << endl;
Output is:
123
123456
I need:
123
456
How can I reset ostringstream to get desired output?
| s.str("");
s.clear();
The first line is required to reset the string to be empty; the second line is required to clear any error flags that may be set. If you know that no error flags are set or you don't care about resetting them, then you don't need to call clear().
Usually it is easier, cleaner, and more straightf... |
5,288,063 | 5,288,084 | Getting a Seg Fault with an iostream and pointers | I am trying to read in a data file (a maze), of which I seem to have coded myself a seg fault, I admit that I was sick for the lecture in my college about dynamic allocation, and have searched for my issue throughly, to no avail.
Here is my snippet of code:
void MazeClass::ReadMaze(ifstream& mazedata) {
mazedata >... | In the line for (unsigned i; i<row;i++) which starts your first for loop, you don't initialize i. Try unsigned i=0;. That may not fix everything, but its a start :)
|
5,288,076 | 5,291,537 | Base64 encoding and decoding with OpenSSL | I've been trying to figure out the openssl documentation for base64 decoding and encoding. I found some code snippets below
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
char *base64(const unsigned char *input, int length)
{
BIO *bmem... | Personally, I find the OpenSSL API to be so incredibly painful to use, I avoid it unless the cost of avoiding it is extremely high. I find it quite upsetting that it has become the standard API in the crypto world.
I was feeling bored, and I wrote you one in C++. This one should even handle the edge cases that can caus... |
5,288,077 | 5,288,093 | Codeblocks comment out whole block | I am using a Codeblocks IDE for C++ and I tried googling it, but could not find the answer.
How do I comment out a block of code in Codeblocks?
For example in Eclipse its ctrl+7.
| A quick google gives me this page, which says it's Ctrl + Shift + C.
|
5,288,151 | 5,288,207 | About a Class Object | I have a very basic question about a class object. After the class has been created, we need to create a class object. At this point, I'm a bit confused to make either *object or object. Example:
CClass object
CClass *object
What is the difference both of them? And to access class function i need to use dot '.' and a... | When used in a function, your first method creates an object on the stack, and methods are called using the . notation.
CClass obj;
obj.method();
Important: The object will be destroyed regardless of how the processing leaves the enclosing function.
When used in a function, your second method creates an object on th... |
5,288,285 | 5,288,450 | Will GetMessage() return -1 in main message loop? | According to the GetMessage API from MSDN Library, it might returns -1 when there is an error. The document provides a code snippet of common error that should be avoid:
while (GetMessage( lpMsg, hWnd, 0, 0)) ...
Document says:
The possibility of a -1 return value
means that such code can lead to fatal
applicatio... | Given that VS gives you wrong code by default, and nobody seems to care, it is very likely that this causes no trouble in current versions of Windows.
It is possible that some future version of GetMessage will return -1. However, since the erroneous code must be in so many existing applications by now, this would break... |
5,288,320 | 5,288,357 | Why is std::map implemented as a red-black tree? | Why is std::map implemented as a red-black tree?
There are several balanced binary search trees (BSTs) out there. What were design trade-offs in choosing a red-black tree?
| Probably the two most common self balancing tree algorithms are Red-Black trees and AVL trees. To balance the tree after an insertion/update both algorithms use the notion of rotations where the nodes of the tree are rotated to perform the re-balancing.
While in both algorithms the insert/delete operations are O(log n... |
5,288,364 | 5,291,702 | MFC ctrls and duplicate messages | I have two CListCtrl objects in my form. I want selected list in both of them be same.
How I can do it.
I want duplicate the message that sent to a ClistCtrl and send to other one.
How I can do it?
if this is a good way?
thanks herzl
| So, essentially what you're saying is that you want the lists to be synchronized.
You can easily achieve that by adding an event handler to catch the user's selection inside you list control, by adding: ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST1, OnItemChangedList1) to your dialog/window's message-map.
Inside OnItemChangedLi... |
5,288,382 | 5,288,393 | Good container for insert-in-order? C++ | Hi I was wondering what the best container for inserting elements in order in? A map I think is unnecessary since I am just going to be accessing the element at the front, popping it and then inserting more elements (I'm implementing a pathfinding algorithm (Dijkstra) with weights)
I could probably have used a list and... | If you need only access the front and back, std::deque (double-ended queue) fits the bill perfectly.
However, for a Dijkstra algorithm, don't you need a priority queue instead?
|
5,288,396 | 5,288,421 | C++ ostream out manipulation | well basically it should list all the vector coords in this kind of format :
(x, y, z)
but at the moment it does like this (x, y, z, )
easiest way would be using if in the for cycle, but can i substract a small piece of string from the out variable?
my code:
template <unsigned short m>
std::ostream& operator<<(... | That isn't possible. Another possibility: moving out of the loop the output of the first or the last coordinates. Then there is no need of an if (or the operator ?:) inside the loop, but handling an empty vector is more complex as it will need an if outside the loop.
|
5,288,447 | 5,288,463 | Accessing a VC++ Dll from C# (compact framework) | I'm trying to compile a DLL in vc++ and use it in C# for Smart Device.
Is it possible and how?
| You have to use PInvoke, and you probably need to expose the call from your unmanaged dll as extern "C". Have a look here. What you have to consider is that generally you can't use the classes you created in your C++ dll directly, but you need some extern "C" facade inside the C++ dll that helps you to interoperate. In... |
5,288,641 | 5,297,263 | g++ including boost library | i builded my boost library with bjam, and then moved all the .a files into c:\Server\libs\boost_1_46_0\lib
if i want to compile my program there is some error:
the compile command
g++ -Ic:\Server\libs\boost_1_46_0\ -Lc:\Server\libs\boost_1_46_0\lib\ -lboost_thread-mgw45-mt-1_46 -o try1 try1.cpp
the errors
C:\Users\FE... | Move the -lboost_thread-mgw45-mt-1_46 option to the end of the command line (after try1.cpp). (From chat.)
|
5,288,696 | 5,288,727 | What's the cause of the error with this C++ template code? | This code results in a compile-time error:
#include <iostream>
#include <vector>
#include <cmath>
template <unsigned short n>
class Vector {
public:
std::vector<float> coords;
Vector();
Vector(std::vector<float> crds);
float distanceFrom(Vector<n> v);
template <unsigned ... | Here is how you should define the constructor outside the class:
template <unsigned short n>
Vector<n>::Vector(std::vector<float> crds) {
//also notice this ^^^^
}
|
5,288,728 | 5,441,590 | Xcode 4 linking object files | I have started a new project consisting of one main.cpp file and an additional file + header. When I build it, it fails with a linking error, because xcode does not seem to link two object files. In Xcode 3 one simply had to add the other cpp to the main target. How does this work in Xcode 4 ?
| Solution found for my case. Was a problem with a template instantiation you obviously have to include them in most cases directly instead of compiling the definition separately.
Otherwise xcode seems to compile an link other source files in your project correctly.
|
5,288,822 | 5,289,055 | Using Boost with Xcode4 | has anyone setup a C++ Xcode4 project to use Boost? what settings do I need to set in Xcode for a simple C++ console application?
Thanks
| Managed it with this:
and this:
|
5,289,086 | 5,289,097 | How to feed Boost.PropertyTree with a string, not a file? | Boost has a tutorial on how to load XML from a file. How do I feed it with a string that I either create in code or receive from a user (e.g. with cin)?
| Wrap the string in an istringstream.
|
5,289,307 | 5,298,844 | Problem compiling program with pqxx | I'm trying to compile a very simple program (sample that does nothing) with pqxx, but cannot do it.
Here's the 'program':
$ cat xx.cpp
#include <pqxx/pqxx>
using namespace pqxx;
int main()
{
connection conn("dbname=do... | After an email exchange with pqxx author Jeroen T. Vermeulen, I could manage to compile the 'program'.
The idea was to place xx.cpp before -lpqxx -lpq
So, the entire command is:
g++ -I /usr/local/include/pqxx/ -L /usr/local/lib/ -I /usr/local/pgsql/include/ -L /usr/local/pgsql/lib/ xx.cpp -lpqxx -lpq
It works now.
|
5,289,404 | 5,289,451 | Initialize an static member in an fully specialized class template | I can't seem to init an static member inside an fully specialized class template!
I'm trying to do the following:
template<typename Type>
class X
{
};
template<>
class X<int>
{
public:
static int Value;
}
But i can't seem to init the static member, i tried everything... | Don't use template<> while defining Value because template<> is not allowed in member definition of explicitly specialized class[X<int> in this case]. Moreover you are missing a semicolon after }
This works for me:
template<typename Type>
class X
{
};
template<>
class X<int>
{
... |
5,289,406 | 5,289,442 | Passing a child of std::ostream to a library that wants std::ostream * | I have a class (for logging) which derives from std::ostream. Stripped down, it looks like this:
class bsgs : public std::ostream {
public:
bsgs(const std::string& msg = "") {
// some setup work
}
~bsgs() {
// some cleanup work
}
template<typename T>
bsgs& operator<<(const T& rhs) {
os << rhs... | The library has no clue that you're passing a pointer to a bsgs - you're not overriding a virtual function, there's no polymorphism involved.
You may find that implementing a streambuf and replacing a streams associated stream buffer (ostream::rdbuf) is a more viable solution.
|
5,289,549 | 5,289,587 | C++ Sending a simple signal in Windows | is there an equivalent to the function kill() on Windows?
int kill(pid_t pid, int sig);
If not, would it be possible to test if a process is running based on its PID?
Thanks
| Windows doesn't have signals in the unix sense.
You can use OpenProcess to check if a process exists - If it succeeds, or fails with an access error, then the process exists.
bool processExists(DWORD ProcessID) {
HANDLE hProcess = OpenProcess(SYNCHRONIZE, FALSE, ProcessID);
if (hProcess != NULL) {
CloseHandle(h... |
5,289,572 | 5,289,593 | What is the meaning of & in c++? | I want to know the meaning of & in the example below:
class1 &class1::instance(){
///something to do
}
| This means your method returns a reference to a method1 object. A reference is just like a pointer in that it refers to the object rather than being a copy of it, but the difference with a pointer is that references:
can never be undefined / NULL
you can't do pointer arithmetic with them
So they are a sort of light, ... |
5,289,597 | 5,289,612 | How to use vector::push_back()` with a struct? | How can I push_back a struct into a vector?
struct point {
int x;
int y;
};
std::vector<point> a;
a.push_back( ??? );
| point mypoint = {0, 1};
a.push_back(mypoint);
Or if you're allowed, give point a constructor, so that you can use a temporary:
a.push_back(point(0,1));
Some people will object if you put a constructor in a class declared with struct, and it makes it non-POD, and maybe you aren't in control of the definition of point.... |
5,289,609 | 5,289,646 | Difference between vector of vectors and custom class | I was wondering what the difference (of any kind) is when using a vector of vectors to represent a 2D matrix or make a class like:
template < class T >
class Matrix2D {
public:
Matrix2D( unsigned m, unsigned n ) : m( m ), n( n ), x( m * n ) {} ;
Matrix2D( const Matrix2D<T> &matrix ) : m( matrix.m ), n( matrix.... |
- .resize() will not keep existing data in the original positions.
- Syntax differences, operator() vs operator[]
- No iterators, and no using e.g. std:: algorithms
+ Better locality, backing vector has contiguous memory
+ More understandable syntax for initialization
+ Guarantees that the array isn't jagged
In short... |
5,289,671 | 5,289,699 | Convert a no. from string to integer |
Possible Duplicate:
convert string to integer in c++
Convert a no. from string to integer.
Eg: str:"1234"
convert to int a=1234;
i want the hint with proper explaination
| The technique that this task is probably trying to get at is accessing each of the digits, e.g., str[0] - '0' = 1 and multiply by their place values. But atoi is much faster!
|
5,289,704 | 5,289,712 | Is this function(operator overloading) threadsafe? | Here's the code:
ElementType& operator[] (int key)
{
//something like boost::mutex::scoped_lock
MutexLockType lock();
if(key < 0 || key > m_bound)
throw std::range_error("access out of bound");
return m_elements[key];
}
| No it is not because you have allowed a reference the element to leak out of the function and away from the safety of the lock.
What's more, thread-safety questions are a little hard to answer without a harder specification of just what flavour of thread-safety you are desirest. At the very least you would need to sho... |
5,289,774 | 5,289,828 | Is it ever "moral" to override a nonvirtual function? | I have used the following C++ rule of thumb for a long time:
If a class overrides a function in its
base class, the function should be
declared virtual in the base.
I think I have come across an exception from this rule. To judge whether this is justified, or points at a flaw in my design, I am asking this questi... | I personally don't like this, but sometimes it's useful. The Standard library uses this too:
stringstream ss;
/* Imagine you want to redirect all output that goes into "ss"
* to "cout". The following does NOT work! */
ss.rdbuf(cout.rdbuf());
Why does it not work? Because stringstream has hidden ios::rdbuf with a sam... |
5,289,834 | 5,289,916 | Template C++0x lambda function... or functor/predicate? | I have recently upgraded my g++ so I can enjoy lambda functions.
Everything is great and I am very thankful to those who made it possible in C++ and gcc in particular. There is only one thing that I can't seem to solve - how to have lambda's arguments to be templated? Below are basic examples of lambda usage to demonst... | These were discussed as "polymorphic lambdas", and were declined because it made problems with the concepts proposal.
Last year 2009 at the Frankfurt meeting, the concepts proposal was voted out of the working paper, but polymorphic lambdas weren't considered anymore for C++0x.
See C++0x and the Lack of Polymorphic L... |
5,289,986 | 5,290,367 | Algorithm for invalidation / refresh system in Guis | I'm making a Gui for games, and I only want the Gui to redraw a widget when it is necessary. Is there an algorithm to knowing when the widget needs to be invalidated? otherwise it seems very error prone.
Thanks
How does Windows's GUI do it.
|
Is there an algorithm to knowing when the widget needs to be invalidated?
Generally when you change a property of your widget.
If you look at the standard Swing components they always repaint when methods like setFont(), setBackground(), setText(), setLocation(), setSize() ... are invoked.
I have no idea what your w... |
5,290,103 | 5,290,119 | How to import an [objective-c++] class which imports a [c++] class into an [objective-c] class? | I have 3 files.
// A.h/A.m, Objective-C.
#import "B.h"
@interface A
{
B* b;
}
@end
// Uses instance method of B in implementation.
// B.h/B.mm, Objective-C++.
#import "C.h"
@interface B
{
C c; // c is declared without pointer.
}
@end
// Uses member methods of C in implementation.
// C.h/C.cpp, C++.
#include ... | Don't include C.h in B.h. Rather say struct C;. This will allow you to forward declare the type in a way that is compatible with Objective-C. In the mm include C.h.
|
5,290,211 | 5,290,280 | Generating word library - C or C++ | I need to create a simple application, but speed is very important here. Application is pretty much simple.
It will generate all available chars by saving them to text file. User will enter length that will be used for generating so the application will use recursive function with loop inside.
Will C be faster then C++... | It doesn't really matter, chances are your application will be I/O bound rather than CPU bound unless you have enough RAM to hold all that in memory.
It's much more important that you choose the best algorithm, and the best data structures to back that algorithm up.
Then implement that in the language you're most famil... |
5,290,241 | 5,292,469 | Most complete c++ facebook library | I am looking for a c++ (or C) library to access facebook. I found some libraries doing some things, but they do not seams to be complete.
So, what is the most complete c++ library to access facebook?
EDIT
Found so far :
1) C++ Facebook REST Client
2) facebook-cpp-graph-api
| From my perspective there is no true complete library as of late for Facebook in c++
best to find the ones you need as you go.
Though I recommend this Facebook api: facebook graph api by meir yanovich
|
5,290,363 | 5,291,021 | How to generate number which exactly has seven divisors? | For a homework assignment, I need the logic to find a series of numbers from 1 to 1000 which have exactly seven divisors.
(Ideally, the code could be easily modified to generate prime numbers.)
| You need loop (for loop) from for n = 1 to 1000 and inside this loop another loop for m = 1 to n inside this loop test if n/m = integer (no remainder) and if it is increment the div counter.
At the end of second loop check if div counter is 7 if it is write the number on the screen.
EDIT: for prime numbers the div coun... |
5,290,430 | 5,290,466 | std::make_pair vs C++11 uniform initializer | Is there a drawback to using the latter? Is std::make_pair more versatile/compatible or are they truly interchangeable?
Thanks!
| How are they related? Using an initializer list constructor doesn't work for a pair, because a pair is heterogeneously typed, while an initializer list constructor uses an initializer_list<T>, which is only usable to retrieve an homogeneously typed initializer list.
(Looking into the spec, it should really be called "... |
5,290,478 | 5,290,572 | Convert a number from string to integer without using inbuilt function | I am trying this technique but error is coming. Please help me to convert a number from string to integer.
#include<iostream>
using namespace std;
int main()
{
char *buffer[80];
int a;
cout<<"enter the number";
cin.get(buffer,79);
char *ptr[80] = &buffer;
while(*ptr!='\0')
{
a=(a*... | As @Tal has mentioned, you are creating buffers of char* but you treat them like buffers of char. However, the recommended C++ way is not to use raw buffers at all:
#include<iostream>
#include <string>
using namespace std;
int main()
{
string buffer;
int a = 0;
cout<<"enter the number";
cin >> buffer;... |
5,290,502 | 5,290,864 | Place an ofImage around a circle | I'm developing for Reactivision using Openframeworks, and I need to place an ofImage (which can be place anywhere in the screen) around a circle, and also rotating it by a specific angle. I include an image to help with this.
http://i.stack.imgur.com/WCyPu.png
As you see, the x and y axes go from 0,0 to 1,1, and I have... | Like so often you don't need trigonometry for this. Let C be the circle's center, r the radius and P the point the user clicks. Then the position U of the click projected to the circle is
U = C + r * (P - C)/|P - C|
where
| A | = sqrt(A_x² + A_y² + …);
So in case of two dimensions you get
U.x = C.x + r * (P.x - C.x)/... |
5,290,770 | 5,291,219 | GCC vs VS anonymous types as template arguments | This code compiles with VS (/za) but doesn't compile with GCC. Who is right and who is wrong? Or both are wrong/right?
#include <iostream>
#include <type_traits>
using namespace std;
struct NullType
{
//NullType(){}
template<class T>
NullType(T value){}
enum {value};
};
template<class T>
struct IntType
{
... | You need to instantiate NullType::NullType(T) with the type of an anonymous enum NullType::value.
This was allowed by N2657, which is implemented in gcc 4.5.
|
5,290,782 | 5,290,900 | input, output and \n's | So I'm trying to solve this problem that asks to look for palindromes in strings, so seems like I've got everything right, however the problem is with the output.
Here's the original and my out put:
http://pastebin.com/c6Gh8kB9
Here's whats been said about input and input of the problem:
Input format :
A file with no ... |
No line is longer than 80 characters (not counting the newline at the end)
does not imply that every line is 80 characters except for the last, while your output code does assume this by taking 80 characters off answer in every iteration.
You may want to keep the newlines in the string until the output phase. Alterna... |
5,291,008 | 5,291,024 | c++ array initialization | float minTime[7]={FLT_MAX};
for(int i=0;i<7;i++)
cout << "Min: " << minTime[i] << endl;
Why do I get in the following output :
Min: 3.40282e+038
Min: 0
Min: 0
Min: 0
...
Shoudln't all have the same value as the first one? As it is refered here:
C++ Notes
|
Shoudln't all have the same value as the first one?
Nopes! When an array is partially initialized the non-initialized array elements are value initialized (zero-initialized in this case).
C++03 Section 8.5.1/7
If there are fewer initializers in the list than there are members in the aggregate, then each... |
5,291,093 | 5,302,486 | Activation record for main() | I am new to reversing. My apologies if question sounds to beginer-ish :) I have created simple code in Visual Studio C++ 2010 on XP SP3:
int main()
{
return 0;
}
Whenever I open it in Olly it shows the following state of the stack with execution paused:
0012FFC4 7C817077 RETURN to kernel32.7C817077
0012FFC8 7... | If you're trying to learn the stack convention by looking at hex in Olly, you should consider which stack convention your code is following. By default, most C++ code follows the __cdecl convention. Check out this link: http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl
|
5,291,144 | 5,291,175 | Automatic code generation in C++ | I want a piece of code which does not involve loops but automatically generates some C++ code.
I have an const int d, and from this I want to write d lines of code to access an array. So for instance
for(int k=0; k<d;++k){
// do something to myarryay[k];
}
but I don't want to write this in a for loop. I want the c... | Are you sure you need to do this manually? This is an optimization known as loop unrolling. At high enough optimization levels, your compiler will do it for you, and possibly better than you can, since a good optimizing compiler will take into account the tradeoffs (reduced instruction cache locality, for one).
|
5,291,291 | 5,291,301 | How to initialize a vector with an explicit element initializer? | We can use the following syntax to initialize a vector.
// assume that UserType has a default constructor
vector<UserType> vecCollections;
Now, if UserType doesn't provide a default constructor for UserType but only a constructor as follows:
explicit UserType::UserType(int i) { ... }.
How should I call this explicit... | vector<UserType> vecCollections(10, UserType(2));
|
5,291,432 | 5,291,906 | Waiting for URLDownloadToFile() to end | I want to make the program that downloads page from internet and makes some parsing on it. Second part is easy, problem is first.
I want to use URLDownloadToFile() function. But by default it doesn't wait for completing the download. MSDN says that the last param is sort of callback function, but I can't find any info ... | Something as simple as the sample below should do the trick if you want to just download the file synchronously:
HRESULT hRez = URLDownloadToFile( NULL, _T(<url>), _T(<file>), 0, NULL );
if( hRez == 0 ){
// download ok
}
else{
// download failed
}
|
5,291,676 | 5,291,901 | Binary Search Tree. Insert method inserting incorrectly | I have an issue where my items in my binary tree are being inserted incorrectly. I'm inserting strings in each node. I think I might be doing something wrong because it seems like I always end up with the wrong tree. i.e.
A, B, C
I should have
B
/ \
A C
but somehow I end up with like:
C
/ \
B A
or... | it's becouse when you never change what was periviusly inserted, for example if you insert C at first the next item you insert(for example b) never can take place in root so if you insert "C","B","A" in this order you will have a tree shaped like :
C
/
B
/
A
you have to check every if the current node has to... |
5,291,834 | 5,292,047 | Universal Set Class - Copy Constructor | Afternoon, guys and gals.
So I'm working on a universal set at the moment, trying to get my copy constructor to work. I have a node class finished. I'm at the point where everything seems to make sense to me, but it's still not working..
Granted, I'm still having issues wrapping my head around linked lists.
template<c... | head=new node<T>;
if(rhs.head!=NULL)
{
node<T> *temp =new node<T>;
node<T> *temp2=new node<T>;
head->set_data(rhs.head->get_data());
temp2=rhs.head->get_link();
temp=head;
while(temp2!=NULL)
{
temp->set_link(new node<T>);
temp=temp->get_link();
temp->set_data(temp2->get_data())... |
5,291,860 | 5,291,995 | Recursion with loops (generating data) | Hello I need to know if it is possible to do something like this with recursion and how?
I want to be able to choose how many loops I want, for instance GenerateNumbers(x) where x is numbers of loops I have inside.
int a, b, c;
for (a = 0; a < 10; a++)
{
printf("\n%d", a);
for (b = 0; b < 10; b++)
{
... | #include <stdio.h>
#include <stdlib.h>
int GenerateNumbersHelper(int depth,int max_depth,int* data)
{
int i;
if(depth == 1 + max_depth)
return 0;
for(i=0;i<depth;i++)
{
printf("%i",data[i]);
}
printf("\n");
for(i=0;i<10;i++)
{
data[depth]=i;
GenerateNu... |
5,291,983 | 5,292,110 | Calling variables from C++ class to Objective C class | I am creating an instance of an Objective C class from a C++ instance. The problem is that when trying to get the values of some vars (in the obj c instance) I always get 0. Some NSLogs are also ignored!:
Objective C class:
InAppPurchaseManager.h
@interface InAppPurchaseManager : NSObject <SKProductsRequestDelegate, SK... | In goToStoreFromMenu, you declare a new local variable named theStore. In checkPurchase, you refer to some other variable with the same name. The goToStoreFromMenu function initializes the local variable, which goes out of scope at the end of the function. You need to initialize the same variable that you'll eventually... |
5,292,073 | 5,298,333 | Problems in MinGW when statically linking SFML libraries | I have a program that compiles with no errors under Linux, but when I compile it for Windows using MinGW it can't run as it says that it requires some DLL's next to it. So I decided to statically link it, but it outputs some errors:
/usr/i586-mingw32msvc/lib/libsfml-window-s.a(WindowImplWin32.o):WindowImplWin32.cpp:(.t... | I had this problem too recently.
It's that SFML is compiled with DW2 exception handling, but the default MinGW cross-compiler (in the Debain and Ubuntu repos) uses SJLJ, and these are not compatible with each other. I had to build my own cross-compiler with DW2 exception handling, and that works flawlessly. Alternative... |
5,292,190 | 5,292,234 | Using Android NDK and C++ | I got the sample HelloJni project working, which uses a C file for the native code. I have not been able to get any simple examples working with C++. Take the following JNI code:
#include <jni.h>
#include <string.h>
JNIEXPORT void JNICALL Java_com_test_testActivity_doSomething(JNIEnv * env, jobject obj)
{
}
If I h... | You might need to surround your code with an extern "C" block:
extern "C" {
JNIEXPORT ...
}
You should be able to make a version that will work in both C and C++ by wrapping the extern block in #if:
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT ...
#ifdef __cplusplus
}
#endif
|
5,292,299 | 5,292,449 | How can I remove the duplicates from answer in O(n) running time? | void findodd(int a[])
{
int hash[100];
int i;
int c[100]={0};
for(i=0;i<6;i++)
{
c[a[i]]=c[a[i]]+1;
hash[a[i]]=c[a[i]];
if(c[a[i]]%2==0)
hash[a[i]]=0;
}
for(i=0;i<6;i++)
if(hash[a[i]]!=0)
cout<<a[i];
}
int main()
{
int a[] = {1,3,3,5,5,5};
findodd(a);
return 0;
}
The pr... | #include <iostream>
void find_odd(int a[])
{
int hash[101] = { 0 };
int i;
for( i = 0 ; i < 6 ; i++ )
{
hash[ a[i] ]++;
}
for(i=0 ; i<100 ; i++)
if(hash[i] != 0 && !(hash[i] % 2 == 0))
std::cout << i << std::endl;
}
int main()
{
int a[] = {1,3,3,5,5,5};
... |
5,292,307 | 5,292,345 | Referencing C functions in static library from C++ | I have a static library of functions written in C. Let's say the header file is called myHeader.h and looks like:
#ifndef MYHEADER_H
#define MYHEADER_H
void function1();
void function2();
#endif
function1 and function2 aren't anything too special. Let's say they exist in a file called impl1.c which looks like:
#in... | The other solution (to the one suggested originally by Yann) is to surround your "C" header with:
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
Which saves you from having to remember to do:
extern "C" {
#include "foo.h"
}
every place you use foo.h
|
5,292,342 | 5,292,365 | Output not matching input C++ | I am trying to (right now anyway), to display a maze from a data file. The first grouping of numbers is the size, the second the entrance, and the third are for the exit coordinates.
I have a simple input file named "MyMaze1.dat":
7 20
0 18
6 12
****************** *
* * ***** *
* ***** *** *
* ***** **... |
You're not skipping EOL's (\n) when reading the maze data.
You're swapping x and y
for (int y=0; y < rows; y++) // rows outer
{
for (int x=0;x < columns ;x++)// columns inner
{
maze[y][x]=mazedata.get(); // Swapped y and x
}
mazedata.get(); // skip \n
}
Same change's needed for Display
|
5,292,412 | 5,292,539 | Why do RGBTRIPLE and RGBQUAD store data in BGR order? | In Windows, the RGBTRIPLE and RGBQUAD structs are defined in reverse order. It is so counterintuitive that I imagine it must have been done deliberately. It doesn't really matter, of course, but this has bugged me enough that I feel it's worth asking. So, why?
The definitions:
typedef struct tagRGBTRIPLE {
BYTE... | The color order storage per-se has absolutely no particular meaning: you could store the components in any order, the important thing is just to agree on which order has been chosen.
Still, the BGR format for these structures matches the components order used for DIBs (at least on little-endian machines - but all the D... |
5,292,498 | 5,292,519 | Variable sized char[] - Is it OK? | forgive me if this is stupid but I'm newer to C/C++.
In the socket library I'm creating, my ClientSocket::recv(int bufsize) function uses 'bufsize' to initialize a char[] array to read into from the C socket. The code, given you compile with G++, works fine.
The issue I am having is that some people that are compiling ... | g++ allows C99 Variable Length Arrays in C++ as a language extension.
they're not supported by standard C++.
in C++ use a std::vector or std::string.
Cheers & hth.,
|
5,292,626 | 5,292,662 | Couldn't find child window using FindWindowExA() | Trying to get button's handle on window calculator's form.
Spy++ shows the following tree:
("Calculator"; CalcFrame) ->
(""; CalcFrame) ->
(""; #32770 Dialog), ...anather child windows ->
(""; Button) ,... another child windows
// ("window caption"; window class)
// -> next child level
I catch main window and go d... | #32770 is actually a class atom. Try:
HWND contentHwnd = ::FindWindowExA(calcHwnd, NULL, MAKEINTRESOURCE(32770), NULL);
|
5,292,700 | 5,350,601 | efficiently acquiring a screenshot of the windows desktop | Is there a more efficient way of getting a copy of the windows desktop ( using GDI or any other library ) than the code below
HDC dcDesktop;
HDC dcMem;
HBITMAP hbmpMem;
HBITMAP hOriginal;
BITMAP bmpDesktopCopy;
dcDesktop = GetDC( GetDesktopWindow() );
dcMem = CreateCompatibleDC( dcDe... | http://www.codeproject.com/KB/dialog/screencap.aspx
This page has a couple different ways to take screenshots. The DirectX method they use seems simple enough.
Aside from what's mentioned in that article, I don't think there's any more an efficient method of capturing the desktop.
|
5,293,072 | 5,293,917 | Creating pointer to Vector of boost::thread pointers | I am attempting to make a vector of pointers to boost thread objects. This vector then is a member of a class that is created on the heap from a pointer when the class constructor is called. It looks something like this.
#ifndef NETWORKSYSTEM_H
#define NETWORKSYSTEM_H
#include "Network.h"
#include "Misc.h"
#include ... | I got a similar error as yours:
class A
{
int B;
public:
A()
{
B = 0;
}
int B();
};
Advice: Don't name your member functions the same name as your member data.
|
5,293,153 | 5,293,204 | VectorList class constructor | for my assignment we are making a VectorList class and I had a question about the constructor. This is the class declaration:
#include <iostream>
#include <vector>
using namespace std;
template< typename NODETYPE >
class VectorList
{
public:
VectorList(); // constructor
~VectorList(); // destructor
void insert... | Your teacher is fishing for a constructor initializer list. This lets you initialize members before the constructor is run:
template< typename NODETYPE >
VectorList< NODETYPE >::VectorList()
: vList(new std::vector)
{
}
This is the standard way to initialize members since it is equivalent to initializing at d... |
5,293,255 | 5,298,530 | Generate expression using C++ boost::spirit PEG grammar | I'm very new to C++ & boost::spirit. Trying to learn both by building a simple expression tree with only || and && using a PEG. I have built many parts of the code from the mini-xml tutorial in the docs.
Here is the code, it works for simple strings like "1 || 0", "1 && 0", "1 || 1 && 0" ... but fails for "(1 || 1)".... | Enabling Spirit debug support will help:
a) add a define
#define BOOST_SPIRIT_QI_DEBUG
and b) add inside the constructor of your grammar a
BOOST_SPIRIT_DEBUG_NODE(r);
for all rules (here r). As a result the parsers will print an execution tree at runtime showing you what rules are executed with what input and whic... |
5,293,416 | 5,293,427 | C++ converting back and forth from derived and base classes | I was wondering if there is a way in C++ to accomplish the following:
I have a base class called ResultBase and two class that are Derived from it, Variable and Expression. I have a few methods that do work on vector<ResultBase> . I want to be able to pass in vectors of Variable and Expression into these methods. I can... | vector<ResultBase *> should fix your slicing problem - a vector<ResultBase> will never contain classes derived from ResultBase, but rather copies that "slice off" e.g. Expression by copying the ResultBase part of it.
See What is object slicing? for a detailed explanation of slicing.
|
5,293,466 | 5,293,471 | c++ push_back() inside a map of vectors | I'm trying to dynamically add elements to a vector that is contained within a map, to store multiple arrays of "Particle" objects that are mapped to different ids. I'm new to the language and so I'm having trouble understanding if this can only be done with iterators? In this case it feels like overkill. Is it possible... | particleMap[currentId].push_back(p);
will work just fine.
There is only one vector per id; this is what you are referring to with particleMap[currentId]. Then you just continue with the expression as if you were writing myVector.push_back(p).
|
5,293,538 | 5,293,800 | Custom Weak/Strong Reference Pointers | I am creating my own implementation of a weak/strong reference pointer relationship and I am confused to the configuration. When I have a class that contains the strong reference, and I want to set the strong pointer to another class that has a weak reference, should I be passing in the pointer of a weak_ref pointer?
I... | The implementations that I have seen, and that I have worked on, that use the concepts of strong and weak reference, all use two counts. Sometimes one count is the number of weak references and the other is the number of strong. Other times one of the counts represents the sum of strong + weak references. Sometimes ... |
5,293,604 | 5,293,725 | Writing C/C++ with Unix Api in Visual Studio? | I'm a third year computer science student. I was raised on Visual C++ and have gotten quite proficient at using it. My school however, teaches primarily on Linux platforms. Up until now I have just programmed and debugged in Visual studio, then when I was certain I got everything working, I would recompile the source i... | Typically, you would just use the platform-independent equivalents found in various libraries- usually Boost. However, if you must use the Unix-specific APIs, the only way to go will be to wrap their functionality for Windows. Likely, there already exist libraries that serve this purpose, much as you can use WINE and s... |
5,293,621 | 5,293,651 | Problem with object declaration/initialization as a private member on a different class | Sorry if this has been asked before, I can't seem to find anything. I'm not sure how to search for this.
I have something like this:
class A {
private:
int x;
int y;
public:
A(int, int);
}
class B {
private:
A a(3, 4); // Doesn't compile because of this line
public:
... | You tag B's constructor with a "member initialization list". Instead of:
B::B() {
...
}
You do this:
B::B() : a(3, 4) {
...
}
Or if the constructor is defined in the header:
class B {
private:
A a;
public:
B() : a(3, 4) {
...
}
};
|
5,293,632 | 5,293,691 | How to set inherited C++ class/struct variables in single declaration | Is there a method I can use to be able to declare a new object w/ inherited variables with a single line of code? Example:
#include <iostream>
using namespace std;
struct item_t {
string name;
string desc;
double weight;
};
struct hat_t : item_t
{
string material;
double size;
};
int main ()
{... | Classes with inheritance are not POD and therefore are definitely not aggregates. If you are not using virtual functions, prefer composition to inheritance.
struct item_t {
string name;
string desc;
double weight;
};
struct hat_t
{
item_t item;
string material;
double size;
};
int main ()
{
... |
5,293,737 | 5,293,777 | Where are the man pages for C++? | Does documentation for C++ exist in Linux? I want something like the man pages of C.
For example, docs for string, stl, iostream, ifstream, etc.?
| If you use the "normal" libstdc++ shipped with g++, its documentation is available online here.
Most Linux distributions make it also available offline as a particular package; for Debian-derived distros, for example, it's libstdc++-6-<version>-doc (e.g. on my Ubuntu machine I have libstdc++-6-4.4-doc installed). In ge... |
5,293,846 | 5,293,964 | aesimc instruction gives incorrect result | I'm trying to implement AES cryptography using the AES machine instructions (basing it on Intel's white paper) available on my Sandy Bridge. Unfortunately, I've come to a halt in the phase of generating the round keys for decryption. Specifically, the instruction aesimc (applying the Inverse Mix Columns operation) retu... | The bytes are backwards. You want 0x5d to be the least significant byte, it has to come first. This is a little-endian chip. In VS, use Debug + Windows + Registers, right-click + tick SSE to see the register values.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.