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 |
|---|---|---|---|---|
7,678,332 | 7,678,429 | Odd results plotting Array with glVertexPointer stride variable | I have an Nx4 array of vertices that I'd like to plot using glVertexArray and glDrawArray. as a 2D scatter plot. I currently initialize the array like so:
GLint data[4][MAX_N_POINT];
for (int j=0; j<MAX_N_POINT; j++)
{
data[j][0] = 200 + rand()%20 - 10; // X Dimension
data[j][1] = 400 + rand()%20 - 10; // Y D... | The stride is not the "gap" between vectors, the stride is the distance between vector start locations. So in your case your vectors are "sizeof(int)*4" apart, which is the stride distance to use:
glVertexPointer(2, GL_INT, sizeof(GLint)*4, data2);
|
7,678,462 | 7,679,124 | Writing your own version of windows | Recently, I've been thinking about how there are multiple versions of linux and how they are all built on a similar kernel. And I was wondering if it was possible with Windows. In this case I am thinking of having the first program loaded after the kernel has booted up and started all the devices, would be the what pop... | Initially I thought this was a naive question, but Mooing Duck's link in the comments proved insightful. There are projects that do just this: EmergeDesktop, SharpE, even the KDE.
They're open and on sourceforge, go get them and dink around to your hearts content.
I'm not sure that the login screen is part of the shel... |
7,678,511 | 9,583,139 | Getting pixel color with Magick++? | I've already asked this question, but that was about FreeImage. Now I'm trying to do the same thing with ImageMagick (to be more correct, with Magick++).
All I need is to get the RGB value of pixels in an image with the ability to print it out onto the screen. I asked this in the ImageMagick forum, but it seems there i... | Version 6 API
Given an "Image" object, you have to request a "pixel cache", then work with it. Documentation is here and here:
// load an image
Magick::Image image("test.jpg");
int w = image.columns();
int h = image.rows();
// get a "pixel cache" for the entire image
Magick::PixelPacket *pixels = image.getPixels(0, 0,... |
7,678,521 | 7,683,674 | Calculating FIR coefficients from frequency response | I have a list of amplitude frequency response points. The amplitudes are given in decibels.
The task is to export this AFR list to a set of coefficients for some hardware DSP device. I know the file format for this device. The specification for the device says that it needs 12288 coefficients and the DSP has 2 FIR filt... | The standard way of finding good FIR coefficients is using the "Remez exchange" algorithm. I found a link to some code (haven't tried it myself) that you may find useful: http://www.janovetz.com/jake/remez/remez-19980711.zip. Another key word to search for is "Parks-McClellan".
Input to the algorithm is a description o... |
7,678,574 | 7,678,673 | Is this code a working critical section wrapper class | I've actually got 2 questions, heres the first one.
Using the code I found at two different sites, I wrote those two critical section wrapper classes.
Is it going to work?
#ifndef CRITICALSECTION_H
#define CRITICALSECTION_H
#include "windows.h"
class CriticalSection{
long m_nLockCount;
long m_nThreadId;
... | The LockSection class uses RAII to call Enter and Leave. When the object is created, the Enter is called. When the object is destroyed (by going out of scope) the Leave is called.
Initialize and Delete are called by the CriticalSection class' constructor and destructor.
Learn RAII, learn it well. It is your friend.
|
7,678,657 | 7,678,684 | Console writing, delete characters | My question concerns deleting already written chars in the console. Is there a way to do it?
Lets say i write 10 spaces to the console. Can i delete some to make space for other chars without the output exeeding 10 chars? I use a special libary given, with functions for writing in the console etc.
| Use '\b'. It erases one character, and the cursor moves back:
std::cout << "nawaz"; //screen shows : nawaz
std::cout << '\b'; //'z' is erased, now screen shows : nawa
|
7,678,704 | 7,678,894 | Calling overloaded constructor from constructor initialisation list | In the code below, my intent is to call one of two overloaded constructors for the kap (class opacity) based on what arguments are passed to the object of class material:
class opacity{
private:
int mode;
double kap_const;
double kappa_array[10][10];
public:
opacity(double constkap); // picking the construc... | If opacity has a copy constructor, you could accomplish this in the initialization list, avoiding a default constructor, but at the cost of a copy:
Matter::Matter(int i, double k, char * filename)
:kap( ( 0 < k ) ? opacity(k) : opacity( filename ) ) { ... }
|
7,678,731 | 7,678,857 | Reading constant number of characters in C++ | How would you read a string if it was no longer than 20 characters and could contain spaces in C++? For example I have this kind of file:
3
Namama 4 5 12
Cool 4 2 34
Not So Cool 4 2 45
I want to write it in the most basic way possible. And I would prefer using only C++ (no C thin... | If you want to read exactly 20 characters,
for(int i=0; i<3; ++i) {
std::string result;
int one, two, three;
result.resize(20);
if (!std::cin.read(&result[0], 20)) throw std::runtime_error("reading buffer failed!");
if (!std::cin >> one >> two >> three) throw std::runtime_error("reading numbers f... |
7,678,779 | 7,678,803 | I can't understand why this program prints 8762 as a result |
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
#include <iostream>
double *foo(){
double *varFoo = new double;
double temp = 8762;
varFoo = &temp;
return varFoo;
}
int main(void){
double *newVar = foo();
std::cout<<*newVar<<std::endl;
std::cin.get(); ... | Because you are in Undefined Behavior land. Anything could happen.
Moral of the story: never return the address of a temporary!
|
7,678,995 | 7,679,050 | From thrust::device_vector to raw pointer and back? | I understand how to go from a vector to a raw pointer but im skipping a beat on how to go backwards.
// our host vector
thrust::host_vector<dbl2> hVec;
// pretend we put data in it here
// get a device_vector
thrust::device_vector<dbl2> dVec = hVec;
// get the device ptr
thrust::device_ptr devPtr = &d_vec[0];
// no... | You initialize and populate thrust vectors just like standard containers, i.e. via iterators:
#include <thrust/device_vector.h>
#include <thrust/device_ptr.h>
int main()
{
thrust::device_vector<double> v1(10); // create a vector of size 10
thrust::device_ptr<double> dp = v1.data(); ... |
7,679,227 | 7,679,255 | In C++, for some type T, how can I obtain a "const T**" from a "T**"? | I have the following C++ code snippet:
class T { };
void f(const T**) { }
int main() {
T *x = new T[5];
f(&x);
}
When I try to compile, g++ reports invalid conversion from 'T**' to 'const T**'. I have done some research and I understand this error. The typical fix is to change the definition of f(const T**) ... | Instead you can pass the address of a pointer storing the same value as x.
int main() {
T *x = new T[5];
T const *y = x;
f(&y);
}
When f returns you can copy the value back into x.
You can also cast the address. A write through T const * to an object of type T * is not an aliasing violation.
int main() {... |
7,679,246 | 7,679,461 | C++ cin char read symbol-by-symbol | I need to read symbol-by-symbol. But I don't know how to read until end of input. As exemple test system will cin>>somecharvariable m times. I have to read symbol-by-symbol all characters. Only m times. How I can do it?
| If you want formatted input character-by-character, do this:
char c;
while (infile >> c)
{
// process character c
}
If you want to read raw bytes, do this:
char b;
while (infile.get(b))
// while(infile.read(&b, 1) // alternative, compare and profile
{
// process byte b
}
In either case, infile should be of type... |
7,679,351 | 7,679,573 | Changing the value of a variable in main to be available for other functions (c++) | I declare this:
int xstartoftable;
void drawframe();
int main()
{
int xstartoftable = 80-TLENGTH;
drawframe();
return 0
}
void drawframe();
{
gotoXY(xstartoftable - 1, ystartoftable - 1);
}
The problem is that when I debug, the value of xstartoftable is random, not equal to the one in the main(). The cod... | That's because you redeclare your variable inside main.
int main()
{
int xstartoftable = 80-TLENGTH; //extra declaration here
drawframe();
return 0;
}
Instead just do:
int main()
{
xstartoftable = 80-TLENGTH; //leave out declaration
drawframe();
return 0;
}
This is similar to:
int main()
{
int ... |
7,679,360 | 7,782,300 | fstream reading misstake | guys im desperate and i really dont know what i am doing wrong :(
I just wanna get my program to simply add "hello" in the file read it and print it;
The writing works well but for some reasone he is not reading it out of the file again (at method list...
#include "user.h"
#include <string>
using namespace std;
u... | You have to set the filepointer to the beginning before reading
log.seekg(0, std::ios::beg);
|
7,679,395 | 7,679,478 | run time error in vc ++ | my project contains a few classes (1 of them is Point3D) & a cpp (CreatePoint.cpp) & a header file (CreatePoint.h).
my stdafx.h file is
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include ... | LNK2001 is a linker error, not a runtime error.
Point3D *point[]; seems to be a declaration, but not an instantiation. That is, this line tells the compiler that this variable will exist somewhere later. Because arrays must have a size to be instantiated. (I hadn't even known [] without a size was allowed in that ... |
7,679,493 | 7,679,648 | Printing out an integer array ends with garbage | I have following code which should print array of 3072 integers:
for(int q=0; q < 3072; q++) printf("%x", band->GetData(q));
one would assume that it will print 3072 integers, however I get 3075 integers with 3 probably garbage ones at the end. Printing to the file using this code
fp=fopen("filename", "w");
fwrite(ban... | The problem with the fwrite is probably because you've opened the file in text mode, and any 0x0a bytes written to the file will be expanded to 0x0d 0x0a.
The problem with the printf is that you're not putting out any separators between the numbers, so you're miscounting the output.
|
7,679,613 | 7,679,654 | Specifying template parameter with a Typedef | I want to able to pass two joined iterators as one to take advantage of some stl like algorithms (such as TBB) so I am making a custom iterator that joins them but am hitting some stumbling blocks.
I need to specialize iterator, however it won't let me generically specify a template parameter.
Like so:
template<typenam... | value_type is a dependent type on IT1, so you have to specify typename there
typename IT1::value_type
|
7,679,673 | 7,679,692 | How to locate Latitude and Longitude | I have a device that is connected to the internet. The objective is to be able to locate the latitude and longitude of the device from the internet.
So I need to implement a code in C++ that would use the internet to find out the latitude and longitude. The device does not have a GPS. So just through an internet conne... | The best you can do without access to some sort of location based service (some use GPS, but some e.g. triangulate known WiFi hotspots) is to geolocate the IP address. Typically that will get you within 20-30 miles, but in some cases you can be very far off (e.g. if the IP is a proxy server far removed from the actual... |
7,679,746 | 7,679,948 | Making a calculator that translates a string to ints and chars | I'm working through a list of practice problems to beef up my C++ skills (I'm a beginner), this one is stumping me.
Make a program that takes input from the user of a calculation (e.g. "2+2") and outputs the
answer (e.g. 4). It shouldn't matter if there are spaces or the formatting of the user's
input, so long ... | Because you seem to have an idea what you want to do, I'll just answer the questions. Go ahead and try. :)
To read from the console in C++ you can include the iostream-library and use cin <<.
For example:
#include <iostream>
#include <string>
int main(void)
{
string yourVar;
// ...
cin >> yourVar;
//...
}
You s... |
7,679,827 | 7,679,911 | reference-related issue in C++ | In the "C++ programming language", there is an example
void g()
{
int ii = 0;
int& rr = ii;
rr++;
int* pp = &rr;
}
The author states:
This is legal, but rr++ does not increment the reference rr, rather, ++ is applied to an int that happens to be ii.
I am quite confusing about this statement, why "rr++ ... | A reference is similar to a dereferenced pointer to a variable. For example:
int v = 3;
int* pv = &v;
int& rv = v;
// Access v through a pointer:
*pv = 4;
// Access v through a reference:
rv = 4;
In this example, both statements will set v to 4.
|
7,679,847 | 7,680,853 | Is this way to allocate memory bad? | I was wonder how malloc would allocate memory (can you tell me ?), so I tried something.
Is this a bad way to allocate memory ?
void* myMalloc(unsigned int size) {
return (void*) new bool[size];
}
| I hate to disagree with quite so many people recommending that you use new char[n], but I feel obliged to do so.
Since you want to allocate "raw" memory, not objects, you should really use ::operator new instead of new some_type[some_size]:
void *myMalloc(size_t size) {
return ::operator new(size);
}
Ultimatel... |
7,679,852 | 10,078,654 | Completely transparent image | Does anyone know how I can create a Completely transparent image or given am image (HBITMAP) how can I wipe it Completely so that all pixels in it are 100% transparent?
Thank you.
| I also found the solution without the use of GDI+.
BITMAPV5HEADER bi = {sizeof(BITMAPV5HEADER), 320, 240, 1, 32, BI_BITFIELDS, 0, 0, 0, 0, 0, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000};
HDC hDc = ::CreateCompatibleDC(0);
if(NULL != hDc)
{
RGBQUAD* pArgb;
HBITMAP tBmp = ::CreateDIBSection(hDc, (BITMAPINFO*... |
7,680,020 | 7,680,071 | Difference between floating-point object and its value | With respect to the following code segment:
struct Pair{
string name;
double val;
}
vector<Pair> pairs;
double& value(const string& s)
{
for (int i=0; i<pairs.size(); i++)
if (s==pairs[i].name) return pairs[i].val;
Pair p = {s,0};
pairs.push_back(p);
return pairs[pairs.size()-1].val;
}
The au... | The object is the actual memory block that contains the value.
So if you get the reference you could replace its value, which is still stored in the original vector.
And of course if you'd just get the value (by changing the return value to double without the &) you wouldn't be able to change the actual value in the v... |
7,680,189 | 7,730,234 | OpenSSL: can't build in VC++ 2010 | I have downloaded the latest OpenSSL source package. I want to build it with VC++ 2010 x64. Following the instructions doesn't seem to work. Configure step looks fine, but then:
C:\1>ms\do_win64a.bat
C:\1>perl util\mkfiles.pl 1>MINFO
C:\1>perl ms\uplink.pl win64a 1>ms\uptable.asm
C:\1>ml64 -c -Foms\uptable.obj ms\upt... | The problem seems to be related to eol (end of lines). The solution is to patch mk1mf.pl to make it remove the carriage-return:
Index: mk1mf.pl
===================================================================
--- mk1mf.pl (revision 88908)
+++ mk1mf.pl (working copy)
@@ -315,7 +315,7 @@
for (;;)
{
... |
7,680,274 | 7,680,317 | How do I externalise the conversion operator? | How do I make it so the following code is externalised outside the class:
template<typename TemplateItem>
class TestA
{
operator const int (){return 10;}
};
So it appears like:
template<typename TemplateItem>
class TestA
{
operator const int ();
};
template<>
TestA<int>::operator const int()
{
//etc etc
... | Write this:
template <typename T> class TestA
{
operator const int();
};
template <typename T> TestA<T>::operator const int()
{
return 10;
}
The standard antonym of "inline" is usually "out of line", by the way. Also, I'd probably make the function const, as one usually does with conversion operators (to allow co... |
7,680,481 | 7,680,587 | short well-written programs in C++ | I'm an intermediate-level programmer and I've been writing the code for several years in PHP, later C#.
Now I want to learn some C++ through reading some short(let's say up to 2000 lines) well-written non-gui program sources.
Have you got any ideas where so find something like that?
I'd prefer some kind of networking ... | I'd recommend Effective C++ #3 by Scott Meyers - it's a pretty cheap textbook, and it starts with some semi-advanced topics (at least with regard to design).
The reason I think it would be good for you is that I came from a C# background primarily, and I know that while you'll be decent with object oriented design (lik... |
7,680,657 | 7,680,765 | How do I implicitly specialise conversion? | With the following code, if I attempt to convert a template array to std::string, instead of the compiler using the expected std::string conversion method, it raises an ambiguity resolution problem (as it attempts to call the array conversion methods):
#include <iostream>
template<typename TemplateItem>
class TestA
{
... | First, the reason you have ambiguity: you provide both conversion to char* and conversion to std::string const, and std::string likes them both.
By the way, before getting to your question, the const in operator std::string const was once a good idea, advocated by e.g. Scott Meyers, but is nowadays ungood: it prevents ... |
7,680,792 | 7,720,397 | WM_TIMER animation flickering | Alright I'm using a timer with a 50 ms elapse time to animate some moving text (technically its scrolling between text).
Problem is, if you look closely, you can see the text flickering, and id like it not to flicker..
So i'm not that good with animation but is there something I can do to reduce flickering? Maybe a fas... | Okay, I debugged the program (it's amazing what you can find if you just step through the code line by line), and at the point where you call BitBlt, you pass the parameters
BitBlt(hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, hdcMem, 0, 0, SRCCOPY);
Inspection of the values in the debugge... |
7,680,816 | 7,681,069 | OpenCV: Error when using function cvGoodFeaturesToTrack | When I call the function cvGoodFeaturesToTrack to find Harris corners I get this error:
OpenCV Error: Assertion failed (src.type() == CV_8UC1 || src.type() == CV_32FC1) in cornerEigenValsVecs, file /build/buildd/opencv-2.1.0/src/cv/cvcorner.cpp,line 254
terminate called after throwing an instance of 'cv::Exception'
... | OpenCV is trying to tell you that one of the images you passed to cvGoodFeaturesToTrack() (the error is actually originating in the helper function cornerEigenValsVecs()) is not of the required type CV_8UC1 or CV_32FC1.
I suspect img1 may not be of the type you need it to be. What is the type of the img1 matrix? If it... |
7,680,831 | 7,695,437 | Plugin Development for Kdevelop | I really love programming in kdevelop4, however it`s quite lacking in language support and other issues, so i would like to developing extension for it.
however .... i thought i would start with an easy plugin but it seems there is no actual documentation about it(not even a good in code comment)
just an example that... | Check that the plugin has been installed to a path in your KDEDIRS env variable, and run kbuildsyscocoa4.
|
7,680,869 | 7,680,909 | Errors with std list | For some reason, I keep getting the following errors in ErrorHandler.h
why size function is missing arguments?
'std::list<_Ty>::size': function call missing argument list; use '&std::list<_Ty>::size' to create a pointer to member
'std::_List_iterator<_Mylist> std::list<_Ty>::erase(std::_List_const_iterator<_Mylist>... | http://www.cplusplus.com/reference/stl/list/pop_back/
Nope, pop_back does not return the last element. This is to prevent accidental errors. You have to get the last element explicitly via back(). This way is also faster if you want to pop several without reading them. This also applies to all the other Standard C+... |
7,681,174 | 7,681,296 | Interview Coding - Take a pointer to a Node structure as a parameter and return a complete copy of the passed-in data structure | This is an interview question that I found interesting.
Write a method that takes a pointer to a Node structure as a parameter and returns a complete copy of the passed-in data structure.
The Node structure contains two pointers to other Node structures.
For example, the method signature could look like so:
Node* Copy(... | In the generic graph case, you need a mapping from nodes in the original graph to nodes in the new graph, so that when a cycle is encountered, the proper link gets created. If you happen to have extra temporary space in each node, large enough to hold a pointer, then you can store the mapping directly in the nodes; ot... |
7,681,220 | 8,013,997 | Creating AS3 code for C++ classes converted with Alchemy (a là Box2D) | So I've a collection of C++ classes which I now have converting fine with Alchemy to a swc file and can call the exposed functions fine from my AS3 code.
What I'd really like to do is recreate stuff like Box2D's b2Vec.as class,
public class b2Vec2 extends b2Base {
public function b2Vec2(p:int) {
_ptr = p;
... | I actually got a good enough answer from the WCK guy, Jesse Sternberg. He got most of his AS3 classes that are paired with their C++ counterparts are done automatically during the build process in his own 'probe' folder. In there, there's one Box2D.c class that defines a load of templates at the top, then in the main f... |
7,681,376 | 7,681,530 | Join and re-split two std::list's without allocation | I would like to do the following:
join two std::lists (l1 and l2)
pass the combined list to a function
restore the two original lists
All this should happen without allocating new memory.
First I wanted to try this with splice(), but then I read that the iterators of the moved items would be invalidated by splice().
... | You could turn the logic around to keep a valid iterator:
auto temp = l2.begin();
l2.splice(temp, l1); // "L2 = L1 + L2"
my_function(l2);
l1.splice(l1.end(), l2, l2.begin(), temp); // restores both l1 and l2
|
7,681,420 | 7,681,434 | Embed HTML browser into a native C++/Win32 project using Visual Studio | I have a C++ project in the MS Visual Studio 2008 IDE (note, NO MFC, NO .NET, just native Win32 APIs!) and I was wondering if it is possible to add to it a child window that can parse and render HTML/CSS/JavaScript, like a browser. It would be very good if that window did not have browser controls/buttons/borders -- if... | You could embed an HTLM Browser (Internet Explorer) within your windows with some heavy use of COM. I used to do that and have the same need to avoid MFC, .NET, etc. This control is quite configurable, and you can remove and/or override pretty much anything.
I did my work based on an old article in The Code Project: ht... |
7,681,436 | 7,681,533 | Why is CSIDL_PERSONAL an integer on this line of code? | Was going through the Filezilla source code and came to this line:
int systemFolders[3] = {CSIDL_PERSONAL, CSIDL_DRIVES, CSIDL_NETWORK};
I searched the project and couldn't find these variables being declared as ints.
I looked up CSIDL_PERSONAL and it seems to be some kind of system variable for Windows.
So why are th... | CSIDLs are numerical identifiers (probably #defines, whose type is int) used to refer to some particular system folders on Windows.
To get the path/shell location they refer to have to you have to use some shell function, typically SHGetSpecialFolderPath. The CSIDL are used to specify whose special folder you want to g... |
7,681,466 | 7,681,479 | Will the class method call be optimized out in the for loop? | code
for (size_t i = 0; i < myClassObject.Method(); ++i)
some work;
I am wondering if the compiler will optimize out the method call and turn it into this?
size_t result = myClassObject.Method();
for (size_t i = 0; i < result; ++i
some work;
Would it matter if it was a function call instead? My worry is that I c... | You should state in code what you want to do. If you need a sum, you wouldn't write code that multiplies instead of adding just because you prefer to do so. It needs a smart compiler to realize that the call to Method() has no side effects, and that the loop of the body does not modify the parameters used within Method... |
7,681,555 | 7,681,612 | Resetting the End of file state of a ifstream object in C++ | I was wondering if there was a way to reset the eof state in C++?
| For a file, you can just seek to any position. For example, to rewind to the beginning:
std::ifstream infile("hello.txt");
while (infile.read(...)) { /*...*/ } // etc etc
infile.clear(); // clear fail and eof bits
infile.seekg(0, std::ios::beg); // back to the start!
If you already read past the end,... |
7,681,571 | 7,681,616 | Why is the copy constructor called on a function argument when the argument is passed by reference? | I came across this example from Accelerated C++
vector<string> func(const string&); //function declaration
vector<string> v;
string line = "abc";
v = func(line); //on entry, initialization of func's single parameter from line
//on exit, both initialization of the return value and then assignment to v
My que... |
on entry, initialization of func's single parameter from line
func's parameter is initialized from line, but it's not a string, but a reference to it. Its initialization do not result in a call to the copy constructor, but it makes the parameter become an alias for line (as always happens with initialization of refer... |
7,681,779 | 7,681,828 | easy way to maintain a min heap with stl? | for user defined struct, as I understand, it's easy. Just overload the operator <. However, for int/float etc.., do I really need to overload operator < for int?
Here is what I tried:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(const int&... | You shouldn't need to overload operator < for int (you can't, actually). If you use an external comparator, you should be passing the same Comparator comp to pop_head as well.
* Edit: *
As ildjarn pointed out, your comparison operator does not implement a strict-weak-ordering relation.
a < b ? false : true; --> a >= b
... |
7,681,813 | 7,681,881 | makefiles and linking a library in a different folder | I've search around a bit on StackOverflow and tried a few suggestions but as of yet nothing has solved the problem.
I'm making a makefile for a school project and as part of my project I'm generating a static library and linking against it. The compiler throws an error when it gets to a header include in the static lib... | In C++, library files are not enough. They are not used when compiling source code, but only when linking. To compile source file, you need to include headers. But the compiler need to know where to find it. Try adding -I utils/inc to your last line like this
g++ -c -static $(LINKFLAGS) -o obj/crawler.o -I inc -I utils... |
7,681,926 | 7,681,941 | C++ pointers difference between * and -> |
Possible Duplicate:
C++: ptr->hello(); /* VERSUS */ (*ptr).hello();
Too bad I can't google this...
Could someone explain or point me to where I can find the difference between these two? I understand * is a dereferencing operator, what about the -> ? What's the difference?
| a->b is a syntactic sugar for (*a).b
The only special case is the object operator-> which is called when -> is used on an object. It can be used to "simulate" the object is a pointer ( as with smart references )
|
7,682,072 | 7,682,158 | What exactly is the ->* operator? | I've never used it before and just stumbled upon it in an article... I thought it would be the equivalent to *x->y but apparently it isn't.
Here's what I tried, and gave me an error:
struct cake {
int * yogurt;
} * pie;
int main(void) {
pie = new cake;
pie->yogurt = new int;
return pie->*yogurt = 4;
}
| Its used when you have pointers to member functions.
When you have a pointer to a function of a class, you call it in much the same way you would call any member function
object.membername( ... )
or
objectptr->membername( ... )
but when you have a member function pointer, an extra * is needed after the . or -> in order... |
7,682,175 | 7,682,188 | Having trouble passing an object into the constructor of another class in C++ | I cannot for the life of me work out why this isn't working... Can't compile, keep getting an error "no matching function for call to 'Duty::Duty()'" for the line with the changeDuty constructor. I think it thinks I'm trying to call one of the Duty class constructors? But I just want to pass in a Duty class object!
cla... | changeDuty(Duty original) {Original = original;}
This first default-constructs Original, then reassigns it. But there is no default constructor, so it is an error. What you wanted was:
changeDuty(Duty original) : Original(original) {}
which copy-constructs Original.
|
7,682,306 | 7,682,352 | C++ Memory Management diffrences with Heap Allocation and Frame Allocation | I am slightly confused about how memory management works in C++, I understand when you use pointers (new/delete) but I'm lost when it comes to Frame allocation.
Say I have a simple class (Using QT Classes)
class Demo {
public:
Demo();
~Demo();
QString AString() const;
void setAString... | There are two allocation disciplines in C++. Heap and Stack. I'm suspecting that you mean Stack when you write 'frame'. Sometimes, especially in old C sources, it's called 'auto'.
Demo localDemo;
is how you would use the stack. Before executing the next statement after this, C++ promises to create a temporary object o... |
7,682,383 | 7,682,411 | Getting the value of a multimap in C++ | I was wondering how do I retrieve the value of a multi map in C++
| Multimap has internal structure represented as std::pair<T_k, T_v>. It has first, second members. first is the key and second is the value associated with the key.
#include <iostream>
#include <map>
using namespace std;
int main(){
multimap<int,int> a;
a.insert(pair<int,int> (1,2));
a.insert(... |
7,682,455 | 7,682,474 | Removing Empty Elements from a Vector of Strings | I'm attempting to make a small program that processes INI files, for use in a later project, first by reducing its size once loaded into memory. Thus,
where vLine is a vector containing the file contents
for (unsigned int i = 0; i < vLine.size(); i++)
{
if (!vLine[i].find(';', 0))
{
vLine[i].erase();
}
... | This:
vLine[i].erase();
does not erase vLine[i] from the vector. The expression vLine[i] returns a reference to the element at index i. So assuming that vLine is of type std::vector<std::string>, the function call erase() actually calls string::erase() on the element, not vector::erase() on the vector. All you're doi... |
7,682,477 | 7,682,539 | Why does integer overflow on x86 with GCC cause an infinite loop? | The following code goes into an infinite loop on GCC:
#include <iostream>
using namespace std;
int main(){
int i = 0x10000000;
int c = 0;
do{
c++;
i += i;
cout << i << endl;
}while (i > 0);
cout << c << endl;
return 0;
}
So here's the deal: Signed integer overflow is ... | When the standard says it's undefined behavior, it means it. Anything can happen. "Anything" includes "usually integers wrap around, but on occasion weird stuff happens".
Yes, on x86 CPUs, integers usually wrap the way you expect. This is one of those exceptions. The compiler assumes you won't cause undefined behavior,... |
7,682,541 | 7,682,667 | What does the DEBUG statement do? | I am studying nachos for a university project and can't understand what the DEBUG(...) statement in the below code is doing.
void
ThreadTest1()
{
DEBUG('t', "Entering ThreadTest1");
Thread *t = new Thread("forked thread");
t->Fork(SimpleThread, 1);
SimpleThread(0);
}
Can someone please help ?
| DEBUG is a conditional print statement that is activated when you run your code with "-d" option, as in $nachos -d ti. There are a few debug flags, for example "t" enables printing (debugging) of thread events, which you think you're after by your code snippet.
|
7,682,593 | 7,682,618 | Quick advice on "casting" variables? Very short function needing adjustment | I have some C++ code that is in this format:
void calculate(int a, float b, long c) {
long long result = (a / b) * (1000 / c);
assert(result > 0);
// more code...
}
However, the assert statement fails. It is a given that a, b, and c are all values that are positive. Then I take it that 'result' e... | If c > 1000, then the expression (1000/c) becomes zero due to integer division. Integer division is being performed here because both operands are integral types.
As a result, the expression (a / b) * (1000 / c) becomes zero, so the value of result becomes zero, triggering the assert.
The same thing will happen if b > ... |
7,682,698 | 7,682,856 | How to quickly identify functions from header files? | I'm somewhat new to C/C++, and I find myself spending exorbitant amounts of time searching through header files (one innocent include might actually bring dozens more header files with it). Even helpful IDEs like Visual Studio aren't always helpful; sometimes when I try to go to the definition of a function, it prompts... | Try adding /showIncludes to the compiler command line (In the project settings, Configuration Properties, C/C++, Command Line). This outputs all the headers used in a given .cpp file compilation. This is not a fast way, but it is a sure way.
When Intellisense isn't working, I recommend Find in Files. It is easier to tr... |
7,682,732 | 7,682,806 | GetProcAddress, Error 127 (ERROR_PROC_NOT_FOUND) | I am trying to call a function defined in a DLL, documented here:
http://xiph.org/vorbis/doc/vorbisfile/ov_fopen.html
LoadLibraryA is successful and GetProcAddress seems to return a valid address for every other function I've tried it with. Here it returns NULL here and GetLastError() returns 127 (ERROR_PROC_NOT_FOUND)... | According to this discussion thread, some versions of libvorbisfile.dll are missing ov_fopen.
|
7,682,918 | 7,683,139 | Object calling an object | Can someone explain to me the (*this) pointer and demonstrate how it would be used as far as an object calling another object of the same class. What I don't understand is how you would refer to two numbers in a member function of different 2 different objects of the same variable name. For example, multiplying two num... | this pointer:
The member functions of every object have access to a pointer named this,which points to the object itself.When we call a member function,it comes into existence with the value of this set to the address of the object for which it was called.Using a this pointer any member function can find out the addre... |
7,682,965 | 7,683,179 | is there any third party tool to create static library for armv6/armv7? | I have some source code in C/C++. I have to make static library to use in my iPhone application. is there any third party tool to create static library for armv6/armv7 ?
| this link will help you create a static library in xcode ...
http://www.icodeblog.com/2011/04/07/creating-static-libraries-for-ios/
just rename the .m file to .mm file and write your c/c++ implementation code in it....
try it for a small function first and if it works for you can implement all your classes in it...
Ple... |
7,682,999 | 7,707,740 | Obtaining the virtual key code from a WM_CHAR message | I am getting text input and keypress input from the WM_CHAR and WM_KEYDOWN messages
What I want to do is filter out WM_CHAR messages the have the same VK_ code as the key that is bound to enable the control that you enter text in.
EG: Game uses ~ to enable console, key binding is done via VK_OEM3 and WM_KEYDOWN, but te... | After some messing around I managed to extract the virtual key with the following code:
This code gets the address of lParam as a unsigned char array (one byte of length), then uses pointer arithmatic to address the 3rd byte (bits 16-23):
unsigned char scancode = ((unsigned char*)&lParam)[2];
This code translates fr... |
7,683,041 | 7,683,832 | How to implement "Variadic Template" with pre-c++0x(VS2008)? | I'm using Visual Studio 2008, and I want to implement string formatting function without Variable Argument List.
How to implement "Variadic Template" with pre-c++0x(VS2008)?
Is there any library which implements this like boost?
Or another way to implement this?
Here is my sample code.
(of course, this can't be complie... | In C++03, you have different possibilities:
generate overloads for 0-N arguments (using Boost.Preprocessor for example)
use Cons-Lists (cons(1)("some string")(foo))
use object and overload some operator (operator() for example, or operator% like Boost.Format)
The first option is a bit tricky, I feel, because not ever... |
7,683,044 | 7,683,209 | Casting an unsigned int + a string to an unsigned char vector | I'm working with the NetLink socket library ( https://sourceforge.net/apps/wordpress/netlinksockets/ ), and I want to send some binary data over the network in a format that I specify.
The format I have planned is pretty simple and is as follows:
Bytes 0 and 1: an opcode of the type uint16_t (i.e., an unsigned integer... | I like how they make you create a vector (which must use the heap and thus execute in unpredictable time) instead of just falling back to the C standard (const void* buffer, size_t len) tuple, which is compatible with everything and can't be beat for performance. Oh, well.
You could try this:
void send_message(uint16_t... |
7,683,104 | 7,683,150 | Solving numerical problems using Newtons method | I am studying numerical analysis and also solving algorithms which is described in book. My problem is about Newton's method. In general, if some function is given and we have to find root, how can we determine derivative of function in code? or even limit? because as you know Newton's method involves derivative and ... | Depending on how the function is given, you can do a couple of things
symbolic differentiation, if you have a symbolic representation of your function
Numerical differentiation, if you only have point-value pairs
Interpolate with a polynomial and differentiate that (symobolically of course)
All Options are viable. Wh... |
7,683,204 | 7,683,735 | TBB concurrent_vector with openmp | Can we use TBB concurrent_vector with openmp?
Will concurrent updates be allowed?
| Yes, TBB's concurrent data structures are meant to be thread-safe, which means whatever threading paradigms, such as OpenMP, TBB, Cilk, PPL, and etc, are okay to use TBB's concurrent data structures. This is because concurrent_vector is simply a data structure class rather than threading-related control code.
Furthermo... |
7,683,421 | 7,683,997 | Is the following undefined behaviour? | The following is an in-lined(defined inside header file) static member function. Is the literal string "MyClass" always guaranteed to be in static memory? If not, will this not be returning a pointer in stack?
const char * className()
{
return "MyClass";
}
Edit:
How about this?
const RWCString& className()
{
return "M... | The first example:
const char * className()
{
return "MyClass";
}
is fine. "MyClass" is a literal of type char const[8] which lifetime begins before your code is invoked and ends after your code is done, so no issue.
The second example, however, will not work.
const RWCString& className()
{
return "MyClass";
}
It... |
7,683,482 | 7,683,497 | c++ multiple inheritance function merging | I have:
class XILightSource
{
public:
virtual XVec2 position() const = 0;
};
class XLightSprite : public XSprite, public XILightSource
{
};
The problem is that XSprite already has the same function position. How can i say to compiler, that i want to use XSprite::position function as an implementation of XILight... | override it and call XILightSource::position() :
class XLightSprite : public XSprite, public XILightSource
{
public:
XVec2 position() const { return XSprite::position(); }
};
|
7,683,568 | 7,683,694 | C++ OpenMP directives | I have a loop that I'm trying to parallelize and in it I am filling a container, say an STL map. Consider then the simple pseudo code below where T1 and T2 are some arbitrary types, while f and g are some functions of integer argument, returning T1, T2 types respectively:
#pragma omp parallel for schedule(static) priva... | This particular example you have is not a good candidate for parallelism unless f() and g() are extremely expensive function calls.
STL containers are not thread-safe. That's why you're getting the race conditions. So accessing them needs to be synchronized - which makes your insertion process inherently sequential.
A... |
7,683,688 | 7,683,757 | newtons methods implementation | i have posted a few hours ago question about newtons method,i got answers and want to thanks everybody,now i have tried to implement code itself
#include <iostream>
#include <math.h>
using namespace std;
#define h powf(10,-7)
#define PI 180
float funct(float x){
return cos(x)-x;
}
float derivative (float x... | Several things:
2 iterations is rarely going to be enough even in the best case.
You need to make sure your starting point is actually convergent.
Be aware of destructive cancellation in your derivative function. You are subtracting two numbers that are very close to each other so the difference will lose a lot of pre... |
7,683,868 | 7,684,035 | Easy way of using STL algorithms in C++ | I have this code on Win32:
Actor* Scene::GetActor(const char* name)
{
StringID actorID(name);
auto actor = find_if(m_actors.begin(), m_actors.end(), [&](Actor* actor){return actor->GetName() == actorID;});
return actor != m_actors.end() ? *actor : NULL;
}
Because this couldn't be compiled on iPhone with ... | You can try to implement a generic predicate for this, something along these lines (demo here):
template<class C, class T, T (C::*func)() const>
class AttributeEquals {
public:
AttributeEquals(const T& value) : value(value) {}
bool operator()(const C& instance) {
return (instance.*func)() == value;
... |
7,684,014 | 7,684,130 | C++ printf with %f but localized for the user's country | I'm using the following C++ syntax to output a floating point value on a Windows platform:
printf("%.2f", 1.5);
It works well if I run it on an English user account. My assumption was that if I run it on, say French user account, the output will be 1,50 instead of 1.50.
Why do I not see it and how to produce my desire... | The radix character (i.e. '.' or ',') is defined by the current locale. The default locale (at least for Windows systems) is "C", which defines '.' as radix character.
You can set the current locale for a C/C++ program using the setlocale function.
To set the locale to the current system/user locale, you can use the fo... |
7,684,428 | 7,684,511 | Thread safe container | There is some exemplary class of container in pseudo code:
class Container
{
public:
Container(){}
~Container(){}
void add(data new)
{
// addition of data
}
data get(size_t which)
{
// returning some data
}
void remove(size_t which)
{
// delete specified object
}
private:
data d;
};... | First of all mutexes should not be static for a class as long as you going to use more than one instance. There is many cases where you should or shouldn't use use them. So without seeing your code it's hard to say. Just remember, they are used to synchronise access to shared data. So it's wise to place them inside met... |
7,684,449 | 7,684,480 | stl map, set error: memory clobbered past end of allocated block | As I tried to solve this interview problem: find the sum of continuous element in an array which equals to a target number, so I come up with the following code. However, I really don't understand why it has some memory allocation problem. Here is the link to the full code. when I tried to insert the second element of ... | The error is in this line:
int* currSum= new int(sizeArr+1);
That line acquires a single int and initializes it to the value sizeArr+1. You probably meant:
int* currSum= new int[sizeArr+1];
That will acquire a block of sizeArr+1 elements of type int. Additionally you will have to change the line delete currSum; to be... |
7,684,472 | 7,684,912 | Do C++ formatting libraries generally fall back to *sprintf for numeric formatting? | I am wondering whether "all" C++ formatting libraries eventually fall back to a *sprintf function to format numbers.
I am asking this because:
Looking at the iostreams library that comes with Visual C++, I can see that numbers input into a stream will eventuall be formatted with sprintf_s.
Boost.Format just uses the a... | Boost Spirit doesn't use *printf, as can be seen from the code (real.hpp and int.hpp) and the benchmarks for e.g. ints and doubles.
The benchmark pits Boost Spirit Karma's generators against Boost.Format against sprintf and std::stringstream. Only for gcc compilers does the performance of sprintf come close in that ben... |
7,684,712 | 7,684,777 | 2D Matrix allocation on heap in c++ | I am looking for a way to allocate a 2D (m x n) matrix on the heap where the elements are consecutive in memory. Currently I know of two ways to accomplish that:
First approach
int* M = new int[m * n];
Pro: The size of M can by dynamically determined.
Con: Indexing of M is a bit of a pain. (M[i * m + j])
Second appr... | You can try this
int** M = new int*[m];
int *M_data = new int[m*n];
for(int i=0; i< m; ++i)
{
M[i] = M_data + i * n;
}
|
7,684,889 | 7,684,920 | Implementing a very small HTTP server in c/c++ and want to use AJAX | I want to have a dynamic webpage that automaticly updates some information, this information should be received from my c/c++ application using HTTP. I have set up a socket and can send HTML and Javascript files to the browser.
I don't know how to move on. How to encapsulate my data into XMLHttpRequest objects? Or may... | A server should handle it as any other request. From the servers point of view, it's a normal HTTP request. Return the data that the client asks for! This is usually a HTML fragment, some XML or some JSON.
|
7,685,039 | 7,685,081 | How to catch integer divide by zero and access violation exceptions in native C++ | I need to catch Integer divide by zero and access violation reading or writing a protected memory and display my own dialog, and do something approprate. These exception can not be catched by try {} catch {} mechanism because hardware generates these exceptions.
How can I catch there exceptions?
Any suggestions or refe... | It's strange not to have the possibility to catch these exceptions. but if it's like that, than i guess you can put your own validations and throw your own exceptions. But again, you may be missing something...
|
7,685,080 | 7,685,113 | Pointer to overload function | Let's say, i want to this thing:
std::thread(std::sin,2.9);
But i get unresolved function type error. How can i resolve it?
std::sin is overloaded, not template (why??)
| Depending on what headers you included, there are the following:
template<class T> complex<T> sin (const complex<T>&); // <complex>
template<class T> valarray<T> sin (const valarray<T>&); // <valarray>
float sin(float); // <cmath>
long double sin(long double); // <cmath>
As you can see, there are templat... |
7,685,313 | 8,414,386 | How to print xml image in IOS? | I've created a simple XML-Parser to parse my rss Feeds to my app.
The id, currentstatus, picture of the simple to parse from the xml file.
But I can't get the image from the XML file. . i retrieve the all the images from xml file. but the noimage.jpg not displaying. could you please any help me.
XML code
<Agent>
<id>34... | You're using cellimages which is an UIImage object to store strings in your else-branch. Also when cellvalue == disable is true, you execute this:
cellimages = [UIImage imageWithContentsOfFile:@"http://telecomstats.co.uk/images/LLReaderProfile/noimage.jpg"];
cellimages = [[UIImage alloc] initWithData:[NSData dataWithCo... |
7,685,610 | 7,685,852 | fixed point iteration | i am trying to find such p,that for given function f(p),we have equality
p=f(p);
here is code
#include <iostream>
#include<math.h>
using namespace std;
float fixed(float x){
return (float)(pow(x,3)-4*pow(x,2)-10);
}
int main(){
float p=0.0;
float p0=1.5;
float tol=(float).001;
int N=25;
int ... | I think you simply don't have a situation in which the iterative algorithm is applicable. See here for some conditions. Your function doesn't have an attractive fixed point near 1.5, and the algorithm diverges.
But why the numerics: Your function is f(x) = x^3 - 4x - 10, so solving f(x) = x amounts to finding the zeros... |
7,685,641 | 7,686,071 | Waf throwing errors on c++ builds | Our project contains a lot of c++ sources, up until now we were sing make to build everything, however this takes ages. So I stumbled upon waf, which works quite well and speeds up the build a lot. However everytime I do a full build I end up with a couple of build errors that make no sense. If I do an incremental buil... | I'm suspecting multiple targets are building the same required object in parallel. Try
export JOBS=1
or
waf --jobs 1
|
7,685,643 | 7,685,780 | Issues while making a java like runnable class in C++ | I've been trying to create a runnable class in order to interface multi-threaded classes just like java-folks do. But I can't seem to use _beginthread with the virtual function run.
I'm getting the following error:
'beginthread' : cannot convert parameter 1
from 'void (_cdecl Runnable::* )(void *)' to 'void (__cdecl *... | You need the function to be passed to _beginthread to be static.
I suggest you read this article by Herb Sutter and try to implement the Active Object Pattern.
|
7,685,779 | 7,685,908 | C++ - Boost Thread/Bind/Shared_ptr : Assert fault | I am having a small issue that I cannot solve. I am making a small server to redirect my syslog messages to it. It is very basic, but I would like to know what I did wrong cause I keep have the following error when I call join ():
/boost/path/shared_ptr.hpp:418: T* boost::shared_ptr< <template-parameter-1-1> >::operato... | The reason for the assertion is not immediately clear from the code that you have presented here, but nonetheless, this code could be improved significantly.
You appear to be using a shared_ptr, but there does not seem to be any need. Ptr_thread could be changed to just boost::thread. This would lead to simpler, more e... |
7,685,816 | 7,685,854 | Enums, overlapping values, C# | Apologies in advance as I'm sure someone must have asked this before but I can't find it.
Just had a surprise, a colleague and I both added the same value in for an enum, and it compiled, e.g.
enum MyEnum
{
mine = 1,
his = 1
}
Looks like C/C++ supports this also (?). Any reason for this behaviour, any ca... | Let's take a simple example
enum PrivilegeLevel
{
None,
Reporter,
Reviewer,
Admin,
DefaultForNewUser = None,
DefaultForProjectOwner = Reviewer,
};
|
7,685,862 | 7,686,160 | C++ pointers to functions as param | #include<iostream>
using namespace std;
void passPointer(int *pointer)
{
cout << *pointer;
}
int main()
{
int *iNum = new int(25);
passPointer(iNum);
return 0;
}
Can someone explain to me why when I use the passPointer() function in main, it has to be passPointer(iNum) but not passPointer(*iNum)? ... | I am very sympathetic to these sorts of questions, because this is one of the only things that I had trouble with when learning C++.
The basic problem is that in the syntax of C++, the * and & characters are used for many different things with similar but subtly different meanings.
In your case, you are considering usi... |
7,686,056 | 7,686,087 | static member of class in c++ | I have a question about static member of class in c++, since the static member belongs to the class not any instance of class, so should the static member be declared as public, private?
| Whether or not to declare a member public or private has nothing to do with whether it is static or not. You can have a static member be either public or private; both uses are acceptable depending on the situation.
Basically, if you want or need components outside of the class to have direct access to the static membe... |
7,686,167 | 7,686,935 | glOrtho is not working? | /* OpenGL animation code goes here */
glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
glClear (GL_COLOR_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f,512.0f,0.0f,512.0f,0.0f,1.0f);
glMatrixMode(GL_MODELVIEW_MATRIX);
... | glOrtho(0.0f,512.0f,0.0f,512.0f,0.0f,1.0f);
This projection effectively selects the box of width 512, height 512 and depth 1 units to be the visible world space. However the vertices you specify will all be within a very small subset of the box, i.e. within one unit.
glBegin (GL_TRIANGLES);
glColor3f (1.0f, 0.0f, 0.0f... |
7,686,220 | 7,691,313 | Using SwapMouseButton( TRUE ); to allow right click dragging of a window | I am required to somehow allow a window to be moved using a right click drag option. I have done this via some sneeky code which I don't really like but it works.
Currently I am trapping the WM_NCRBUTTONDOWN message and setting a bool to say that I am in move mode, resetting this variable when the WM_NCRBUTTONUP is rec... | Instead of manually tracking the mouse or swapping the buttons, there is an easier way - in response to WM_NCRBUTTONDOWN, simply put the window into a move mode natively by sending it a special WM_SYSCOMMAND message, then it will handle all the hard work of dragging for you, eg:
const WPARAM MOUSE_MOVE = SC_MOVE + 2;
... |
7,686,245 | 7,687,297 | Multiple predicates specified during runtime | There are operator classes in STL like less, equal_to, greater_equal etc. How to easily combine them to use with for example remove_if function?
For example I want to remove in vector elements which are greater than 0 AND less than 3 AND not equal to 2, then it would be something like:
remove_if (v.begin(), v.end(), b... | This is rather simple in your case, actually.
You first need to parse the statement the user gave, and turn it into an AST (Abstract Syntax Tree). It turns out that this AST is nearly already suitable.
x > 0 && x < 3 && x != 2
Can be expressed as a tree:
AND
/ \
> AND
/ \ / \
x 0 < ... |
7,686,318 | 7,686,467 | Locking sqlite3 db for file download | I have a sqlite3 database on some system which I need to download during ongoing operation. Stopping or pausing the accessing processes is not an option. So as far as I understand this I need to hold a SHARED lock (as described in http://www.sqlite.org/lockingv3.html) to the db during download to avoid db changes and c... | No, no. no and no!
Messing with locks and copying files by hand is the old way to do things. SQLite now has a proper backup API that you can use. It is the recommended way to perform on-line copies of an SQLite database - you can use it to create a copy of the database, which can be then downloaded at your convenience.... |
7,686,343 | 8,944,722 | QGIS: Default constructor for QgsVectorLayer and QgsRasterLayer? | I'm trying to create a Windows Forms control using the QGIS API and a pre-defined QGIS project file, so that I can set X and Y properties on the Windows Forms control and the QGIS API will show the predefined map data in the Control, focused at the supplied coordinates.
Using QgsProject::instance()->read() seems to cau... | Just a guess: Do you use Visual Studio 2008? http://hub.qgis.org/wiki/quantum-gis/Building_QGIS_from_Source#Building-with-Microsoft-Visual-Studio indicates that the QGIS binaries (I assume that you're using them) are build using Visual Studio 2008 - if you use a different compiler version, you might encounter runtime m... |
7,686,538 | 7,686,693 | boost lambda with a vector of shared pointers | Below is a slightly modified code from one good example how to copy values fro one vector of strings to another vector of objects. (see: another copy algorithm )
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda... | std::vector<shared_ptr<Object> > objects(3, make_shared<Object>());
This is equivalent to doing:
shared_ptr<Object> object = make_shared<Object>();
std::vector<shared_ptr<Object> > objects(3, object);
The vector constructor will then make 3 copies of that object pointer, which will all refer to same one and unique Ob... |
7,686,745 | 7,686,763 | 3D vector constructor C++ | For a 2d vector, I know I can go:
vector<vector<T>> vec;
vec = vector<vector<T>> (boardSize, vector<T>(boardSize));
But how do I do it for a 3d vector?
I tried
vector<vector<vector<T>>> vec;
vec = vector<vector<vector<T>>> (boardSize, boardSize, vector<T>(boardSize));
But it wouldn't compile. Any ideas?
| Just a guess:
vec = vector<vector<vector<T>>> (boardSize, vector<vector<T>>(boardSize, vector<T>(boardSize)));
That means, when you've declared a vector<vector<T>>, the second argument should be a vector<T>; and when you declared a vector<vector<vector<T>>>, the second argument should be a vector<vector<T>>, which in... |
7,686,753 | 7,687,190 | Boost MPL: Call a (member) function only if it exists | I have a class A that has a template parameter T. There are use cases where the class T offers a function func1() and there are use cases where T doesn't offer it.
A function f() in A should call func1(), iff it exists. I think this should be possible with boost mpl, but I don't know how.
Here some pseudo code:
templat... | Boost.MPL doesn't deal with that as it's strictly for TMP and you can't call members in TMP. Boost.Fusion and Boost.TypeTraits don't have anything either; I thought one of them would but apparently I'm misremembering.
Here and here are some solutions on how to write a trait to detect a member in C++03. Once you have su... |
7,686,911 | 7,687,075 | Using Queue class to queue carriages of a Train - C++ | I am attempting make a simulator class that will use a Queue to add the Carriages from Train in to a Queue, so it will become a Queue of carriages. Carriage is also the dataType of the train class.
I will use a method to enqueue trains as they arrive, adding them to different queues. I will also have a method to deque... | You are passing argument of type LinkedList to a constructor takes argument of array of datatype, which causes the error.
You can, however, loop through every train1 element, and push it to the Queue.
As a note, push and pop are function names for the stack. Queue has enqueue and dequeue
|
7,686,939 | 7,687,050 | C++: Simple return value from std::thread? | With win32 threads I have the straight forward GetExitCodeThread() that gives me the value which the thread function returned. I'm looking for something similar for std::thread (or boost threads)
As I understand this can be done with futures but how exactly?
| See this video tutorial on C++11 futures.
Explicitly with threads and futures:
#include <thread>
#include <future>
void func(std::promise<int> && p) {
p.set_value(1);
}
std::promise<int> p;
auto f = p.get_future();
std::thread t(&func, std::move(p));
t.join();
int i = f.get();
Or with std::async (higher-level wr... |
7,687,041 | 7,687,156 | dynamic_cast with RTTI disabled | I'm curious to know what happens when compiling code with a dynamic cast whith RTTI disabled
(either with -fno-rttion GCC or with /GR- on visual studio). Does the compiler "falls back" to static_cast ? Since (at least on VS) it does only issue a warning, what will the compiled code do ?
More specifically, what bad thi... | The easiest way to find out is to try it.
What you will find is that some of your dynamic casts will be flagged as illegal. Some won't. For example, the conversion is known at compile time when you use dynamic cast to upcast to an unambiguous base class.
Addendum
Re "Since (at least on VS) it does only issue a warning ... |
7,687,059 | 7,687,142 | use qsort with comparator function | i know qsort from c library and i have implemented it with chars and integers(convert from const void * form to relevant form) but now i am implementing code which gives me longest duplicated in given sentences here is simple compare function
int pstrcmp(char **p,char **q){
return strcmp(*p,*q);
}
and i wa... | You need to give your comparator function the correct function signature and then cast internally, e.g.
int pstrcmp(const void * p, const void * q)
{
const char **ps = (const char **)p;
const char **qs = (const char **)q;
return strcmp(*ps, *qs);
}
|
7,687,148 | 7,687,312 | Drawing Sphere in OpenGL without using gluSphere()? | Are there any tutorials out there that explain how I can draw a sphere in OpenGL without having to use gluSphere()?
Many of the 3D tutorials for OpenGL are just on cubes. I have searched but most of the solutions to drawing a sphere are to use gluSphere(). There is also a site that has the code to drawing a sphere at t... | One way you can do it is to start with a platonic solid with triangular sides - an octahedron, for example. Then, take each triangle and recursively break it up into smaller triangles, like so:
Once you have a sufficient amount of points, you normalize their vectors so that they are all a constant distance from the ce... |
7,687,230 | 7,743,703 | Problems with opening a process with DEBUG flags | I'm trying to open a process with my debugger using CreateProcess with the DEBUG_PROCESS and DEBUG_ONLY_THIS_PROCESS flags and the the process is opened, but then when I try to call SymInitialize with the handle I receive, it fails.
This is my code:
#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>
#pragm... | Your error is result of calling MAKE_HRESULT macro as
MAKE_HRESULT(ERROR_SEVERITY_ERROR, FACILITY_NULL, ERROR_INVALID_DATA)
So your error code is not trash. Documentaion doesn't say what kind of data might be invalid in this context. I will try to see what exactly is causing the problem.
EDIT:
This code works for me
... |
7,687,279 | 7,991,530 | Isn't boost::asio fully UNICODE compliant? | I am writing a C++ application that is using boost::asio for some http operations. I chose boost::asio assuming it is fully unicode compliant. However, I am unable compile in UNICODE because some part of asio is hardcoded to char.
Case in point:
#ifndef TCHAR
#ifdef _UNICODE
#define TCHAR wchar_t
#else... | Correct, boost::asio is not UNICODE compliant.
|
7,687,521 | 7,687,678 | C++ wxWidgets Gui-App stays in memory after closing it | The subject says it all. After i closed my app, it stays in the list of processes with some memory. I tried google perf tools and hours of debugging to find the leak.
Are there other tools to test it and find the problem?
Thank you.
| My guess is that you have closed the top level window, and thus all its child windows, but you have not closed the app itself.
This does not happen if your program is arranged in a 'normal' way, but if you have, deliberately or by accident, used an unusual arrangement this can happen.
Fixing it, of course, depends on h... |
7,687,634 | 7,687,945 | Is there a way to escape a C preprocessor directive? | What I am trying to do is have the C preprocessor output #ifdef, #else, and #endif directives. That is, I would like to somehow "escape" a directive so that the output of the preprocessor includes the directive were the preprocessor to run on the output.
Is it possible to "escape" a CPP directive so that it is outputte... | A slight variant of Marcelo Cantos's answer works for me on GNU cpp 4.4.3:
#define HASH(x) x
...
HASH(#)ifdef __cplusplus
class foo { };
HASH(#)endif
|
7,688,107 | 7,688,146 | Is copy thread-safe? | In terms of C++11, am I correct in thinking that copy of value-semantic objects that is shared between at least two threads isn't thread safe?
Meaning that if we want to get a copy of an big object in a thread, we still need some synchronisation mecanism to make the copy?
|
Meaning that if we want to get a copy of an big object in a thread, we still need some synchronisation mecanism to make the copy?
Yes. If the object is accessed (written to) from other threads and you want to copy it, you have to ensure the access is synchronized.
|
7,688,150 | 7,688,212 | Different behavior with different types of arrays | i have tested two different varianat of similary code ,suppose i have char array
char x[]="snow comes in winter ";
then following code
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char x[]="snow comes in winter ";
int k=0;
int n=3;
cout<<x+n-k+1<<endl;
system("PAUSE");
return... |
why we can access in case of char array so easily?
Because there's a convention that C strings are represented by char*, people assume char* are actually strings. The iostreams follow that and overload output for char* to print the string, whereas for an int* (in your second example), they print the representation of... |
7,688,371 | 7,688,481 | Reading from two serial ports simultaneously in c++ | The operating system I am working with is Windows 7. I am needing to grab data at certain intervals from a broadband card. This car sends data to two separate COM ports. COM 3 and COM 4. Every interval I will need to query the line of info on both serial ports and write them to a file.
How do I read from two COM ports?... | Take a look at this tutorial. If you open up the com port and then make a call to WaitComEvent in overlapped IO you'll get a handle in the OVERLAPPED that can be used in WaitForMultipleObjects.
You should be able to do it in a single thread with the general outline below:
HANDLE hSerial3;
hSerial3 = CreateFile("COM3",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.