question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,379,532 | 3,379,548 | C - PJLIB why not working? | I follow this PJLIB ( https://trac.pjsip.org/repos/wiki/Getting-Started/Autoconf ). But i cant get this up yet, always its giving undefined reference, can anyone please have a look kindly.
Stackoverlow source code gets broken please find from
here details: http://gist.github.com/5765529
[sun@example mysip]$ gcc myapp... | You are not linking with the library. You need something like:
gcc myapp.c -lpjlib
but exactly what you need I don't know - it will be described in the library's documentation.
|
3,379,673 | 3,379,921 | Function is causing huge memory leak? | I have the following function:
void CGlEngineFunctions::GetBezierOpposite( const POINTFLOAT &a,const POINTFLOAT ¢er, POINTFLOAT &b, float blength )
{
POINTFLOAT v;
v.x = a.x - center.x;
v.y = a.y - center.y;
float alength = GetDistance(a,center);
if(blength == 0)
{
blength = alen... | If the GetDistance calls this method, there may be a Stack Overflow.
If other threads call this method, there may be a Stack Overflow.
Check the POINTFLOAT definition. IMHO, it should be modified to provide subtraction operations. You should not need to reference any of the structure's members. But then this comme... |
3,379,687 | 3,379,867 | Can't find error in pixel searching algorithm | Ok, I'm trying to make a program that finds the position of a colored pixel within the desktop. To do this I make a screenshot of the desktop then go through the pixels and search for the one that has the matching RGB as i need. The only problem is that my program returs strange coordonates X,Y for the found pixel...
#... | Ok, finally I found a mistake that I think is the cause of this problem.
The pointer arithmetics:
B= *(byteptr+pitch*j+3*i);
G= *(byteptr+pitch*j+3*i+1);
R= *(byteptr+pitch*j+3*i+2);
Are done for 24bits images, but the screenshot is a 32bits image that means I have to change the multiplier to 4... |
3,379,956 | 3,379,977 | How to create a temporary directory in C++? | I'm writing a function in C++ which creates a temporary directory. Such function should be as most portable as possible, e.g. it should work under linux, mac and win32 environments. How do I achieve that?
| Check the mkdtemp function here.
|
3,380,063 | 3,380,070 | Is it proper to use a default constructor with polymorphism? | I basically have something like this:
class CGlToolBase
{
public:
CGlToolBase(void)
{
}
virtual void OnMouseDown(CGlEngine &glEngine, WPARAM wParam, LPARAM lParam);
virtual void OnMouseMove(CGlEngine &glEngine, WPARAM wParam, LPARAM lParam);
virtual void OnMouseUp(CGlEngine &glEngine, WPARAM wP... | That's perfectly legal and acceptable.
However, some notes:
Your destructor should be virtual. If any class has virtual methods (abstract or not), you should have a public virtual (abstract?) destructor (so delete calls the children destructors) or a protected non-virtual destructor (which prevents the superclass from... |
3,380,196 | 3,380,208 | Passing multiarrays into functions through pointer | how can I pass multiarray into function through pointer with c++. I can do this with simple arrays
void Foo(int *arr) { }
int someArr[10];
Foo(someArr);
What about 2-dimensions array?
| You can achieve what you want in this way:
void foo(int *array) { }
int column_size = 5;
int main() {
int array[column_size][2];
foo(&array[0][0]);
return 0;
}
although you should take care on how you read the elements from inside the foo function.
In order to read the array[c][r] element you must d... |
3,380,233 | 3,380,281 | How can I simplify interface declarations in C++? | My interface declarations usually (always?) follow the same scheme. Here's an example:
class Output
{
public:
virtual ~Output() { }
virtual void write( const std::vector<char> &data ) = 0;
protected:
Output() { }
private:
Output( const Output &rhs ); // intentionally not implemented
void operator... | Personally, I would remove the copy constructor declaration. You have pure virtual functions so instances of this class can't be created by slicing in any case. If a derived class isn't copyable because of the nature of a resource that it holds; it can mark itself as non-copyable.
Then I would get rid of the protected ... |
3,380,283 | 3,380,285 | Should I create multiple classes? | This applies to several cases in my application:
I have 3 or 4 functions that belong together, one is a starting function that creates and frees the required memory structures and calls the other functions as appropriate. The other functions also call themselves repeatedly. Only the starting functions is called from ou... | Definitely go for a class here. That's what objects and classes are designed for.
|
3,380,294 | 3,380,319 | Object oriented c++ win32? | I want to create my own class to handle creating windows and the window procedure but I have noticed that the window procedure has to be static! I'm now wondering whether its possible to make the window procedure object oriented? I have read some tutorials on object oriented windows, but they always make the procedure ... | You can get around that by making the static WndProc delegate everything to the members:
// Forward declarations
class MyWindowClass;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
std::map<HWND, MyWindowClass *> windowMap;
// Your class
class MyWindowClass {
private:
HWND m_handle... |
3,380,486 | 3,380,500 | Help with this problem? | I'm working on implementing bezier handles into my application. I have points and I need to figure out weather the current direction of the new point is clockwise or counter clockwise. This is because my bezier interpolation algorithm calculates the handles from right to left.
Therefore no matter what it interpolates:
... | You have your original angle, the last known angle (since I'm sure you're redrawing the handle as it's being dragged), and the current angle. I'd take a look at the last known handle angle on the last redraw and compare whether the new angle, relative to that is > 180 degrees or < 180 degrees. If it's 0 - 180 degrees... |
3,380,513 | 3,380,530 | C++ - basic function question | Is there any way to make a function call only once?
Suppose I have some class
struct A {
void MainRoutine(Params) {
// Want to call other routine only once
}
void OtherRoutine(Params) {
// Do something that should be done only once and
// what depends on the params
}
};
I want to ca... | Take a look at Boost Thread's one-time initialization mechanism
|
3,380,520 | 3,380,524 | C++ char * to string |
Possible Duplicate:
how to copy char * into a string and vice-versa
I have to pass a value into a method that required a char *
MyMethod(char * parameter)
{
// code
}
However, the parameter I need to feed it is currently a std::string. How do I convert the std::string to a char *?
std::string myStringParameter ... | You are looking for the c_str() method:
char * myCharParameter = myStringParameter.c_str();
You might need to const_cast the return to get it into a char * instead of a const char *. Refrain from modifying the string though; it is the internal buffer of the std::string object. If you actually need to modify the string... |
3,380,565 | 3,380,578 | opening an exe from current dir C++ | I have the python code... but how do i do it in c++?
I don't have much experience with c++. What i want is to make an exe that will be put as autorun in an cd. It has to open the application.ini file in my cd with xulrunner.exe in my cd. As the path will vary in each computer i hav to do something like this.
import su... | os.system() is system(), in Win32 getcwd() is GetCurrentDirectory()
http://msdn.microsoft.com/en-us/library/aa364934(VS.85).aspx
Probably should stick to char buffers for strings. So, something like (untested, untried)
#include <stdio.h>
int main(int ac, char **av) {
char path[MAX_PATH+1];
GetCurrentDirecto... |
3,380,628 | 3,380,723 | Fast Arc Cos algorithm? | I have my own, very fast cos function:
float sine(float x)
{
const float B = 4/pi;
const float C = -4/(pi*pi);
float y = B * x + C * x * abs(x);
// const float Q = 0.775;
const float P = 0.225;
y = P * (y * abs(y) - y) + y; // Q * y + P * y * abs(y)
return y;
}
float cosine(float x)... | A simple cubic approximation, the Lagrange polynomial for x ∈ {-1, -½, 0, ½, 1}, is:
double acos(x) {
return (-0.69813170079773212 * x * x - 0.87266462599716477) * x + 1.5707963267948966;
}
It has a maximum error of about 0.18 rad.
|
3,380,633 | 3,380,660 | Is it always evil to have a struct with methods? | I've just been browsing and spotted the following...
When should you use a class vs a struct in C++?
The consensus there is that, by convention, you should only use struct for POD, no methods, etc.
I've always felt that some types were naturally structs rather than classes, yet could still have a few helper functions a... | For what it's worth, all the standard STL functors are defined as structs, and their sole purpose is to have member functions; STL functors aren't supposed to have state.
EDIT: Personally, I use struct whenever a class has all public members. It matters little, so long as one is consistent.
|
3,380,769 | 3,380,783 | Console application in C++ for smart devices (WinCE)? | I am new in developing application for WinCE 5.0. I want to start from "Hello world" program or console application. But I couldn't find anything like that or any other sample applications to start from.
I am using Visual Studio 2005. I created new project >> visual C++ >> Win32 smart device project >> console applicat... | What does the log say? That the application has terminated successfully with return code 0x0?
If you did not put anything to stop the application it might be that it runs good and terminates without you noticing it. Try to add a scanf or Sleep(5000) after the printf statement so things will be visible. You can also com... |
3,380,902 | 3,380,908 | How to initialize an integer pointer in C++? | I have a very simple question.
I want to write the below line of code in 2 lines :
IplImage *image = 0;
like :
IplImage *image;
image = 0;
I want to know what I have written is correct or else I want to know how to write the correct one (in two lines).
Thanks
| Perfectly correct. But if you don't have a very good reason to do it that way, I'd suggest leaving it as a single line that both declares and initializes it. It's more obvious, and you're less likely to ever miss initializing a pointer that way.
|
3,381,085 | 3,381,225 | Writing non-class types onto raw memory | Given a void pointer to a "blob" of raw memory, there are two ways of writing something onto it.
The first way is to use placement new. This method has the advantage of calling the ctor automagically when we are dealing with class-types. However, when I deal with non-class types, would it be better to do a cast instead... | I had a look at the generated assembly for each of these techniques, using the following program:
#include <new>
char blob[128];
int main() {
void *pLocation = blob;
char pattern = 'x';
#ifdef CAST
*reinterpret_cast<char*>(pLocation) = pattern;
#else
::new(pLocation) char(pattern);
#endif
}
I'm using... |
3,381,184 | 3,381,195 | -L option not working for mingw gcc | I am trying to get mingw gcc to work.
I need it to link with libopengl32.a.
Said file exists in C:/mingw/lib.
I used g++ as follows:
g++ -L"C:/mingw/lib" main.o -o test.exe -llibopengl32.a
It has no trouble finding the includes, it just complains that it can't find the library.
It seems unable to find any other library... | The -l flag automatically adds the lib prefix and the .a extension- you want:
g++ -LC:/mingw/lib main.o -o test.exe -lopengl32
Note you don't need the quotes around the path either. You could also just specify the whole library name & path:
g++ main.o -o test.exe C:/mingw/lib/libopengl32.a
As regards your installati... |
3,381,595 | 3,381,612 | C++: Getting hex unexpectedly when printing array | I am declaring an array using new
int *a = NULL;
a = new int[10];
a[0] = 23;
a[1] = 43;
a[2] = 45;
a[3] = 76;
a[4] = 34;
a[5] = 85;
a[6] = 34;
a[7] = 97;
a[8] = 45;
a[9] = 22;
PrintElements(a, 10);
void PrintElements(int * array, int size){
for (int i=0; i<size; i++) {
cout << endl << array[i];
}
}
... | You may have written a std::hex to the cout at some point; that will remain in effect until overridden.
|
3,381,602 | 3,381,691 | Need help in finding name of specific thing I'm trying to do | I think it's possible to somehow hook with the windows environment (specifically explorer.exe) and trigger specific things, for example launching control panel and using it as if I had mouse (meaning I'm clicking the interface from the code).
Basically what I'm trying to do is automate some redundant tasks I do often, ... | Forget about "automated clicking". GUI tools are just front-ends to control the system. You can control the system like they do, it will be much easier.
Huge possibilities can give you Microsoft Management Console. Each "snap-in" can be accessed via COM model. Some of them have GUI front-ends, find and fire "*.msc" fi... |
3,381,614 | 3,382,894 | C++ convert string to hexadecimal and vice versa | What is the best way to convert a string to hex and vice versa in C++?
Example:
A string like "Hello World" to hex format: 48656C6C6F20576F726C64
And from hex 48656C6C6F20576F726C64 to string: "Hello World"
|
A string like "Hello World" to hex format: 48656C6C6F20576F726C64.
Ah, here you go:
#include <string>
std::string string_to_hex(const std::string& input)
{
static const char hex_digits[] = "0123456789ABCDEF";
std::string output;
output.reserve(input.length() * 2);
for (unsigned char c : input)
{... |
3,381,739 | 3,381,754 | Hash map, string compares, and std::map? | First off, I would like to make a few points I believe to be true. Please can these be verified?
A hash map stores strings by
converting them into an integer
somehow.
std::map is not a hash map, and if I'm using strings, I should consider using a hash map for memory issues?
String compares are not good to rely on.
I... | I don't believe most of your points are correct.
there is no hash map in the current standard. C++0x introduces unordered_map, who's implementation will be a hash table and your compiler probably already supports it.
std::map is implemented as a balanced tree, not a hash table. There are no "memory issues" when usin... |
3,381,829 | 3,381,854 | How do I implement a callback in C++? | I want to implement a class in c++ that has a callback.
So I think I need a method that has 2 arguments:
the target object. (let's say
*myObj)
the pointer to a member function of
the target object. (so i can do
*myObj->memberFunc(); )
The conditions are:
myObj can be from any class.
the member function that is gonn... | The best solution, use boost::function with boost::bind, or if your compiler supports tr1/c++0x use std::tr1::function and std::tr1::bind.
So it becomes as simple as:
boost::function<void()> callback;
Target myTarget;
callback=boost::bind(&Target::doSomething,&myTarget);
callback(); // calls the function
And your set... |
3,381,867 | 3,382,161 | Iterating over a map | In this question I'm not asking how to do it but HOW IS IT DONE.
I'm trying (as an excersise) implement simple map and although I do not have problems with implementing links and they behavior (how to find next place to insert new link etc.) I'm stuck with the problem how to implement iterating over a map. When you thi... | The representation of your map's iterator is totally up to you. I think it should suffice to use a single wrapped pointer to a node. E.g.:
template <typename T>
struct mymapiterator
{
typename mymap<T>::node * n;
};
Or something similar. Now, mymap::begin() could return such instance of the iterator that n would poi... |
3,381,897 | 3,381,919 | Win32 Device Context without Window | In my application i need to create HBITMAP objects to which I render and from where I copy the result.
I use the function "CreateDIBSection" to create these bitmaps, however this function required a DC (Device Context) as first parameter. Currently I get this by calling GetDC(hWnd) on the main windows handle (hWnd). B... | CreateCompatibleDC(NULL) will create you a device context that is compatible with the screen - which sounds like it would be ideal in the situation.
|
3,382,554 | 3,382,571 | Distributed computing framework in c/c++ | I am looking for a way to make distributed computing over a network (lan). Is there any good framework or a library for this purpose in C/C++.
| Take a look at MPI.
|
3,382,691 | 3,382,762 | Setting TTL on outgoing ICMP packets? | I have been trying to set the TTL on ICMP packets using the
boost::asio::ip::unicast::hops option (using Boost 1.43) and then reading it out with get_option.
get_option gets 1 regardless what I use in set_option. And when inspecting the
packets sent using wireshark, the TTL is 128. Am I missing something here?
Should I... | Linux platform? Based on the documentation you appear to be doing it correctly.
|
3,382,721 | 3,382,737 | If I implement an operator for a class, is it possible that it won't be inline? | Are operators always inlined?
struct foo {
void operator ()() {
// Do tons of work.
}
};
int main() {
foo f;
f();
}
| The compiler is the unprecedented and (officially) unpredictable lord of inlining decisions. Good compilers will provide some guidance in the documentation about their implementations behaviour. The more complicated the code the less likely it is to be inlined, you can find some examples of what does/doesn't tend to in... |
3,382,759 | 3,382,772 | multiheritance in C++, different files : "Expected class-name before ',' token" | I am getting this error "Expected class-name before ',' token" and "Expected class-name before '{' token" in MainController.h
I think I am including files as needed, also doing #ifndef HEADER_H #define HEADER_H, etc in all headers, I had no errors until I wrote MainController class.
I have no idea why this error appea... | There seem to be two typos in your code:
In N4GestureRecognizer.h you have N4GestureRecognizerDataSource, but you try have MainController inherit from N4GestureRecognizerDatasource; note the different case of the S in DataSource.
In N4FingerTipGestureRecognizer.h you have N4FingerTipGestureRecognizerDelegate, but you ... |
3,382,851 | 3,382,853 | Tiny crashing program | The following program compiles with g++ but then crashes upon running:
class someClass
{
public:
int const mem;
someClass(int arg):mem(arg){}
};
int main()
{
int arg = 0;
someClass ob(arg);
float* sample;
*sample = (float)1;
return 0;
}
The following program does not crash:
int main()
{
... | float* sample;
*sample = (float)1;
sample is never initialized to point to an object, so when you dereference it, your program crashes. You need to initialize it before you use it, for example:
float f;
float* sample = &f;
*sample = (float)1;
Your second program is still wrong, even though it does not crash. Derefe... |
3,382,876 | 3,382,920 | C++ and Objective-C Combination | I need to know whether I can write the whole class in C++ and use it in XCode using Objective-C?
I need to write a code to query HTML using POST method and I think the best approach is to use either C++ or C#.
Umair
| Yes you can, with C++ that is. From the chapter "Using C++ With Objective-C" in Apples "The Objective-C Programming Language" document:
Apple’s Objective-C compiler allows you to freely mix C++ and Objective-C code in the same source file. This Objective-C/C++ language hybrid is called Objective-C++. With it you can m... |
3,383,064 | 3,383,088 | Weird C++ preprocessor macro syntax | I've distilled my problem down to this code snippet - but it is a part of a larger program so I don't want a different way to do this - I need a way to make this work!
When I generate a preprocessed file from this code:
#define OUTER(a, b) \
a##b
#define INNER(c, d) \
c##d
enum foo {
OUTER(INNER(x, y), z)
... | Use this instead:
#define CONCAT(X,Y) X##Y
#define OUTER(a, b) CONCAT(a,b)
#define INNER(a, b) CONCAT(a,b)
enum foo {
OUTER(INNER(x, y),z)
}; // line 108
int main(...)
{
foo bar = xyz; // line 112
}
|
3,383,090 | 3,383,099 | Is returning void valid code? | I found out that the following code gets accepted by Visual C++ 2008 and GCC 4.3 compilers:
void foo()
{
}
void bar()
{
return foo();
}
I am a bit surprised that it compiles. Is this a language feature or is it a bug in the compilers? What do the C/C++ standards say about this?
| It's a language feature of C++
C++ (ISO 14882:2003) 6.6.3/3
A return statement with an expression of type “cv void” can be used only in functions with a return type of cv void; the expression is evaluated just before the function returns to its caller.
C (ISO 9899:1999) 6.8.6.4/1
A return statement with an expressio... |
3,383,105 | 3,383,203 | Projection of polygon onto plane using GSL in C/C++ | The general problem is projecting a polygon onto a plane is widely solved, but I was wondering if anybody could make some suggestions for my particular case.
I have a planar polygon P in 3-space and I would like to project it onto the plane through the origin that is orthogonal to the unit vector u. The vertices of P a... | I haven't used GSL, but you only need to use dot-product, cross-product, and normalizing to get the result.
(1) Pick any vector r that is not a multiple of u. Let v = the normalized cross-product of r and u. Let w = the cross-product of u and v. Your orthonormal basis vectors are v and w.
(2) To project a vertex a t... |
3,383,113 | 3,383,138 | getting the name of the invoked function | when using either the '.', '->' or '->*' operators is there any way of getting the name of the function invoked (or the name of the variable in the case of '->*' and everything goes.
EDIT:
Just to clarify I'm not talking about reflection but more something in the line of 'function' basically I want to create an overloa... | As far as I know, no. C++ does not support any form of reflection, so in order to get this kind of information you have to design your own tools and tricks.
|
3,383,366 | 3,383,374 | struct declaration syntax error | I have the following code:
#include <iostream>
using namespace std;
struct stud{
int roll;
char name[10];
double marks;
}
struct stud stud1={1,"ABC",99.9};
struct stud stud2={2,"xyz",80.0};
int main(){
cout<<stud1.marks<<"\n"<<endl;
cout<<stud1.name<<"\n";
cout<<stud1.roll<<"\n";
r... | I don't know C++, but maybe:
#include <iostream>
using namespace std;
struct stud{
int roll;
char name[10];
double marks;
}; // notice the semicolon
struct stud stud1={1,"ABC",99.9};
struct stud stud2={2,"xyz",80.0};
int main(){
cout<<stud1.marks<<"\n"<<endl;
cout<<stud1.name<<"\n";
cout<... |
3,383,817 | 3,383,822 | Limit floating point precision? | Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556 becomes 3576.76.
| round(x * 100) / 100.0
If you must keep things floats:
roundf(x * 100) / 100.0
Flexible version using standard library functions:
double GetFloatPrecision(double value, double precision)
{
return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision));
}
|
3,383,932 | 3,394,852 | Multiple C++ .lib projects to .dll projects, Lua crashes! | Today I've tried to get Edit & Continue to work in my solution, which looks like this:
Game Engine .lib <- Game .lib <- Editor .exe
<- Server .exe
<- Client .exe
Which works nicely. But now I wanted to turn the engine and game .libs into .dlls, so I can use the Edit & C... | You wrote:
The engine and the game both work with Lua, they both have their own static C++ interface functions.
That suggests to me the possibility that the engine and game are each individually statically linked to a copy of Lua.
If that were true, then this is exactly what you would expect to happen if a Lua state ... |
3,384,005 | 3,384,022 | Qt Table and Tree View with the same model | I have a neat Model based off QAbstractItemModel. This has a simple hierarchical tree structure which works perfectly for QTreeView. However, I want the QTableView/QListView to access and display only the leaf nodes( ALL leaf nodes ). What is the best way to do this? I don't want to rebuild the model( because it will b... | You could create a proxy model. A class that sits between the View and the Model and filters out all of the non-leaf nodes and then just forwards the function calls to the original model for the leaves.
|
3,384,066 | 3,384,104 | Why do certain things never crash whith debugger on? | My application uses GLUTesselator to tesselate complex concave polygons. It randomly crashes when I run the plain release exe, but it never crashes if I do start debugging in VS. I found this right here which is basically my problem:
The multi-thread debug CRT (/MTd) masks the problem, because, like
Windows does with... | It's a fact of life that sometimes programs behave differently in the debugger. In your case, some memory is initialized differently, and it's probably laid out differently as well. Another common case in concurrent programs is that the timing is different, and race conditions often happen less often in a debugger.
You... |
3,384,193 | 3,384,354 | A way of debugging GLU with Visual Studio? | I'm using GLUTess to tesselate polygons. Sometimes it crashes with a null pointer issue and I have no way of knowing why since I just link to glu32.lib . Is there a way to see the source and get the exact line it crashes on?
Thanks
|
Is there a way to see the source and get the exact line it crashes on?
You can build program on linux. If issue persists, AND if corresponding *.so contains debugging info (and if you have source code in your distribution), then you'll be able to find line number. Do not expect source of glu to be easy to understand... |
3,384,430 | 3,384,442 | error RC2175 : resource file res\icon3.bmp is not in 3.00 format? | HI,
what does this mean, and how to resolve it?
error RC2175 : resource file res\icon3.bmp is not in 3.00 format
| Your .bmp file is corrupted or using a compression format not supported by vs2005. Trying opening it in another program, such as mspaint, and then save as uncompressed bmp.
|
3,384,749 | 3,384,771 | what is the mazimum icon' size can be used in c++ mfc dev? | what is the mazimum icon' size can be used in c++ mfc dev?
| 256x256 pixels in 24-bit color (which is the largest supported by the .ICO file format).
Edit: at least as of VS 2008, the full list is: 16x16, 32x32, 48x48, 64x64, 96x96, 128x128, and 256x256 pixels. Supported bit depths are 1, 4, 8 and 24 bits per pixel. It does also have a "custom sizes" dialog, in case you want an ... |
3,384,880 | 3,384,895 | How to store bits to a huge char array for file input/output | I want to store lots of information to a block by bits, and save it into a file.
To keep my file not so big, I want to use a small number of bits to save specified information instead of a int.
For example, I want to store Day, Hour, Minute to a file.
I only want 5 bit(day) + 5 bit(Hour) + 6 bit(Minute) = 16 bit of mem... | I think I'd just use the number of bits necessary to store the largest value you might ever need for any given piece of information. Then, Huffman encode the data as you write it (and obviously Huffman decode it as you read it). Most other approaches are likely to be less efficient, and many are likely to be more compl... |
3,384,911 | 3,384,918 | Unsigned and signed comparison | Here is very simple code,
#include <iostream>
using namespace std;
int main() {
unsigned int u=10;
int i;
int count=0;
for (i=-1;i<=u;i++){
count++;
}
cout<<count<<"\n";
return 0;
}
The value of count is 0. Why?
| Both operands of <= have to be promoted to the same type.
Evidently they are promoted to unsigned int (I don't have the rule from the standard in front of me, I'll look it up in a second). Since (unsigned int)(-1) <= u is false, the loop never executes.
The rule is found in section 5 (expr) of the standard, paragraph ... |
3,385,229 | 3,385,251 | C++ Erase vector element by value rather than by position? | vector<int> myVector;
and lets say the values in the vector are this (in this order):
5 9 2 8 0 7
If I wanted to erase the element that contains the value of "8", I think I would do this:
myVector.erase(myVector.begin()+4);
Because that would erase the 4th element. But is there any way to erase an element based off ... | How about std::remove() instead:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());
This combination is also known as the erase-remove idiom.
|
3,385,256 | 3,385,266 | Is this a valid C code? |
Possible Duplicate:
What does the code do?
void duff(register char *to, register char *from, register int count)
{
register int n=(count+7)/8;
switch(count%8)
{
case 0: do{ *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
... | It's called Duff's device and you can read about it on wikipedia.
It takes care of one problem with an unrolled loop: there could be a non-integer number of passes needed. One method is to deal with this outside the main loop, but it's more efficient to use Duff's device which uses a very fast jump table and avoids ex... |
3,385,528 | 3,385,644 | int versus unsigned char | Suppose we have a loop that runs for 100 times. Does using unsigned char instead of int for its counter make a difference? And also using i += 1U instead of i++? Or do compilers take care of that?
| In simple case int vs unsigned char gives the same code for me:
for ( unsigned char i = 0; i < 100; ++i ) {
01081001 mov esi,64h
01081006 jmp main+10h (1081010h)
01081008 lea esp,[esp]
0108100F nop
std::cout << 1 << std::endl;
01081010 mov eax,dword ptr [__imp_st... |
3,385,680 | 3,385,696 | how to find that is there any loop exist in the link list using two pointers? |
Possible Duplicate:
How to determine if a linked list has a cycle using only two memory locations.
hello i have been asked in an interview that how can i find a loop exists in a link list using only two pointers.
i have done the following:
1) find the center of the link list each time
2) by iterating this at the end... | I think you're looking for Floyd's cycle detection algorithm, also known as the "Tortoise and Hare algorithm". The idea is to set one pointer (the "tortoise") to the
first node in the list, and another pointer (the "hare") to the next item. Then in
each step, the "tortoise" pointer is advanced one position, and the ... |
3,385,691 | 3,385,771 | Question about loop speed | I have the following two loops:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(){
int start=clock();
for (int i=0;i<100;i++)
cout<<i<<" "<<endl;
cout<<clock()-start<<"\n"<<endl;
cout<<"\n";
int start1=clock();
for (int j=0;j<100;++j)
co... | In your case it is probably standard measurement error and it does not matter do you use post-increment or pre-increment. For standard types (int, byte ...) it does not matter.
BUT you should get used to using pre-increment because there are performance implications if you are using them on a Class, depending how those... |
3,385,926 | 3,388,305 | how can i cancel editing in CListCtrl by hitting the "cancel" key? | I'm editing an item in CListCtrl control. an edit box appears where I can enter text.
The event of entering the text will, however, not be catched by the LVN_KEYDOWN handler.
how do I catch it otherwise? any samples?
Thank you
| Hitting ESC does cancels editing the label of CListCtrl so what is the "Cancel" key exactly?
|
3,385,970 | 3,386,006 | Unable to find an entry point named * in dll | I have a C++ project with the following definition in the header file:
typedef enum /* Set operation type */
{
GPC_DIFF, /* Difference */
GPC_INT, /* Intersection */
GPC_XOR, ... | extern "C" __declspec(dllexport) void gpc_polygon_clip (gpc_opset_operation,
gpc_polygon *subject_polygon,
gpc_polygon *clip_polygon,
gpc_polygon *result_polygon);
try out above in c++ vc project.
|
3,386,299 | 3,394,280 | How to specialize a widget according to a file type? | I'm looking for a way to specialize a widget at runtime. I have a form created with Qt Designer. In this form there is a widget that displays user data, like name, age and so on. Then the user chooses a file and according to the type the widget shall display additional information (like to OO example person -> student,... | You need to add a widget dynamically to the widget you have drawn in the designer.
// in UI file
QWidget *wdgFromForm;
// in cpp file
QHBoxLayout *const layout(new QHBoxLayout(wdgFromForm));
SpecializedWidget * specializedWidget( new SpecializedWidget(wdgFromForm));
layout->addWidget(specializedWidget);
|
3,386,564 | 3,386,830 | MFC: How to use C++ Global Object in C | I have an MFC application in which I have declared a Global Object say "obj" in a file called MiRec2PC.cpp now I want to use this object in a C file.
I have used an approach in which I include the header file in which the structure of that particular object is declared. I also use a keyword "extern" with that obj when... | You cannot access classes from C++ in C without some sort of indirection and/or interface. If you really want to use it in C (Why?) then you will have to devise some kind of extern "C" interface to your object.
E.g. implement some cinterface.h:
#ifdef __cplusplus
extern "C" {
#endif
// It does not have to be void* but... |
3,386,687 | 3,387,781 | Using templates to manage glUniform functions | Hi again and welcome to another 'wouldn't it be great if we'd combine two things that i really don't understand anything about'-question ;)
This Episode: OpenGL Uniforms and c++ Templates
The Idea: Wouldn't it be great if you could write a single template function to set uniforms in an OpenGL shader?
The Problem: Unifo... | 1 : Yes, and yes, but at least when the compiler complains that it can't choose between float and double overloads, you can force him very simply, ie setUniform<float>(blah) instead of setUniform(blah)
2 : This time overloading is a simpler solution :)
3 : What is the question ?
The question is, why would you want to ... |
3,386,861 | 3,386,938 | converting a variable name to a string in C++ | I'd like to output some data to a file. For example assume I have two vectors of doubles:
vector<double> data1(10);
vector<double> data2(10);
is there an easy way to output this to a file so that the first row contains the headings 'data1' and 'data2' followed by the actual contents. The function which
outputs the ... | You can use the preprocessor "stringify" # to do what you want:
#include <stdio.h>
#define PRINTER(name) printer(#name, (name))
void printer(char *name, int value) {
printf("name: %s\tvalue: %d\n", name, value);
}
int main (int argc, char* argv[]) {
int foo = 0;
int bar = 1;
PRINTER(foo);
PRINTE... |
3,386,968 | 3,387,044 | C++ Templates compilation | I am failing to answer questions related to templates. Basically how templates are compiled by the compiler. I googled but did not find answers. Can somebody help me
| Templates themselves are not compiled, particular instantiations of templates are. Templates can be instantiated by simply being used or by being explicitly instantiated
E.g. given a function template:
template<class T> void f() {}
This is just a template for a function, which you can use:
f<int>(); // compiler will ... |
3,386,983 | 3,387,332 | Restart Mac OS X ungracefully using a C++ call? | How do I restart Mac OS X using C++ (not Objetive-C) without invoking any child processes? Don't care if it's ungraceful.
system("reboot"); //Is not acceptable as it relies on invoking a process
| I can't think why you wouldn't want to create a new process, but if you really don't want to, then execve("reboot",0,0) will run reboot, replacing the current process. You'll need to include <unistd.h>.
I'm assuming this is available on Mac OS; it should be on all POSIX platforms.
UPDATE
It appears that Mac OS has a re... |
3,387,021 | 3,387,160 | Alternate way of computing size of a type using pointer arithmetic | Is the following code 100% portable?
int a=10;
size_t size_of_int = (char *)(&a+1)-(char*)(&a); // No problem here?
std::cout<<size_of_int;// or printf("%zu",size_of_int);
P.S: The question is only for learning purpose. So please don't give answers like Use sizeof() etc
| From ANSI-ISO-IEC 14882-2003, p.87 (c++03):
"75) Another way to approach pointer
arithmetic is first to convert the
pointer(s) to character pointer(s): In
this scheme the integral value of the
expression added to or subtracted from
the converted pointer is first
multiplied by the size of the object
orig... |
3,387,422 | 3,387,701 | Problem with std::make_tuple in C++0x | Tying to compile the following program with Visual Studio 10, I get lot of compile errors:
#include "stdafx.h"
#include <tuple>
#include <string>
#include <map>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
typedef std::tuple<std::string, std::string> key_t;
typedef std::map<key_t, std::string> m... | Apparently the error comes in fact from the line the_map[k] = "the value";
When you use the [] operator on a map, the library tries to create a std::pair<Key,Value> object. In your case, this becomes std::pair<std::tuple<std::string,std::string>,std::string>.
However if you use an intermediate variable k, the construc... |
3,387,435 | 3,394,196 | arbitrary datatype ratio converter | I have following code:
template<typename I,typename O> O convertRatio(I input,
I inpMinLevel = std::numeric_limits<I>::min(),
I inpMaxLevel = std::numeric_limits<I>::max(),
O outMinLevel = std::numeric_limits<O>::min(),
O outMaxLevel = std::numeric_limits<O>::max() )
{
double inpRange = abs(double(i... | Adding to romkyns answer, besides casting all values to doubles before casting to prevent overflows, your code returns wrong results when the lower bounds are distinct than 0, because you don't adjust the values appropiately. The idea is mapping the range [in_min, in_max] to the range [out_min, out_max], so:
f(in_min)... |
3,387,453 | 3,387,518 | Include header files using command line option? | Is it possible to specify extra header files to include from the command line (using GCC 4 / C++)?
Or is there any other way files can be included except with #include?
Background: I'm trying to compile a large code base on my own PC. The code is usually compiled in a cluster, with a complicated build system (SoftRelTo... | I found the -include option. Does this what you want?
-include file
Process file as if "#include "file"" appeared as the first line of
the primary source file. However, the
first directory searched for file is
the preprocessor's working directory
instead of the directory containing
the main source file. If n... |
3,387,498 | 3,387,552 | Upload music to iPhone/iPod/... directly without iTunes | is it possible to program a tool that sends music to iPhone/iPod without putting the songs in iTunes?
the tool can work with "iTunes SDK" andit is not attended to go against Apple rules
the idea is to not "cache" the songs as iTunes in libraryes, just upload it directly to the iPhone/iPod from file server this help if ... | Yes, there is a way to achieve that - a player called MediaMonkey does that. I seem to remember that still requires iTunes to be installed on the machine, but you never need to add your tracks to iTunes after installing it.
As to how it's done - that I don't know, but the MediaMonkey guys might be willing to share.
|
3,387,557 | 3,387,585 | size of struct without use sizeof keyword | here is code which returns size of struct without using sizeof keyword
#include <iostream>
using namespace std;
struct point{
int x;
int y;
};
struct point pt={0,0};
int main(){
point *ppt=&pt;
unsigned char *p1,*p2;
p1=(unsigned char *)ppt;
p2=(unsigned char *)++ppt;
printf("%d",p2... | The cast here happens after the ++
p2 = (unsigned char *)++ppt;
It works because ++ on a pointer increases the pointer the number of bytes equal to the size of the type pointed to. Then you cast to char, because minus divides the difference in pointers by the size of the type (so divide by 1 because it's now char*).
... |
3,387,884 | 3,388,540 | optimization, branching elimination | float mixValue = ... //in range -1.0f to 1.0f
for(... ; ... ; ... ) //long loop
{
float inputLevel = ... //in range -1.0f to 1.0f
if(inputLevel < 0.0 && mixValue < 0.0)
{
mixValue = (mixValue + inputLevel) + (mixValue*inputLevel);
}
else
{
mixValue = (mixValue + inputLevel) - (m... | Inspired by Roku's answer (which on MSVC++10 branches), this doesn't seem to branch:
#include <iostream>
using namespace std;
const float sign[] = {-1, 1};
int main() {
const int N = 10;
float mixValue = -0.5F;
for(int i = 0; i < N; i++) {
volatile float inputLevel = -0.3F;
int bothNegative... |
3,387,913 | 3,387,938 | Library for electrical network simulation | I'm searching for a free and open source library for electrical network simulation.
In (Per preference order) : Python, Ruby, Javascript, PHP, C++ (with Qt if it exist) or bash (ahah).
Do you know one ?
| http://www.thedigitalmachine.net/eispice.html
|
3,387,991 | 3,388,102 | MSVC: Implicit Template Instantiation, though templated constructor not used | I am trying to compile Flusspferd on Windows using MSVC, but it fails due to a template instantiation problem. For the ease of explanation I rewrote the problem in simpler terms:
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_convertible.hpp>
class UndefinedType;
class A
{
};
class TestClass ... | As you state, "is_convertible only works for complete types". This means that if you violate this precondition, anything can happen - in particular undefined behavior. So both GCC and MSVC are "right" - they're neither obliged to produce working code nor an error.
|
3,388,387 | 3,388,402 | Code optimization problem with variable argument list C++ | I'm using Visual Studio C++ 2010 Express. I made this function with variable argument list:
BOOL Send(SOCKADDR_IN toAddr, LPTSTR command, LPTSTR first, ...) {
if (g_udpSocket == INVALID_SOCKET || command == NULL)
return FALSE;
va_list args;
va_start(args, command);
LPTSTR str = va_arg(args, LPTSTR);
TCHAR szDa... |
The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.
The parameter last is the name of the last parameter before the variable argument list, i.e., the last parameter of which the calling function knows the type.
Your code reads:
BOOL Send(SOCKADDR_IN toAddr, LPTST... |
3,388,494 | 3,388,579 | public, protected, private | Take a look at this code:
#include <iostream>
using namespace std;
class A
{
private:
int privatefield;
protected:
int protectedfield;
public:
int publicfield;
};
class B: private A
{
private:
A a;
public:
void test()
{
cout << this->publicfield << this->protectedfield << endl;
}
... | B has access only to the protected fields in itself or other objects of type B (or possibly derived from B, if it sees them as B-s).
B does not have access to the protected fields of any other unrelated objects in the same inheritance tree.
An Apple has no right to access the internals of an Orange, even if they are bo... |
3,388,698 | 3,389,120 | Compiling make based project with MSVC? | In OSX, I'm used to simply doing
./configure
make
But in MSVC when I do Project from existing code and try to compile I get hundreds of errors.
I'm trying to compile GLU from the Mesa3D library. How could I do this in MSVC? Thanks
| Still fighting with glu ? :)
In windows\VC8\mesa you have a .sln. Find it, open it, compile it, done.
|
3,388,907 | 3,388,937 | How does the address of stringstream buffer changes | When i use << operator to put values in buffer sometimes the address of buffer changes. does it copy the values to new address or move them to a new address in memory and how can i know the address where data is stored in?
Also, I'd be interested in a book that covers about streams in c++.
| If you put more data into a buffer then it can hold, the stream class will automatically reallocate a bigger buffer and move all the current data into the new one.
The entire point of the iostreams class is that you are not supposed to worry about those details.
For a book on just IOStream: Try Standard C++ IOStreams ... |
3,389,156 | 3,389,193 | Struct vs namespace for C++ component based design | We have a component based C++ design, where each component is comprised of a public outer class that is used to group component interfaces. Each interface is defined as a nested class as shown below.
struct ComponentContainer {
class InterfaceClass_1 : public ComponentInterface {
public:
virtual ~... | The main differences between the struct and namespace methods:
The struct method will require all of the interface classes contained to be declared in the same file. The namespace can be added to in multiple files. In other words: you can have several files extending the namespace ComponentContainer, which you cann... |
3,389,195 | 3,389,659 | Double precision in C++ (or pow(2, 1000)) | I'm working on Project Euler to brush up on my C++ coding skills in preparation for the programming challenge(s) we'll be having this next semester (since they don't let us use Python, boo!).
I'm on #16, and I'm trying to find a way to keep real precision for 2¹°°°
For instance:
int main(){
double num = pow(2, 100... | If you just keep track of each digit in a char array, this is easy. Doubling a digit is trivial, and if the result is greater than 10 you just subtract 10 and add a carry to the next digit. Start with a value of 1, loop over the doubling function 1000 times, and you're done. You can predict the number of digits you'll ... |
3,389,326 | 3,389,349 | C++ Overloaded Function Error | I'm working with JNI on a current project, and am getting a strange error from my C++ code during compilation. I get an error stating:
error: overloaded function with no contextual type information
This is coming from the "nativegetsupportedciphersuites" line in the following array, which is mapping java functions wit... | The error message indicates that you method is overloaded. The compiler can't figure out which one of the overloads you want to take a pointer to, since it doesn't have any parameter information.
It sounds like you didn't intend to overload the method. Do you have a second declaration of that method anywhere? Are you u... |
3,389,420 | 3,389,428 | Will new operator return NULL? |
Possible Duplicate:
Will new return NULL in any case?
Say i have a class Car and i create an object
Car *newcar = new Car();
if(newcar==NULL) //is it valid to check for NULL if new runs out of memory
{
}
| On a standards-conforming C++ implementation, no. The ordinary form of new will never return NULL; if allocation fails, a std::bad_alloc exception will be thrown (the new (nothrow) form does not throw exceptions, and will return NULL if allocation fails).
On some older C++ compilers (especially those that were release... |
3,389,461 | 3,389,481 | Array of objects created dynamically |
Possible Duplicate:
How does delete[] “know” the size of the operand array?
Assume i have an array of objects created dynamically
Car *newcars = new Car[10];
delete [] newcars;
How does the compiler know that there are 10 objects that need to be deleted.
| Because new[] allocates more space than is needed for the objects. It also allocates space for the number of elements, and on debug systems maybe also the file and line number where the allocation took place, to help debug memory leaks.
Including extra space in every allocation for the memory manager's internal use is... |
3,389,546 | 3,389,623 | Is a handle the same thing as a smart pointer? | I'm just about done Koenig & Moo's Accelerated C++ and in Chapters 13 & 14 they lay out the idea and implementation of a few Handle classes (simple, shared, reference counted).
The classes encpasulate a raw pointer and abstract the allocation / deallocation of dynamic objects away from the client code to avoid all the ... | From your description it sounds like a smart pointer.
Though personally I would not use the term handle as it is slightly ambiguous (just call a smart pointer a smart pointer).
Q: Could you write a smart pointer from scratch?
A: Yes
Q: Should you write your own smart pointer.
A: No. Its a lot trickier than you think. E... |
3,389,613 | 3,586,288 | Hitting Escape versus Enter triggering LVN_ENDLABELEDIT in CListCtrl | how can I differentiate between the two, when the edit field is empty in both cases?
when the user hits escape, I assume user doesn't want the new value at all, when
enter is hit, I assume the user wants an empty string for the edited item...
| BEGIN_MESSAGE_MAP(CMyPropertyPage, CPropertyPage)
//{{AFX_MSG_MAP(CMyPropertyPage)
ON_NOTIFY(LVN_ENDLABELEDIT, IDC_LIST_CONTROL, OnEndLabelEdit)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CMyPropertyPage::OnEndLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
{
LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;
if (pDis... |
3,389,648 | 3,389,806 | What is the difference between std::list<std::pair> and std::map in C++ STL? | What is the difference between std::list<std::pair> and std::map? Is there a find method for the list, too?
| std::map<X, Y>:
is an ordered structure with respect to keys (that is, when you iterate over it, keys will be always increasing).
supports unique keys (Xs) only
offers fast find() method (O(log n)) which finds the Key-Value pair by Key
offers an indexing operator map[key], which is also fast
std::list<std::pair<X, Y>... |
3,389,723 | 3,466,082 | C++ XQuery engine - zorba or XQilla or another | I have been using zorba for a little while and it seems to generally work. But it seems to leak memory here and there and I am having to look at other options.
Has anyone had luck with any other XQuery engines in linux environment?
| The new zorba 1.4 pretty OK! So I am putting this to bed till I get around to trying XQilla.
|
3,390,160 | 3,390,261 | Problem using abstract factory | I am using an abstract factory to create user interface components such as dialogs. The abstract factory used is returned from a currently selected generic "INode" which is the base class for several different types of node. So for instance, if I want to add a new node of the same type as the selected node, the scena... | A common solution is "double-dispatch", where you call a virtual function on one object, which in turn calls a virtual function on the other, passing this, which now has the correct static type. So, in your case, the factory can contain "create" functions for the various types of dialogues:
class IFactory
{
public:
... |
3,390,385 | 3,390,442 | std::tr1::mem_fn return type | I want to put the result of this:
std::tr1::mem_fn(&ClassA::method);
Inside a variable, what is the type of this variable ?
That will look something like this:
MagicalType fun = std::tr1::mem_fn(&ClassA::method);
Also, what is the result type of std::tr1::bind ?
Thank you !
| The return types of both std::tr1::mem_fn and std::tr1::bind are unspecified.
You can store the result of std::tr1::bind in a std::tr1::function:
struct ClassA {
void Func() { }
};
ClassA obj;
std::tr1::function<void()> bound_memfun(std::tr1::bind(&ClassA::Func, obj));
You can also store the result of std::tr1::... |
3,390,476 | 3,390,504 | Using g++ to compile, how do I point it to other .h files? | I'm trying to compile a .cpp + .h file that includes newmat.h and tinyxml.h - I have libnewmat.a and libtinyxml.a in the same directory as my .cpp and .h files and I'm running
g++ -lnewmat -ltinyxml test.cpp test.h
but still getting newmat.h and tinyxml.h not found at the beginning of compilation. I'm obviously a tot... | Try this one:
g++ -lnewmat -ltinyxml -I. test.cpp
-I. to look the header files in the current folder and include your required .h in your .c files
|
3,390,553 | 3,390,589 | Relearning C++ and a typedef issue | So, it's been 5 or 6 years since I've used C++ for a large project, and about half a year since I last had to deal with small/trivial C++ programs and the C++ runtime in general. I've decided I want to re-learn the language, primarily because it might prove very relevant for an upcoming project at work.
I've been work... | To answer your specific question, typedefs that hide the fact that something is a pointer or a reference are always a bad idea - the same is true in C. Consider for example the opaque type FILE - one still has to explicitly create FILE pointers in order to use it.
As for books, see The Definitive C++ Book Guide and Lis... |
3,390,603 | 3,390,616 | Can boolean operators be used with the preprocessor? | I wondering if it possible to have a preprocessor OR or AND statement? I have this code where I want to run under _DEBUG or _UNIT_TEST tags(?).
What I want is something like the following:
#if _DEBUG || _UNIT_TEST
//Code here
#endif
If this is not possible, is there a workaround to achieve the same thing without ha... | #if defined _DEBUG || defined _UNIT_TEST
//Code here
#endif
You could use AND and NOT operators as well. For instance:
#if !defined _DEBUG && defined _UNIT_TEST
//Code here
#endif
|
3,391,187 | 3,454,540 | Why would GLU crash at this spot? | I have found that my application crashes with a null reference exception right here in sweep.c in GLU source code:
static void ConnectLeftVertex( GLUtesselator *tess, GLUvertex *vEvent )
/*
* Purpose: connect a "left" vertex (one where both edges go right)
* to the processed portion of the mesh. Let R be the active ... | You will have to look into the source for RegionBelow and see if and when it can return a NULL pointer. Between your call to RegionBelow and your de-reference of regLo, perform a regLo == NULL check. You can do this with an assert or by throwing an exception (in C++). Most likely, if RegionBelow can return NULL on e... |
3,391,192 | 3,391,349 | offsetof function in c++ | here is code
#include <stdio.h>
#include <stddef.h>
struct mystruct {
char singlechar;
char arraymember[10];
char anotherchar;
};
int main ()
{
printf ("offsetof(mystruct,singlechar) is %d\n",offsetof(mystruct,singlechar));
printf ("offsetof(mystruct,arraymember) is %d\n",offsetof(mystruct,arraymember));... | offsetof tells you where in the memory allocation of the structure you will find a particular member.
The structure you defined takes up 12 bytes:
struct mystruct {
char singlechar;
char arraymember[10];
char anotherchar;
};
byte 0: singlechar
byte 1: arraymember[0]
byte 2: arraymember[1]
byte 3: arraymember[2]... |
3,391,335 | 3,392,172 | Where in the C++ Standard does it say ::delete can change lvalues? | I ran into my first compiler that changes the lvalue passed to ::delete, but doesn't zero out the lvalue. That is the following is true:
Foo * p = new Foo();
Foo * q = p;
assert(p != 0);
assert(p == q);
::delete p;
assert(p != q);
assert(p != 0);
Note that p is not zero after the delete operation, and it has ch... | It might not be so explicit. In 5.3.5/7 it says that the delete expression will call a deallocator function. Then in 3.7.3.2/4 it says that using a pointer that has been deallocated is undefined. Since the value of the pointer cannot be used after the deallocation, then whether the pointer keeps the value or the value ... |
3,391,531 | 3,391,562 | Calculate vertices of a circle | I am having a simple program, it draws a circle :/
This works fine...
for (k = 1; k < n+1+1; k++){
vertices[k].color = GU_COLOR( 0.0f, 0.0f, 1.0f, 0.0f );
vertices[k].x = cos_d( 360 - ((k-1) * dstep) );
vertices[k].y = sin_d( 360 - ((k-1) * dstep) );
vertices[k].z = 0.0f;
}
...
//Now draw it
sceGumDrawArray(GU_TRIA... | Not really sure how you are drawing the circle (I see you creating a list of vertices, but know nothing about the rendering of those), but:
Usually, when you invert from clockwise to counter-clockwise, you end up getting the normal inverted, which means that you are looking at the back of your circle. And, as is the c... |
3,391,631 | 3,391,828 | Installing Rcpp in R 2.10 on Ubuntu | I'm trying to install Rcpp on Ubuntu 10.04 and getting this error (which implies that it doesn't exist):
> install.packages("Rcpp")
Warning in install.packages("Rcpp") :
argument 'lib' is missing: using '/home/vadmin/R/i486-pc-linux-gnu-library/2.10'
Warning message:
In getDependencies(pkgs, dependencies, available, ... | A few things:
thanks for your interest in Rcpp :-)
it has been on CRAN as Rcpp for years; if you get a Rcpp not available error then you are looking at a bad CRAN mirror and I suggest using a different one
Ubuntu also has their Rcpp version of the Rcpp Debian package so you could just do 'sudo apt-get install r-cran-r... |
3,391,643 | 3,400,341 | Android JNI System.loadLibrary not needed? | I need your help to add some insight into JNI on Android. I've been looking at the /libcore/x-net package in Android and notice that Apache Harmony is the default provider for SSL functionality (using OpenSSL).
Everywhere I've found on the internet says that when you use JNI in Android you must load the native code by... | Chrisc,
To follow up on adding a new provider, you can add the files anywhere you want, including within an application. Android already has multiple providers registered in different packages. For example, in dalvik/libcore/security/src/main/java/java/security/Security.java
// Register default providers
private static... |
3,391,947 | 3,391,989 | Enjoying Both Worlds: vector With insert/erase efficiency of list | I need a container that gives me a fast indexer and can also be very efficiency in arbitrary insertion and deletion operations (meaning at any position of the container).
I remember reading about such container that uses buckets but I can't seem to find it or retrace the steps that lead me to it (I will start using t... | You may be looking for some sort of hash map, like boost::unordered_map (soon to be in the C++ standard). There are plenty of other hash implementations out there.
|
3,392,308 | 3,392,339 | Control flow syntax in c++ | With the following c++ example(indention was left out in purpose).
if(condA) // if #1
if(condB) // if #2
if(condC) // if #3
if(condD) // if #4
funcA();
else if(condD) // else #1 if #5
funcB();
else if(condE) // else #2 if #6
funcC();
else // else #3
funcD();
els... | DeadMG is right. Just in case you are interested, the rule is
else is attached to the last free
(that is, unprotected by braces and
without corresponding else) if.
|
3,392,596 | 3,392,695 | C++ - design question | I am working on game engine prototype and have the following question:
Right now my engine implementation is DirectX-bound and everything works fine.
I've got a core::Renderer class which has methods to render geometry, set shaders, lightning, etc...
Some of them are templated, some not.
class Renderer {
// ...
... | Use a base Geometry class:
class Geometry {
public:
virtual ~Geometry() { }
virtual void Render() = 0;
};
and have each of your Geometry-type classes derive from this base class and implement their specific rendering functionality by overriding Render.
Then, Renderer::RenderGeometry does not need to be a funct... |
3,392,598 | 3,392,651 | C++ Data structures API Questions | What C++ library provides Data structures API that match the ones provided by java.util.* as much as possible.
Specifically, I am looking for the following DS and following Utility Functions:-
**DS**: Priority Queue, HashMap, TreeMap, HashSet,
TreeSet, ArrayList, String most importantly.
**Utility**: Arrays.* , C... | All of those containers are available in some form in the SC++L:
Priority Queue std::priority_queue (this is actually a container adapter, rather than a container itself - that is, it works "on top of" another container, usually std::vector or std::deque.
HashMap std::unordered_map (or if your compiler doesn't support... |
3,392,608 | 3,392,666 | Is it bad practice to have an application which ships with lots of DLL's? | Is it better to have lots of DLL dependencies or better to static link as mich as possible?
Thanks
| No, it is not bad practice to ship with lots of DLLs; it is bad practice, though, to put them in %System32%. Actually, it is usually good to use DLLs instead of statically linking; for one thing, you can easily swap out just the DLL that you need to update, rather than having to replace the entire binary, and for anoth... |
3,392,910 | 3,402,026 | Data structure for matching sets | I have an application where I have a number of sets. A set might be
{4, 7, 12, 18}
unique numbers and all less than 50.
I then have several data items:
1 {1, 2, 4, 7, 8, 12, 18, 23, 29}
2 {3, 4, 6, 7, 15, 23, 34, 38}
3 {4, 7, 12, 18}
4 {1, 4, 7, 12, 13, 14, 15, 16, 17, 18}
5 {2, 4, 6, 7, 13, 15}
Data items 1, 3 and 4 m... | I see another solution which is dual to yours (i.e., testing a data item against every set) and that is using a binary tree where each node tests whether a specific item is included or not.
For instance if you had the sets A = { 2, 3 } and B = { 4 } and C = { 1, 3 } you'd have the following tree
_... |
3,393,044 | 3,393,118 | Convert a dll to a lib for static linking? | Is there a free way to statically link a dll? I've tried dll to lib but $999 is too expensive. What are alternatives since I want to have 1 nice exe instead of 1 exe + 1 DLL.
Thanks
| I'm not certain it can even be done. There are some issues that would need to be treated very delicately.
Resources in the DLL? LIB files wouldn't hold those, so you'd have to export them as well and then reintegrate them into the final EXE
Who calls DLLMain, and when?
Lou Franco's idea would skirt all of those issue... |
3,393,243 | 3,393,251 | how to use stl::map as two dimension array | Could you let us know how to use stl:map as two dimension array? I wanted to access the individual elements as like mymap[i][j] where I do not know beforehand what the value of i or j could be. Any better ideas to do the same thing in other way?
| You can do
std::map<int, std::map<int, int> > mymap;
For example:
#include <map>
#include <iostream>
int main()
{
std::map<int, std::map<int, int> > mymap;
mymap[9][2] = 7;
std::cout << mymap[9][2] << std::endl;
if (mymap.find(9) != mymap.end() && mymap[9].find(2) != mymap[9].end()) {
std::... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.