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 |
|---|---|---|---|---|
6,090,820 | 6,090,879 | Any basic C++ websites/ book using visual studio 2008 enviroment? | I am looking for websites/books which teach C++ in visual studio 2008
THanks
| For C++ using Visual Studio, the obvious site would be MSDN itself. Go through these:
Visual C++ Walkthroughs
Getting Started with Visual C++
Introducing the Visual Studio IDE (C++)
|
6,090,901 | 6,090,909 | 'memcpy' is not defined in this scope | I am getting a "memcpy is not defined in this scope error" with the following piece of code:
CommonSessionMessage::CommonSessionMessage(const char* data, int size)
: m_data(new char[size]) {
memcpy(m_data.get(), data, size);
}
I have looked through this site and google and could not find a solution that would r... | Did you include string.h/cstring (or another header that includes it) at the beginning of your code file?
|
6,090,911 | 6,090,942 | c++ vector problem; passing stuff by reference | So I've checked my pointers and I'm really not sure what's going wrong here. I'm passing 2 vectors of vectors by reference to a function that modifies them. Here's the function:
bool imageToTips( Mat& img,
vector<vector<int> > & fingertips,
vector<vector<Point> > & hand,
double epsilon,
double theta){
//c... | You don't need the () to default-construct a variable, otherwise you're defining a function.
vector<vector<int> > fingertips;
vector<vector<Point> > hands;
// ^ loose the ()s
|
6,090,976 | 6,091,201 | Swig, Python, C++: TypeError: in method 'Geodatabase_Open', argument 2 of type 'std::string' | I am new to C++ and SWIG. This is my first project.
I am able to successfully build my Python extension using distutils. However, when I try my object, I keep getting this error.
It seems that there is a conversion problem from getting the python string and transforming it into a std::string.
I am working on Windows 7... | According to the swig documentation, using std::string requires %include "std_string.i".
%module example
%include "std_string.i"
std::string foo();
void bar(const std::string &x);
|
6,091,215 | 6,091,359 | text game character collision detection problems | I'm making a game where you avoid walls made of 'X's as you move down the screen, and if you hit an X you lose a shield and keep plowing through the X's without losing any more shields until you pop out into a character space where there isn't an X.
However, when running the code below along with some other unneccesar... | I suggest a drastic re-organization of the code. This routine appears to be concerned with both drawing the player on the screen and changing the player's shield rating. I believe if you separate the display of the player from the modification of the player, your code will be easier to read and maintain.
Consider this:... |
6,091,299 | 6,091,376 | Help with using the perlin noise library libnoise | When I call libnoise's getvalue function with x, y, and z as integers I always get 0 back as a result. Is this normal? When I try 1.25, 0.75, 0.5 as in the tutorial http://libnoise.sourceforge.net/tutorials/tutorial2.html I get the expected result of 0.686347. Specifically I've tried this with integers under 20. Do... |
Although Oli Charlesworth is correct, you're getting zeroes at integer values because all zeroes occur at integer values. See the above graph for an easy visual demonstration! The reason why zeroes occur at integers is due to the fact that coherent noise is stipulated to be smooth (as opposed to jagged) and a very eas... |
6,091,316 | 6,091,321 | Is there a more or less agreed-upon convention as to how one should call member functions which return the _support_ of a functor? | In a function object representing a compactly-supported function f mapping the real numbers to the real numbers, how should I call a member function which returns an interval outside of which the values of f are zero? Should I rather use one single member function, returning the entire interval as some special object (... | If the return value is modelled by a single concept, return a single object and have a single function.
|
6,091,443 | 6,452,372 | QTableView view displays nothing | I am working with SQLite from Qt and I can't seem to make code that is derived from one of examples to work properly. My QTableView displays nothing, even though its model is by no means empty:
QSqlTableModel model;
initializeDeliveryModel(&model);
QTableView *view = new QTableView;
view->setModel(&model);
//view->s... | Did you add your QTableView to corresponding form layout?
|
6,091,837 | 6,091,846 | sin and cos are slow, is there an alternatve? | My game needs to move by a certain angle. To do this I get the vector of the angle via sin and cos. Unfortunately sin and cos are my bottleneck. I'm sure I do not need this much precision. Is there an alternative to a C sin & cos and look-up table that is decently precise but very fast?
I had found this:
float Skeleton... | For your fastSin(), you should check its documentation to see what range it's valid on. The units you're using for your game could be too big or too small and scaling them to fit within that function's expected range could make it work better.
EDIT:
Someone else mentioned getting it into the desired range by subtractin... |
6,091,895 | 6,091,936 | QDialog-derived form closes immediately | I am trying to make a form with data table appear when the button is clicked on thr main form. However, in practice second form 'blinks' - appears less than on second - and then vanished. What could be the reason and how that should be fixed?
Here is the derived form header and source files' content:
#ifndef GOODTABLE_... | The problem is, that you have a local dialog object on the stack in your on_goodTable_clicked method. So you create the view, call show, which shows the dialog and immediately returns, then your view get's destroyed as you leave the function. If you make the dialog modal anyway, why not use QDialog's exec method intead... |
6,091,944 | 6,091,968 | Why does printing an object fail with a "no match for 'operator<<'" error? | I have created a dynamic memory as s_points, which has the type PointList. PointList is vector of integer values. I have appended to s_points by getting some values from another list of data. Now I want to visualise my s_points to check whether it is updated or not, but I have an error:
no match for 'operator<<' in 'st... | The error speaks for itself. You don't have operator<<() defined for Number.
|
6,092,004 | 6,092,022 | Reading a ";" delimited file into a character array structure | I am trying to read a set of values from a text file into an array of structures of arrays. The entries are each separated by a '\n', and each entry consists of 3 values, separated by a ';'.
The problem is that after correctly reading the first line of file data the program reads the first value from the second line, t... | Perhaps the last get should be:
InputFile.get(TaskList[ListSize].DueDate, BUFFERSIZE, '\n');
instead of
InputFile.get(TaskList[ListSize].DueDate, BUFFERSIZE, ';');
Your last field (due date) does not have a semicolon at the end, only a newline.
Update: I suggest you also look into using getline instead of get. They h... |
6,092,102 | 6,092,121 | Getting "carry" in x + y |
Possible Duplicate:
Best way to detect integer overflow in C/C++
If I have an expression x + y (in C or C++) where x and y are both of type uint64_t which causes an integer overflow, how do I detect how much it overflowed by (the carry), place than in another variable, then compute the remainder?
| The remainder will already be stored in the sum of x + y, assuming you are using unsigned integers. Unsigned integer overflow causes a wrap around ( signed integer overflow is undefined ). See standards reference from Pascal in the comments.
The overflow can only be 1 bit. If you add 2 64 bit numbers, there cannot be ... |
6,092,113 | 6,102,560 | How can I check for a valid contact ID in my Symbian app? | In my application I have two views, Main View and Contacts view, and I have a saved Contacts ID.
When I load my second view, that should access default Contacts Database using my saved ID list and get these contacts information Title, etc. It leaves because the contact has been deleted.
So, How can I check if the cont... | Thanks Abhijith for your help, and I figured out the reason behind this issue, I shouldn't call
ReadContactL directly under TRAPD under For loop, So I created a function that checks the ID validity
and I called it under TRAPD, and now my Contacts List View loads well, and invalid IDs removed from
My saved IDs list.
... |
6,092,220 | 6,094,257 | C++ For what types can the parameter type name be the same as the parameter name with a type specifier? | This question is going to take a bit of explination, sorry. I am fixing an oversight in doxygen parsing some C++ code and I have come across an unusual corner case that doxygen doesn't account for. I have a fix but I want to make it more general so I need some explanation.
To illustrate the case where doxygen is failin... | What compiler and version are you using?
void foo( simpson simpson ) {}
No enum present, that is, you don't need to use an elaborated type specifier in this context, and it compiles perfectly in gcc 4.2 and 4.6. The problem is that inside the function, the argument name hides* the type, and if you want to declare a n... |
6,092,278 | 6,092,339 | When/How do container data types (string, vector, etc.) in C++ free their dynamically allocated memory? | Since container data types have dynamic size I'm assuming they allocate memory on the heap. But when/how do they free this allocated memory?
| They get freed either when they go out of scope (if the container was created in the stack), or when you explicitly call delete on the container(in case of heap-based container). When this happens, the destructor of the container automatically gets called and the heap memory allocated for the container (that contains t... |
6,092,524 | 6,093,423 | WinCE C++ Application development | Should I install Windows Embedded CE 6.0 for developing a WinCE application?.
What steps should I follow to develop a sample WinCE c++ application?
How can I copy the new application to the device?
|
Should I install Windows Embedded CE
6.0 for developing a WinCE application?.
No, you just need Visual Studio 2005/2008 and the SDK of your target device (Visual Studio 2010 does not support WinCE/WinMO development). You may need Windows Embedded CE 6.0 if you are the OEM of the device, depending on your deployment... |
6,092,856 | 6,092,886 | What does "variable|variable" mean in C++? | I was looking into this ITE8712 watchdog timer demo code when I saw this:
void InitWD(char cSetWatchDogUnit, char cSetTriggerSignal)
{
OpenIoConfig(); //open super IO of configuration for Super I/O
SelectIoDevice(0x07); //select device7
//set watch dog counter of unit
WriteIoCR(0x72, cSetWatchDogUnit|cSetTrigge... | It's a bitwise or, as distinct to your normal logical or. It basically sets the bits in the target variable if the corresponding bit in either of the source variables was set.
For example, the expression 43 | 17 can be calculated as:
43 = 0x2b = binary 0010 1011
17 = 0x11 = binary 0001 0001
==== ====... |
6,092,874 | 6,092,902 | boost unordered set not working | I am new to boost. I am trying to implement boost::unorder_set. Here is the code:
struct point {
int x;
int y;};
bool operator==(point const& p1, point const& p2) {
return p1.x == p2.x && p1.y == p2.y;
}
struct point_hash {{
size_t operator()(point const& p) const
{
size_t seed = 0;
hash_combine(seed, p.x);
... | unordered_multiset cannot be constructed from a single element (it has no such a constructor). Try this:
point pt;
boost::unordered_multiset<point,point_hash> points;
points.insert( pt );
Also you need properly included header:
#include <boost/unordered_set.hpp>
|
6,092,879 | 6,092,953 | Need some help with errors, culmination of a File System Project | class BufferFile{
public:
BufferFile(IOBuffer &);
int Open(char *);
int Create(char *);
int Close();
int Rewind();
int Read(int recaddr = -1);
int Write(int recaddr = -1);
int Append();
IOBuffer & GetBuffer();
protected:
IOBuffer & Buff... | Several of the errors mention that class IOBuffer has no member named "pack". The message is absolutely correct, it doesn't; if you look at the header, it has a method named Pack, with a capital P. C++ is case-sensitive!
The errors about "redefinition" are happening because your include files don't have include guards ... |
6,093,086 | 6,093,626 | Changing a normal function to template will make any positive/negative difference? | I have a wrapper function (templatized) Outer() and core functionality function as Inner().
namespace N
{
A* Inner (void *p, int value, const int ID);
template<typename T>
A* Outer (T *p, const int ID) // ID is a compile time constant
{
return Inner (p, p->value, ID);
}
}
Usage:
A *px = Outer(new X(3),... | None. The function is a template and therefore must be inlined, and constant folding like this is one of the most common optimizations done when functions are inlined. This suggests that if you have a modern compiler, it will make absolutely no difference whatsoever.
|
6,093,170 | 6,093,251 | Function and Class errors | class BufferFile{
public:
BufferFile(IOBuffer &);
int Open(char *);
int Create(char *);
int Close();
int Rewind();
int Read(int recaddr = -1);
int Write(int recaddr = -1);
int Append();
IOBuffer & GetBuffer();
protected: ... | I think your problem is this (from Buffile.h):
#ifndef IOBUFFER
#define IOBUFFER
#include "Iobuffer.h"
#endif
... that logic breaks the similar/redundant logic that you have in Iobuffer.h:
#ifndef IOBUFFER
#define IOBUFFER
class IOBuffer{
[...]
#endif
The problem is that the declaration of "class IOBuffer" in Iobuffe... |
6,093,523 | 6,093,549 | How to make my EXE can accept parameter at the console? | Here is the code that I use to play around with. I want to make this code can accept parameter from the console.
Now I can only run the code with hardcoded parameter. At the console I just type Example1Client.exe and press Enter.
I would like to send parameter like this: Example1Client.exe http://www.website.com
int ma... | Modify definition of your main to: int main(int argc, char *argv[]) instead of int main().
Inside the main then, you can have the code as follows:
std::string url = "some default url";
if (argc > 1) {
url = argv[1];
}
Similar question(s) on Stackoverflow:
Passing filename as arguments in C
Passing command line ... |
6,094,176 | 6,094,323 | multidimensional string c++ | I'm writing a function that has a 2D array of strings as input parameter. I initialized the string, passed it to the function but when I tried to print the array nothing happened. It says that the length of the array is 0. All my functions are stored in a header file. Here's my code:
#include<iostream>
#include<string>... | The reason why you don't get any output is that you don't initialize the global variable rows, so it stays at 0. Your init function should be:
void ini(int focus_text_color, int n_fields,int n_rows, string options[][50], bool animation=false, int animation_speed=10)
{
color=focus_text_color;
fields=n_fields;
... |
6,094,309 | 6,094,357 | Disabling pointer output in C++ streams? | If you hand any pointer to a C++ stream, it's address will be put into the output. (Obviously unless there's a more specific output handler.)
void* px = NULL;
const char* ps = "Test";
FooType* pf = ...;
stringstream s;
s << ps << " " << px << " " << pf "\n";
s.str(); // yields, for example: "Test 0 AF120089"
This can ... | This gives a compilation error in g++ if the second and/or third output to cout is uncommented:
#include <iostream>
using namespace std;
ostream & operator << ( const ostream &, void * ) {
}
int main() {
int n = 0;
cout << 0;
// cout << &n;
// cout << (void *) 0;
}
|
6,094,452 | 6,095,220 | QTableWidget - context menu only for specific cells/columns | I am using a QTableWidget for displaying data. I know that I can use the addAction method to add a context menu. How can I limit the context menu to only specific cells or columns? addAction exists for QActionGroup QGraphicsWidget QMenu QMenuBar QToolBar QWidget. Should I somehow filter oder disable/enable the signal/s... | Another method to create custom context menus is to implement a slot to the QWidget::customContextMenuRequested() signal. There you can query the cell under the position (QTableWidget::itemAt() - watch out for global->widget mapping!), and then build a custom menu using QMenu and QAction.
Also, I'd build the menu(s) be... |
6,094,502 | 6,094,579 | Textmate to browse C++ project with a bunch of files and CUDA | I am new to Textmate. I have to work on a CUDA C++ project and at the moment just would like to get the project (bunch of files and directories), start with the main C++ file and from there, selecting functions and that Textmate jumps to the definitions which usually are in other files. Is it possible with Textmate and... | You want the CTags bundle for TextMate. Here's a tutorial that explains how to do by hand what the bundle does for you.
|
6,094,648 | 6,094,670 | Do all C++ STLs produce the same random numbers (for the same seed)? | Do all C++ STLs produce the same random numbers (for the same seed)?
Does this hold for all platforms?
Is this specified somewhere?
| No, the standard does not require a specific implementation. Also, the only standard way to get random numbers are rand and srand, and they are not part of what originally was the STL, but rather functions taken over from C.
|
6,094,665 | 6,094,914 | How does _stat() under Windows exactly work | In my code I try to get the permissions for a file with _stat(). Currently I want to run it under Windows. The method is as follows:
bool CFile::Private::checkPermissions(std::string sFilename, CFile::EOpenmode iOpenmode)
{
std::string sErrMsg = "";
bool bResult = true;
struct _stat buf;
int iResult = 0;
// ... | _stat is a function that is not native to Windows. It's a helper function to ease the porting of UNIX programs to Windows. But the UNIX file model just doesn't apply to Windows, so not all fields make sense. For instance, Windows has real ACL's, not rwx bits. There's just no way to fit all the ACL information in st_mod... |
6,094,688 | 6,094,710 | C++ std::ifstream read to string delimiters | When using:
string s;
cin >> s;
Which characters can string contain and which characters will stop the reading to string.
| std::ctype_base::space is the delimiter for std::istream which makes it stop reading further character from the source.
std::ctype_base::space refers to whitespace and newline. That means, s can contain any character except whitespace and newline, when reading using cin>>s.
If you want to read complete line containing... |
6,094,732 | 6,094,772 | Is it allowed to name the parameter in postfix operator ++? | I am not using this code in any production environment, it is just for my understanding. Is this code valid (i.e. can I define my postfix operator like this?):
class A
{
public:
A& operator++(int n)
{
std::cout<<"N is:"<<n<<"\n";
return *this;
}
};
int main()
{
A a;
a++;
a.o... | This behavior is legal and well defined in 13.5.7:
Calling operator++ explicitly, as in
expressions like a.operator++(2), has
no special properties: The argument to
operator++ is 2.
|
6,094,881 | 6,095,038 | Adding a child widget to another widget in Qt | Although there are similar questions to mine posted on stackoverflow, none of their solutions actually respond to my problem. I have 2 independent widgets that I would like to combine (insert one widget into the other as a child): one is a UI created only with Qt Creator (drag-and-drop), and the other one an animation ... | Are you trying to change the central widget to the GL one? Because specifying the parent for the GL widget does not change them. If you'd like to change a widget to another (using the Designer), I recommend the "promote to" feature, with which you can change a widget's actual class in the designer. So add a QWidget on ... |
6,094,903 | 6,095,022 | execution order of loops in C | this is probably a very noob question but I was what the result of this would be:
int someVariable = 1;
while (callFunction(someVariable));
if (someVariable = 1) {
printf("a1");
} else {
printf("a2");
}
callFunction (int i) {
while (i< 100000000) {
i++;
}
return 0;
}
... | UPDATE
basically what I'm trying to figure out is what the different between a loop like while (callFunction(someVariable)); is vs while (callFunction(someVariable)){}
No practical difference. ; delimits an empty statement, { } is a scope without statements. Any compiler can be expected to produce identical code.
O... |
6,095,283 | 6,095,506 | template<class T> error | I have a: header.cpp, header.hpp and a test_header.cpp.
In header.hpp i've i have:
class MyClass
{
public;
MyClass();
std::string name;
//...code with other variables,methods;
class MySecondClass
{
public:
MySecondClass();
std::string surname;
//..code with other variables,metho... | When you instantiate a template it gets fully compiled, independently of what branches of the code will get eventually executed. In your particular code, even if the if statement will ensure that only the branch that has the valid assignment gets executed, both branches must be compiled, and one of them is not correct.... |
6,095,424 | 6,096,439 | How to configure makecall using GnuGK or OpenH323gk? | When i use GnuGK/Openh323gk from its telnet session how can i do makecall?
$ telnet localhost 7000
;
makecall alias1 alias2
$ ./gnugk -c config.ini -ttt
2011/05/23 11:10:48.957 1 MakeCall.cxx(55) MakeCallEndpoint: Error registering with gatekeeper at "<my public ip>"
2011/05/23 11:10:49.458 1 SoftPBX.c... | GnuGk uses an internal endpoint to initiate calls. This endpoint is treated exactly like any other external endpoint and needs to register with GnuGk.
Your quoted trace lines indicate that this registration fails. Make sure it is not blocked by any authorization rule and that it is using an alias that isn't already use... |
6,095,802 | 6,095,954 | Conversion operator vs constructor from given type. Which is preferable? | I'm defining iterator types for my container and of course I want iterator to be convertible to const_iterator. But I'm not sure which is better/preferable:
Conversion operator in iterator
class iterator
{
operator const_iterator();
};
or non-explicit constructor in const_iterator
class iterator
{
// implement... | You should write a casting operator only if it is possible to return the desired type without constructing a new object, or if its return is a simple data type. For example, if it were to return a const reference to a property within the class, then you should write it as a casting operator.
In all other cases, you sho... |
6,095,924 | 6,095,940 | When throwing different kinds of exceptions is useful? | Is it useful to throw different exceptions for instance std::runtime_error or std::invalid_argument in huge projects? Or is it better to throw in general std::exception with a good text parameter for what()? And when does it make sence to derive some sub classes from std::exception?
Rumo
| It always makes sense to use throw the most specific exception. As each exception should be derived from std::exception the code catching may decide at which level of granularity it wants to handle it (catch by reference! Item 13 in "More effective C++" from S. Meyers).
Using only std::exception with only some text a n... |
6,095,946 | 6,096,158 | How can I get the QObject::deleteLater() to zero the object? | Normally when I delete an object I set it to zero. This helps in that I code my routines to check the object is not zero then proceed.
However if I use the deleteLater() function I have lost control of it. I don't know if its a valid item or if I need to create a new one. The solution I found was just to keep track o... | There is nothing wrong if you call deleteLater() on your object and then set your pointer to nullptr. Qt framework will safely delete the object for you.
As an alternative you can also connect to destroyed signal to be notified of your object's destruction and set your pointer to nullptr in that slot.
|
6,096,131 | 6,100,058 | Should I be using scripting in this circumstance? | I am writing a game. it is in c++ an direct x and I think I am making my own engine as I am programming from winproc up.
I have made large amounts of progress such as sound, collision detection, AI specific to my game settings, dynamic graphics creation from tile sheets.
after doing some research on event programming ... | I don't think scripting is entirely necessary in your case. The bonus behind adding scripting support an engine have been listed up and down this page.
It gives you a simple langue to work with
It is more accessible to someone without training
It can be compiled on the fly, hot
swapped at runtime
For lots of high e... |
6,096,209 | 6,096,301 | Why VS2010 wizard add void type in ctor and dtor? | Any time I add class via VS Wizard, I have these implementations:
class CDxWindow
{
public:
CDxWindow(void);
~CDxWindow(void);
};
Usually I delete voids.
But maybe is there any reason of leaving them in the code?
Why does Microsoft added void there?
| In C a function declared with no parameters is assumed to take a single integer parameter. Declaring the function with a void parameter list tells the compiler not to assume this default.
This doesn't apply in C++, so the void is unnecessary.
|
6,096,279 | 6,097,013 | Keeping a valid vector::iterator after erase() | EDIT: I have had a lot of answers telling me that I should separate the deletion into another loop. Perhaps I did not make it clear enough, but I stated in my last paragraph that I'd like to find a solution OTHER than that. ie keeping the current code structure, but using some little-known C++fu to make it work.
Well, ... | You can't really iterate over and mutate a std::vector at the same time unless there's some communication between the iteration that the mutation.
I've seen other, non-standard, containers facilatate this through "smart" iterators that know when their value has been erased (and maybe auto-jump to the next item). It's q... |
6,096,384 | 12,325,848 | How to fix .pch file missing on build? | When I build my c++ solution in Visual Studio it complains that the xxxxx.pch file is missing. Is there a setting I am missing to get the pre-compiled headers back?
here is the exact error for completeness:
Error 1 fatal error C1083: Cannot open precompiled header file: 'Debug\xxxxx.pch': No such file or directory
... | NOTE: Later versions of the IDE may use "pch" rather than "stdafx" in the default names for related files. It may be necessary to substitute pch for stdafx in the instructions below. I apologize. It's not my fault.
Right-click on your project in the Solution Explorer.
Click Properties at the bottom of the drop-down... |
6,096,545 | 6,096,560 | Should C++ Iterators be able to decrement after passing the last item? | I have been modifying my containers to be STL compatible. I have modified my iterators to have the necessary functions. They are all random access iterators. Currently they work fine with all applicable STL algorithms. But one of my iterators will not be functional once it became invalid (out of bounds). Is it necessar... | For a random_access_iterator this is required. You will have to implement it. Specifically, according to 24.1.4.1 for a bidirectional_iterator (of which a random_access_iterator is a specialization) decrementing always has to be valid.
|
6,096,605 | 6,096,752 | Is handler set via XSetErrorHandler global or threadlocal? | If I set error handler using xlib function XSetErrorHandler will this handler work for the whole process or only for a thread where XSetErrorHandler was called?
| It should work for the whole process. It is not good for more than 1 thread to communicate with Xlib, because Xlib is not thread-safe.
|
6,096,860 | 6,096,975 | Storing and later calling member function of unknown class | I am trying to create a threadpool that can run functions from unknown classes. I do not wish to have to create non-members as a proxy.
I have managed to create a working pool & workerthread class and a task structure, all of these are templates.
// ThreadPool.h
/* Threadpool creates N WorkerThreads (each worker has a ... | Why use a T* at all, instead of just boost::function<void ()>?
That way you can use free functions as well as member functions, and you can simplify your code.
A task for a member on an instance of class X could be queued like this:
poll.add(boost::bind(&X::member, x_instance, other_arguments));
With no casts and no t... |
6,096,916 | 6,097,144 | Polymorphic class member variable | I have a class messenger which relies on a printer instance. printer is a polymorphic base class and the actual object is passed to the messenger in the constructor.
For a non-polymorphic object, I would just do the following:
class messenger {
public:
messenger(printer const& pp) : pp(pp) { }
void signal(std:... | There is no way to clone polymorphic object without a virtual clone method. So you can either:
pass and hold a reference and ensure the printer is not destroyed before the messenger in the code constructing messenger,
pass and hold a smart pointer and create the printer instance with new,
pass a reference and create p... |
6,096,942 | 6,097,030 | C++ pointer explanation | char* pstr[] = { "Robert Redford", // Initializing a pointer array
"Hopalong Cassidy",
"Lassie",
"Slim Pickens",
"Boris Karloff",
"Oliver Hardy"
};
If I write like below:
*pstr[0] = 'X';
The program can compile but cra... | The compiler should have warned you:
warning: deprecated conversion from string constant to 'char*''
What you're doing here is assigning some constant char arrays to a mutable char pointer, much like:
const char[] astring = "ababa";
char* mutablestring = astring; // shouldn't be possible
mutablestring[0] = 'o'; // cha... |
6,097,402 | 6,097,667 | How does the Linux C++ compiler (and linker) decide where to put typeinfo? | I have a class defined in one h file and implemented in a cpp that is part of one lib (we'll call it libdef).
I have two other libs that have cpp files that include this h file. One of them does dynamic_cast() to this class (we'll call it libdyn) and the other does new for this class (we'll call it libnew).
It seems th... | G++ probably defines the typeinfo for the class as a weak
symbol, in every object file that needs it. One of the object
files in libdef needs it, because it's part of the vtable
installed by the constructor. And one of the object files in
libdyn needs it, because of the dynamic_cast. If all
libnew does is a new, how... |
6,097,525 | 6,097,719 | Declare a forwarded class definition in a cpp file, what for? | What is the point of forwarding a class definition in a .cpp file?
Imagine that I have a private class inside another public class. I forward the definition of the private class, like class Private.
Is there any advantages to putting the declaration of my private class in a .cpp file or should I just stick with my forw... | Internal classes and structs are often best kept out of public headers to avoid dependencies and coupling.
If stuff is in the public header, it will mean that the public header will have to change if an implementation detail (in your private class/struct) changed. This is bad, because client programs will actually need... |
6,097,543 | 6,097,577 | Datatype size for number of bits | So I have the following function:
static int calcDTSize( int depth )
{
if ( depth <= 8 )
{
return 1;
}
if ( depth <= 16 )
{
return 2;
}
if ( depth <= 32 )
{
return 4;
}
if ( depth <= 64 )
{
return 8;
}
throw std::exception( "Invalid bi... | Divide by 8 and round up to closest power of 2.
Considering that the input is limited and the information is completely static, I would however probably put it in a look up array and do
if (depth <= 64)
return lut[depth];
throw std::exception( "Invalid bit count" );
If you don't want 64 entries in the lut, you c... |
6,097,766 | 6,097,816 | What is the scope of a unique_ptr returned from a function? | Would this work properly? (see example)
unique_ptr<A> source()
{
return unique_ptr<A>(new A);
}
void doSomething(A &a)
{
// ...
}
void test()
{
doSomething(*source().get()); // unsafe?
// When does the returned unique_ptr go out of scope?
}
| A unique_ptr returned from a function does not have scope, because scope only applies to names.
In your example, the lifetime of the temporary unique_ptr ends at the semicolon. (So yes, it would work properly.) In general, a temporary object is destroyed when the full-expression that lexically contains the rvalue whose... |
6,097,927 | 6,098,417 | Is there a way to implement analog of Python's 'separator'.join() in C++? | All I've found is boost::algorithm::string::join. However, it seems like overkill to use Boost only for join. So maybe there are some time-tested recipes?
UPDATE:
Sorry, the question caption were bad.
I'm looking for method to concatenate strings with separator, not just to concatenate one-by-one.
| Since you're looking for a recipe, go ahead and use the one from Boost. Once you get past all the genericity, it's not too complicated:
Allocate a place to store the result.
Add the first element of the sequence to the result.
While there are additional elements, append the separator and the next element to the result... |
6,098,011 | 6,098,036 | Infinite Loop until application gets signal | I have an application which starts 5 threads.
After starting those threads nothing happens in main().
main(){
`start thread 1..5
}
How do I loop infinitely in main() so my program will run continuously until it gets a signal.
I don't want to use
while(true)
because it will eat CPU cycle. (As I think )
Edit:... | the simplest would be:
while (true) sleep(1000);
and the best would be to join() all the five threads.
|
6,098,022 | 6,099,300 | Netbeans C/C++ linker problem | In Netbeans 6.9 on Linux and I was trying to to compile my C++ code.
It consists of two CPP files - main.cpp and later I added Tree.cpp and Tree.h to the project, but linker obviously ignores that fact and throws an "undefined reference error" in main.cpp when I use something from the Tree unit.
Do you have any clue ... | You need to add Tree.cpp to your project's build configuration; also you need to add the path to Tree.h in the "Search files" build section.
Right-click your project and select "properties", then go to the C++ compiler section. In "include directories" add the path to Tree.h. Now right click your project again and sele... |
6,098,024 | 6,098,066 | Is there an equivalent function in C/C++ to GNU-R which()? | Let me explain what the 'which' function does:
From GNU-R help:
which indices are TRUE?
Give the ‘TRUE’ indices of a logical object, allowing for array indices.
or showing some code: (GNU-R starts counting indices with 1)
> x <- c(1,2,3,1,3,5);
> which(x == 1);
[1] 1 4
> which(x == 3);
[1] 3 5
> ll <- c(TRUE,FALSE,TR... | You have to understand that R is vectorised, whereas C first and foremost works on individual atomistic data pieces: a single int, double, ...
With C++, you can look into STL algorithms with which you approach this.
Lastly, at the R and C++ intersection, our Rcpp package has some vectorized operations in C++ which mimi... |
6,098,228 | 6,098,444 | Memory overwritten after allocating array of structs | I'm trying to allocate memory for a array of structures, but after it is allocated a int that is passed in the function is set to '0'... The problem is gone when i increase the size of the array. Here is my code:
wchar_t* ISTFallSensor::JSON_EventLog(int nRecords) {
wchar_t* returnstring = new wchar_t[8192]; memset( re... | You have a memory overflow.
You adjust the variable nRecords so that it won't exceed 32, which is the maximum number of IST_LOG_RECORD that fit the eventlog array.
However you don't use it in the call to IST_GetMotionEventLogRecords. Instead you use drops, which equals to dropsD, which is not limited to 32.
Just use nR... |
6,098,288 | 6,098,324 | C++ how convert wide string to base64? | What is the best way to convert wide string to base64?
| Octet (8 bit symbols) -> Base64 (6 bit symbols) conversion works on bytes, not characters, so it works the same way independent of your string encoding.
To be clear: Base64 is not a character encoding. Sender and receiver need to agree on the character encoding (ASCII, UTF-8, UTF-16, UCS-2, etc) as well as the transp... |
6,098,351 | 7,026,641 | Access custom Performance counter of application via WMI | is it possible to access custom Performance counter of my application via WMI?
| i am able to find out the solution of accessing performance counter, i searched custom counter in window Shell and then utilized this Class to get performance counter in c# via WMI. Microsoft has provided an bridge between performance counter and WMI
|
6,098,607 | 6,099,676 | Partitioning big rectangle to small ones (2D Packing) | I need algorithm which splits big static sized rectangle to small ones. A perfect implementation for me look like this:
struct RECT
{
int l,t,r,b;
};
class BigRect
{
public:
// width and height of big rect
BigRect( unsigned width, unsigned height );
// returns -1 if rect cannot be allocated, otherwise returns... | What you're trying to do is online 2D bin packing. It's online because you don't have all your small pictures in hand before you attempt to pack them into the big picture. Furthermore some small pictures will be "deallocated" and their space will be freed up. On the other hand, an offline algorithm allows you to do thi... |
6,099,310 | 6,099,331 | Vector find with pointers of custom class | I am trying to understand operators you need to overload when working with custom classes in STL(SCL).
Can any one please tell me what is it I am doing wrong ?
class myClass
{
public:
int data;
myClass()
{
data =0;
cout<<"Default const "<<endl;
}
myClass(int x)
{
data = ... | Operator overloads must have at least one user-defined type. So you cannot overload operator== for two pointers, for instance.
Your myClass::operator==(const myClass *temp) is valid in the sense that it compiles, but makes very little semantic sense, and is not recommended (there are very few situations where you'd wa... |
6,099,411 | 6,099,464 | Advanced file type guesser | How does (exactly) utility like UNIX file command guess the file type?
Are there any source-codes?
| It uses various heuristics, mainly signatures which are described in a configuration file.
man -s 5 magic
will gives the file format.
|
6,099,415 | 6,099,664 | Any way to parse preprocessed source through external tool before it compiles? | I want the compiler to run preprocessing, generate all the .i files like it normally does if I just use the "generate preprocessed file" option, and then run an external tool, wait for it to complete, and then go on with the compilation of those .i files (which by now can be modified of course).
If that is not possible... | Let x.cpp be your file you want to preprocess.
Set the compiler option to generate preprocessed output for x.cpp, let it be x.i.
Add the x.i to the project and set the "custom build tool" in the properties. Set the "output files" to x.preprocessed.cpp.
Add x.preprocessed.cpp to the project.
See msdn for details.
|
6,099,699 | 6,099,760 | Wrap C block in function. Beginner question | I found the C snippet to get the current working directory from here. Essentially, the code is:
char directory[_MAX_PATH];
getcwd(directory, sizeof(directory))
I want to abstract that into another function, in a different file (so it can be swapped out on different platforms if necessary).
Currently, I have in the ext... | Theres a number of things that you are doing wrong here:
void getCurrentDirectory(char *directory)
{
getcwd(directory, sizeof(directory));
}
Mistake 1:
`sizeof(directory)`
gives you size of a pointer, to be precise, char *. Your intention is to pass size of the array, and not the pointer size.
Mistake 2:
... |
6,100,257 | 6,100,284 | C and C++ programming on MacBook | I recently bought a macbook and was wondering if I can write C and C++ programs on mac without having to install anything more. Say for Java, mac came with a preinstalled version.
Is it the same for C/C++. if yes, can you pls let me know hoe to compile and run a sample program or if not, can you please let me know wha... | You need to install the Mac Developer Tools either from your original Mac OS X disk or by downloading the latest version. This package includes the GCC compiler collection (supporting the C and C++ languages, amongst others).
|
6,100,486 | 6,100,695 | In C can we use operators such as :: or -> to access predefined methods in header files? | I will have two files. One header.h file and second one is main.c file.
Now, how to make a header.h file with methods written in C (such as print test etc), then in main.c file, how can I access them with operators such as :: or ->
@file: main.c
#include "header.h"; // sorry i made mistake before
int main()
{
... |
I would like to do it completely in C.
(from @Sonia's comment on @Als' answer)
Not completely possible. What you got there is C++ code, it can't be emulated in C in exactly that way.
In C, a struct can't have functions, only function pointer and also can't have any static members at all. So, no :: for you in that reg... |
6,100,598 | 6,194,655 | Why would fclose hang / deadlock? (Windows) | I have a directory change monitor process that reads updates from files within a set of directories. I have another process that performs small writes to a lot of files to those directories (test program). Figure about 100 directories with 10 files in each, and about 500 files being modified per second.
After running f... | I posted this as a comment, but I realize this could be an answer in its own right...
Based on the disassembly, my guess is you've overwritten some internal heap structure maintained by ntdll, and it is looping forever iterating through a linked list.
In particular at the start of the loop, the current list node seems ... |
6,100,614 | 6,101,154 | opengl oblique projection | I want to create a oblique (cavalier) projection in OpenGL. I know this operation is not default supported and instead I need a Shear Matrix and then make an Orthogonal Projection.
Can you tell me what are the OpenGl steps / functions that I have to make?
| I've not used a oblique/cavalier projection before, but the following should give you an idea of how to proceed:
Create a 4x4 shear matrix,
H(θ, Φ) = | 1, 0, -cot(θ), 0 |
| 0, 1, -cot(Φ), 0 |
| 0, 0, 1, 0 |
| 0, 0, 0, 1 |
θ being the shear in X, Φ being the shear in Y, and Z b... |
6,100,973 | 6,101,040 | Why I can't define operator= with non-reference return type? | Operator= in C++ inside a class is being declared like this:
MyType & operator=(const MyType & rhs);
It is reasoned like it is necessary for chaining. But, as operator= has right precedence, then returning the value should be enough.
| You certainly can declare operator = with a non-reference return type. In fact, on the very rare occasions I implement it, I normally make it return void as I don't think that multiple assignments, or testing the result of assignment, are one of C++'s greatest features.
|
6,101,084 | 6,101,094 | Division in C++ not working as expected | I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
What am I missing?
| You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:
double f = 3.0 / 5;
|
6,101,253 | 6,101,279 | Using atan2 to rotate an image when dragged with the mouse | I'm working on a skeletal animation editor. Right now, each bone has a start and end point, when the mouse is under a point,subsequent dragging will cause the bone to rotate based on where the mouse is. To do this, I call atan2 and transform the mouse coordinates to local space where the local is where the mouse was pr... | atan2 has order of arguments y, x. Thus you need
atan2((float)event.mouse.y - startY, (float)event.mouse.x - startX)
|
6,101,273 | 54,696,182 | qmake : Build library without the symlinks and 'lib' prefix | I require a very simple mechanism in my application, where my project is built as a shared library '.so' or '.dll', but what I want is:
ExampleAppOne.so
I get:
libExampleAppOne.so -> libExampleAppOne.so.1.0.0
libExampleAppOne.so.1 -> libExampleAppOne.so.1.0.0
libExampleAppOne.so.1.0 -> libExampleAppOne.so.1.0.0
I don... | add the following to you .pro file
# disables the lib prefix
CONFIG += no_plugin_name_prefix
# disable symlinks & versioning
CONFIG += plugin
|
6,101,297 | 6,101,408 | Overflow or Memory error c++ | This could be considered a homework question.
This problem is wel known: "you have a triangle of numbers and you have to find the greatest sum"
well no problem, I've made a solution in python some time ago, works flawless.
But now in c++, the solution is 75256, my answer is 9729.
So the problem is that the type short... | You get a stack overflow instead of a numeric overflow!
Move the array to static memory outside of main, so it doesn't use the stack.
|
6,101,304 | 6,101,348 | Inherit Shell Class for Container Use | Would it be considered good practice to have a group of related classes all inherit from the same (essentially empty) class, so the client can organize all of the instances into one container?
For example:
class One : public Foo { }
class Two : public Foo { }
class Three : public Foo { }
So later I can do std::vector<... | It's the standard practice for implementing polymorphic types. However, it is unusual for the base class to be empty. Apart from anything else, it MUST implement a virtual destructor, and normally there are other (probably pure) virtual functions that must be provided in order to do anything useful.
|
6,101,728 | 6,102,706 | Behavior of decltype | Say I have an object of some of stl container classes obj. I can define other object of same type this way:
decltype(obj) obj2;
But I can't declare iterator for the container this way:
decltype(obj)::iterator it = obj.begin();
Why? Am I doing something wrong?
| Your code is well-formed according to the final C++0x draft (FDIS). This was a late change that's not yet been implemented by the Visual Studio compiler.
In the meantime, a workaround is to use a typedef:
typedef decltype(obj) obj_type;
obj_type::iterator it = obj.begin();
EDIT: The relevant chapter and verse is 5.1.1... |
6,101,963 | 6,102,004 | Pushing element into vector | template <class T>
class A{
//...
};
class B{
//...
};
class C{
protected:
vector< A<B> > vec;
public:
void f(B *ptr);
};
C::f(B *ptr){
vec.push_back(ptr); // gives error
}
The line that I'm trying add element into the vector gives compiler error. How can i fix this one?
| It expects an A, you give it a B
A<B> a;
a.initsomehowwith(*ptr);
vec.push_back(a);
|
6,102,040 | 6,108,843 | How to implement a QThread that runs forever{} with a QWaitCondition but still needs to catch another Slot while doing that | I implemented a class that can write data to a serial port via a QQueue and read from it by a slot. I use QAsyncSerial for this which in turn uses boost::asio with a callback.
The class is moved to a thread and its start() method is executed when the QThread emits "started()"
The problem is that I dequeue the QQueue in... | 1) Create slot in your thread, for example onMessageReady(), which will do the job.
2) Create a signal indicates that new message ready, and emit it each time you creating a new message.
3) Connect them using QueuedConnection and call your thread's exec function.
This won't block your thread, as WaitforObject does, a... |
6,102,066 | 6,102,096 | Overloading post increment operator results in argument valued at 0 |
Possible Duplicate:
Is it allowed to name the parameter in postfix operator ++?
I created an object to hold a list of objects that maintains the current position internally, so I thought this was a great place to overload the pre and post increment operators, which effectively increment this internal position with b... | You should just ignore the parameter.
|
6,102,097 | 6,102,181 | C++, std::copy and templates | I am doing experiments with templates and STL. This is my testing code...
template <typename Item>
struct TList
{
typedef std::vector <Item> Type;
};
template <typename Item>
class Cont
{
private:
typename TList <Item>::Type elements;
public:
void push_back ( const Item & p ) {elements.push_back ( p );}
... | The expression:
elements.size() + last - first
is evaluated as:
(elements.size() + last) - first
The result of the first addition will be an iterator that exceeds the vector's bounds, which triggers the exception (in debug mode). You could try this:
elements.size() + (last - first)
Or the more STL-like approach:
el... |
6,102,510 | 6,103,117 | Call a function from C# .exe with unmanaged C++ .dll | So, I have an executable file that was made with C#, I don't have its source code but I have disassembled it with IDA, and it gave me a lot of object oriented assembly.
I've made an .exe file that injects a .dll into another .exe, and I've injected this new C++ DLL into the C# .exe, with no problems, the DLLMain is cal... | You are trying to do something tricky and I'm not perfectly clear on what it is. From your description you have at least four things:
Managed EXE
Managed DLL
Unmanaged EXE
Unmanaged DLL
some of which you have control over (i.e. source code for), and some of which don't.
You want to use a process you call "injecting"... |
6,102,658 | 6,102,728 | What is wrong with my int to hex function? | why is this code not giving me correct values for large numbers? does it have something to do with me using numbers larger than 32 bits? if so, how do i get my function to accept values of any bit size? would i just overload the function? that seems a bit of a waste of space
std::string makehex(unsigned int value, unsi... | template<typename T>
std::string makehex(T value, const unsigned size = 2 * sizeof(T))
{
std::string out(size, '0');
while (value && size){
out[--size] = "0123456789abcdef"[value & 0x0f];
value >>= 4;
}
return out;
}
Demo: http://ideone.com/v04Vo
|
6,102,698 | 6,102,758 | How to convert pugi::char_t* to string | Hi
I'm using pugixml to process xml documents. I iterate through nodes using this construction
pugi::xml_node tools = doc.child("settings");
//[code_traverse_iter
for (pugi::xml_node_iterator it = tools.begin(); it != tools.end(); ++it)
{
//std::cout << "Tool:";
cout <<it->name();
}
... | According to the manual, pugi::char_t is either char or wchar_t, depending on your library configuration. This is so that you can switch between single bytes (ASCII or UTF-8) and double bytes (usually UTF-16/32).
This means you don't need to change it to anything. However, if you're using the wchar_t* variant, you will... |
6,102,789 | 6,102,932 | Dynamic structures in C++ | I am running a simulation in which I have objects of a class which use different models. These models are randomly selected for some objects of the class and specifically decided for some objects too. These objects communicate with each other for which I am using structures (aka struct) in C++ which has some
standard... | All instances of a structure or class have the same structure. Luckily, there are some tricks that can be used to 'simulate' what you try to do.
The first trick (which can also be used in C), is to use a union, e.g.:
struct MyStruct
{
int field1;
char field2;
int type;
union
{
int field3a;
... |
6,102,915 | 6,160,956 | passing pyqt object to swig exported c++ code | anyone knows if there exists a method for passing pyQt objects to c++ code?
I'll explain better; say i have this c++ code
void QtGuiPDLVisitor::set_layout(QLayout* _layout){
layout = _layout;
}
where QtGuiPDLVisitor is a c++ class exported in python using SWIG, so in python i want to do something like t... | Ok i actually find a way to do that. I used
visitor.set_layout_address(sip.unwrapinstance(layout))
from python, and than in c++
void QtGuiPDLVisitor::set_layout_address(long _layout_address){
layout = reinterpret_cast<QLayout*>(_layout_address);
}
and worked!
here sip doc for more about sip.unwrapinstance()
|
6,102,948 | 6,103,040 | Why does modulus division (%) only work with integers? | I recently ran into an issue that could easily be solved using modulus division, but the input was a float:
Given a periodic function (e.g. sin) and a computer function that can only compute it within the period range (e.g. [-π, π]), make a function that can handle any input.
The "obvious" solution is something like:... | Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real op... |
6,102,981 | 6,103,069 | how to reference a .net coded library in a MFC dialog-based project | I want to use Html Agility Pack which is in a .NET code library. Anyone knows how to import/reference the dll file into my vc++ MFC project?
I tried right clicking on my project, choose "References...", then I click the "Add new Reference" button, and I get an empty dialog box with a single tab "Projects" which contain... | You can't call .Net code directly from unmanaged native code. You have several options if you want to do this indirectly though:
Convert your MFC project to be mixed-mode
Add an intermediate façade assembly
Expose htmlagilitypack via COM (if you have access) and call it via COM interop
You need to provide more contex... |
6,103,036 | 6,103,095 | How to change a text file's name in C++? | I would like to change a txt file's name, but I can not find how to do this.
For example, I want to rename foo.txt to boo.txt in my C++ program.
| #include <stdio.h> (or <cstdio>) and use rename (or std::rename):
rename("oldname.txt", "newname.txt");
Contrary to popular belief, this is included in the standard library, and is portable up to a point -- though of course the allowable contents of the strings will vary with the target system.
|
6,103,153 | 6,103,631 | Colouring Textures Without Vertex Buffer Diffuse | I'm currently working on a two-dimensional Direct3D application, and I'm trying to figure out how to properly add a hue and alpha effect to different textures.
I had it working previously, but the way I was doing it was by:
Locking the vertex buffer.
Changing the diffuse colour on each of the vertices.
Unlocking the v... | I don't think so - as per MSDN docs on D3D lighting:
Note that although Direct3D uses RGBA
values for lights, the alpha color
component is not used.
Writing a shader to adjust the color for each vertex sounds like what you're after, which runs in the GPU and has little performance overhead compared to modifying e... |
6,103,234 | 6,103,399 | How to compile fltk file with other files? | I have a gui window using fltk class that works fine when I compile it by itself. For doing that, I use -
fltk-config --compile guiwindow.cpp
But I really want to use this in my project. So how can I do something like -
g++ -o go file1.cpp file2.cpp etc guiwindow.cpp
so that I can use this guiwindow class with my othe... | fltk is a not great when it comes to linking it with other stuff. It brings its own c++ stdlib and other libraries. just avoid it.
Other than that you should give more information on what command you used for compiling and what was the compiler's output. In theory it is possible to build stuff with fltk using plain g++... |
6,103,252 | 7,100,334 | Boost::GIL bits8* to gray8_ptr_t without reinterpret_cast? | Trying to work by the design guidelines for GIL, I use bits__ for my channel data types. I often have external data I'm wrapping into GIL image views. However, even using the bits__ types for data pointers, I have to add in a reinterpret_cast before I can create my image views. Take the following code
int width = 3;
in... | template<class Dest, class Src>
Dest gil_safe_ptr_cast(Src src)
{
// this cast is unsafe, use reinterpret_cast
BOOST_STATIC_ASSERT(false);
}
template<> boost::gil::gray8_ptr_t gil_safe_ptr_cast(boost::gil::bits8* pBits8)
{
return reinterpret_cast<boost::gil::gray8_ptr_t>(pBits8);
}
boost::gil::bits8* pBits... |
6,103,314 | 6,104,239 | Visual Studio debug iterators | What is the relation between _SECURE_SCL and _HAS_ITERATOR_DEBUGGING.
Is it possible to turn on/off range checking and preserve binary compatibility?
Any difference between 2008 and 2010 versions?
| Stephan Lavavej has provided some detail on this _SECURE_SCL and _HAS_ITERATOR_DEBUGGING:
From http://blogs.msdn.com/b/vcblog/archive/2007/08/10/the-future-of-the-c-language.aspx
Iterator debugging, enabled by
_HAS_ITERATOR_DEBUGGING, performs powerful correctness verification.
Iterator checking, enabled by
_SE... |
6,103,627 | 6,143,995 | Making a C function pointer work with C-style stack based calling mechanics in C++ | I want to call a pure C style function from a dll in my C++ program. I tried casting my function pointer using reinterpret_cast to __cdecl and still the calling convention of _stdcall seems to be preserved. I am new to Windows C++ programming.
Edit Code from comment
reinterpret_cast< Error ( __cdecl*)(int,int)> (Get... | This helped me out!
http://www.codeguru.com/forum/archive/index.php/t-70673.html
|
6,103,750 | 6,104,471 | Does the VS2010 Parallel Patterns Library (PPL) parallel_for_each algorithm support std::set<>? | When trying the following code:
Concurrency::concurrent_vector<int> results_temp;
std::set<int > temp;
Concurrency::parallel_for_each(temp.begin(), temp.end(),[&](int p) {
results_temp.push_back(p);
});
I get the following compile time error:
1>C:\Program Files (x86)\M... | The example code compiled without error for me.
I added these includes:
#include <ppl.h>
#include <concurrent_vector.h>
Do you have SP1 installed?
|
6,103,761 | 6,103,785 | Is It Possible to Put non (Static Const Integral) Types in C++ Header.h File | I have a class in MyClass.h file:
// MyClass.h
#ifndef __MY_CLASS_H__
#define __MY_CLASS_H__
#include <string>
class MyClass
{
static const std::string MyStaticConstString; // I cannot initialize it here, because it's not an integral type.
};
// OK, let's define/initialize it out side of the class declaration
//... | No, for the same reason you can't put global variables in headers, const-qualified or not. Document your constant instead (if it's a constant, then why should users care about its value anyway?).
Also, don't prepend your identifiers with underscores (__MY_CLASS_H__), they're reserved for implementation stuff.
|
6,103,847 | 6,103,924 | Checking A PyObjects C Type | I am using Python 3.2 and C++.
I need to extract what kind of C type is currently being stored in a PyObject.
I have checked over the documentation and googled it as well and no one else seems to have needed to do this.
So I have a PyObject and am attempting to extract the C Value. I have the list of functions need to ... | Python objects don't have a C type, they have a Python type. For example, an integer can be an C long or a long integer. You can check for the type with PyInt_Check(obj), PyList_Check(obj), etc. If that returns true then you know you have an object of that type.
Note that PyLong_FromLong and such go the other way. They... |
6,103,927 | 6,104,149 | Count the number of times each word occurs in a file | Hi I am writing a program that counts the number of times each word occurs in a file. Then it prints a list of words with counts between 800 and 1000, sorted in the order of count. I am stuck on keeping a counter to see if the first word matches the next until a new word appears. In the main I am trying to open the fil... | One solution could be this : define letter_only locale so as to ignore punctuations coming from the stream, and to read only valid "english" letters from the input stream. That way, the stream will treat the words "ways", "ways." and "ways!" as just the same word "ways", because the stream will ignore punctuations like... |
6,103,990 | 6,104,043 | How to get the terminating NUL character \x00 into a string? | How would i get a string with the null character \x00 since \x00 is also the terminating character?
I really do need it for part of my program.
The string I need is "\x00\x00\x00\x00". Is there some special syntax for it? What is it?
| std::string str("\0\0\0\0", 4);
This constructor tells string to use the 1st 4 characters of the char*, without interpreting any \0 characters as null.
|
6,104,821 | 6,104,838 | C++ equivalent of sscanf? | I've been using sscanf and I think I've gotten too comfortable with it. Apparently it is deprecated too and I should use sscanf_s, which is not standard as far as I know. So I was wondering if the STL has an idiomatic C++ replacement do the same thing?
Thanks
I do:
sscanf(it->second->c_str(),"%d %f %f %f %f %f... | The formatting isn't as easy but check out stringstream. See also istringstream and ostringstream for input and output buffers formatting.
|
6,104,929 | 6,105,100 | C++ Array of objects at two times | I have a class Agent, which contains a pointer (array) of class ValueContainer.
Now what I have to do is to create an array of Agent first, and then initialize each one of them independently. Also, Agent has no empty constructor due to its nature.
It's more or less like this:
Agent agent[n];
for (int i...)
{
load v... | Saying that you want to create an array of Agent without initializing those agents is an anachronism. Initialization takes place during construction. You can't create a thing without doing some kind of initialization.
In almost every case, the "right" thing to do in C++ is to use a vector or some other Standard conta... |
6,105,002 | 6,105,460 | WriteFile on a named pipe sometimes returns ERROR_NO_DATA | I've got a C++ program that is creating a named pipe to write data to. Some customers have reported a situation where the client connects to the named pipe but the server end fails to write the data (with ERROR_NO_DATA).
This error code isn't really explained in any MSDN page that I could find; does anyone have any id... | Looking at WinError.h, which is where this and other error codes are defined:
//
// MessageId: ERROR_NO_DATA
//
// MessageText:
//
// The pipe is being closed.
//
#define ERROR_NO_DATA 232L
Sounds like the client has already closed their end of the pipe - perhaps the client code thinks it has alread... |
6,105,119 | 6,105,138 | doubt resolving namespaces in enums? | from the below question i sort of get how enums and namespace scoping works
Scope resolution operator on enums a compiler-specific extension?
However with regard to test code below i'm confused as to why in the below code snippet:
1) i can refer to return type in function signature as test_enum::foo_enum
2) however "... | The reason using namespace test_enum::foo_enum; is not allowed is because foo_enum is not a namespace, it is an enum. What works is using test_enum::foo_enum;
I believe what you are trying to do is something like this:
namespace foo_enum {
enum foo_enum_t {
INVALID,
VALID,
};
}
using foo_enum::... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.