question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,575,095 | 5,575,119 | c++ error: expected unqualified-id before '[' token | I'm trying to make a simple game in c++, I'm almost complete but I keep running into this error. I'm sure these are syntax errors, I'm just not sure on how to fix them.
Board::Board()
{
side = 6;
Piece[][] spaces = new Piece[6][6];
for (int row = 00; row < side; ++row)
{
for (int column = 0; col... | This is illegal:
Piece[][]
C++ does not store a 2-dimensional array as an array of pointers, but rather a flat series of subarrays. Therefore all but the last bound must be specified.
Also, new is unnecessary and undesirable if the array size is fixed. Simply use this.
Piece spaces[6][6]; // that's all!
Finally, the ... |
5,575,477 | 5,577,670 | Is there any way to know how much mem is used by a thread? | I am maintaining a program, and it use 600+MB mem when starting up, doing nothing!
I wanna know how much mem used by every thread, can gdb do this work?
| valgrind --tool=massif is the right solution. It will give you all information which thread uses how much memory at what point of time.
|
5,575,521 | 5,575,656 | How do i overload new/stl to make unknown objects faster? | In my question profiling: deque is 23% of my runtime i have a problem with 'new' being a large % of my runtime. The problems are
I have to use the new keyword a lot and on many different classes/structs (i have >200 of them and its by design). I use lots of stl objects, iterators and strings. I use strdup and other all... | Look for opportunities to avoid the allocation/freeing, either by adding your own management layer to recycle memory and objects that have already been allocated, or modifying their allocators. There are plenty of articles on STL Allocators:
http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079
http://bmagic.s... |
5,575,538 | 5,575,548 | "error: conversion from 'int' to non-scalar type 'COORD' requested" | I get this solitary error while trying to compile the following code in code::blocks.
The error is occurring 8 lines down.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = (40, 3);
SetConsoleCursorPosition(screen, pos);
cout << "O" ... | COORD pos = (40, 3);
This should be:
COORD pos = {40, 3};
Note the use of {} instead of ().
|
5,575,625 | 5,575,764 | How do I convert this to c# (Marshalling) | I have these declarations (DLL) and tried to convert it in C# so i can call the functions from the DLL.
Same for struct1 to struct3
typedef struct1
{
int num;
char chars[25];
short shrt;
union
{
struct4 objstruct4;
}
}
typedef struct
{
Long Length; ... | There's no obvious reason why you chose Pack=1, the default for most C compilers is 8, just like .NET. MsgData at offset 6 is iffy. Use sizeof and offsetof() in a test C program to find out where everything is located. Compare with Marshal.SizeOf and OffsetOf() in a test C# program. This isn't going to work until t... |
5,575,983 | 5,576,299 | Qt 4.0 Signals and Slots with minimal OOP | I'm relatively new to Qt; I'm writing a small program and I don't want to get into making my own classes for each widget and such. So far I haven't had many difficulties, but I'm slightly confused about signals and slots. I want to make a signal that triggers when a user types into a text box (QLineEdit) and presses en... | Sadly, I don't think there is a way to achieve this without inheritance - if you want the text to go with the signal or some custom handling to be done in the slot that is called.
If not, you can just use the "returnPressed" signal emitted from the QLineEdit and some pre-existing slot I couldn't possibly know.
Here's m... |
5,576,334 | 5,576,388 | Learning Pointers By Example | Hi I came across this bit of C++ code and am trying to learn how pointers operate.
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is ... |
what exactly happens in memory when int *mypointer; is declared?
Sufficient memory is allocated from the stack to store a memory address. This will be 32 or 64 bits, depending on your OS.
what does mypointer represent?
mypointer is a variable on the stack that contains a memory address.
what does *mypointer repre... |
5,576,364 | 5,576,506 | what things are costly to implement in PHP on a large social networking site? | It is very common to hear that C++ or Java should be used on the "back end" to improve performance. I believe sites like Facebook have C++ based "services" for critical performance.
For example: Is it at any time more cost effective to replace SQL "SELECT * FROM ...." type commands passed via PHP with something else be... | I am not web developer, and I am also not PHP programmer and this question is more discussion so let me try.
On this super big type of sites you need smart and efficient algorithms, not efficient languages. Lot of Google code running their website is written in Python, which have same speed compared whit PHP.
I think ... |
5,576,387 | 5,608,198 | Redefine malloc/free with static linking has multiple definition error | Recently, my company wants to update the compiler from gcc-3.4 to gcc-4.5. However, our customer's machine may not have the up-to-date libstdc++.so, so we want to static link our binary.
Our program needs customized malloc()/free() for very high performance requirement.
I modified the makefile, added a -static while li... | If your primary concern is the availability of libstdc++.so in the target system, then why not simply distribute the newer version of that together with your application?
I think that static linking in any case is not a good solution, compiling the project becomes much harder, and if you are using shared objects yourse... |
5,576,517 | 5,576,553 | How C++ is this code working? | I have a strange bit of code. I must have been hitting my keyboard with my eyes closed because this type of thing is really dumb, but weird thing is, I caught it after the program ran successfully.
struct Number{
private:
unsigned long longNumber;
public:
Number(unsigned long n)
{
longNumber = n;
}
... | Since Number has a constructor which accepts unsigned long the compiler is creating a temporary object of type Number from the return value of number.getReverse() and passing it to the add function. If you don't want such implicit conversion to occur, you need to declare the Number constructor as explicit.
|
5,576,724 | 5,577,056 | control after unexpected shutdown | I'm working on a program that sends a command to the server and creates a file on the server to let it know its connected for example, while the program is running it creates a file say "here" everytime it loops, a php site then checks the server for that file, if the file is there it knows the program is connected. ... | You're probably better off creating something other than a file for this purpose. Since files are generally used as a more permanent storage solution, it's not what you want.
What I would recommend is something like a mutex or some other kind of named, OS implemented, cross-process token or synchronisation primitive. S... |
5,576,731 | 5,577,194 | How to copy objects in the vector list to another vector list? | I like to copy the object of first vector to second vector but when i delete the second vector , the first vector content should not changed.
How can i do this?
CODE:
typedef vector<CLog*> CLogData;
CLogData CMultiThreadedDlg::CopyLogData()
{
CLogData logdata;
for(size_t i = 0; i < m_pThreadInfo->GetLog().size()-1; ++... | Oh, man. There are some serious problems in that code of yours.
First, you have
class CLog
{
char* m_threadname;
public:
CLog()
{
m_threadname = new char[20];
}
~CLog()
{
delete[ ] m_threadname;
}
};
It's C++ and the year is 2011, please don't do that. And if you do that,... |
5,576,922 | 5,577,290 | Should I use shared_ptr or unique_ptr | I've been making some objects using the pimpl idiom, but I'm not sure whether to use std::shared_ptr or std::unique_ptr.
I understand that std::unique_ptr is more efficient, but this isn't so much of an issue for me, as these objects are relatively heavyweight anyway so the cost of std::shared_ptr over std::unique_ptr... |
I've been making some objects using the pimpl idiom, but I'm not sure whether to used shared_ptr or unique_ptr.
Definitely unique_ptr or scoped_ptr.
Pimpl is not a pattern, but an idiom, which deals with compile-time dependency and binary compatibility. It should not affect the semantics of the objects, especially wi... |
5,576,944 | 7,394,504 | Take OpenCV window and make full screen | I am currently making an OpenCV project in C++ where I look for motion with a kinect and use that to cue a slideshow (sans recognition). Currently, I am displaying the slideshow using OpenCV (as I've only had about a week to whip this up). It looks good and its quick. The only problem is that this is going to be on ... | I am using OpenCV 2.1 on Ubuntu 11.04. On my system CV_WINDOW_FULLSCREEN and CV_WINDOW_AUTOSIZE flags both map to 1
And both flags behave exactly the same. They give you a fixed size window, which would be expected for AUTOSIZE flag but not the FULLSCREEN. I think these two flags are meant for different functions altho... |
5,577,026 | 5,577,123 | How to cast dynamic array to static array in c++? | In c++ how do you cast a dynamic array to static?
Say
I have
int ** da;
da = new int*[9];
for (int i=0; i<9; i++) da[i] = new int[9];
and my function argument is of type
int[9][9], how do I cast da so my function can use it?
| An int[9][9] is 81 integers consecutive in memory, taking 81*sizeof(int) bytes. An int *[9] is a sequence of 9 pointers to integer, taking 9*sizeof(int *) bytes. Each of these are setup to point to 9 distinct sequences of 9 ints.
You cannot use one in place of the other - no casting will change that these two are laid ... |
5,577,425 | 5,577,763 | Using regular expressions in python to determine C++ functions and their parameters | So I'm doing something wrong in this python script, but it's becoming convoluted and I'm losing sight of what I'm doing wrong.
I want a script to go through a file, find all the function definitions, and then pull out the name, return type, and parameters of the function, and output a "doxygen" style comment like this:... | The grammar of C++ is far too complex to be handled by simple
regular expressions. You'll need at least a minimal parser.
I've found that for restricted cases, where I'm not concerned
with C++ in general, but only my own style, I can often get away
with a flex based tokenizer and a simple state machine. This
will fai... |
5,577,439 | 5,578,726 | How can I determine if the OpenGL window is the active window? | How can I determine if the OpenGL window is the active window?
| OpenGL only deals with drawing stuff. Terms like "Window" "Active" or "Focused" are completely outside the scope of OpenGL. You need to consult your windowing system's functions for this (Win32, X11, or functions provided by a cross-plattform toolkit)
|
5,577,483 | 8,588,854 | Using Tcp, why do large blocks of data get transmitted with a lower bandwidth then small blocks of data? | Using 2 PC's with Windows XP, 64kB Tcp Window size, connected with a crossover cable
Using Qt 4.5.3, QTcpServer and QTcpSocket
Sending 2000 messages of 40kB takes 2 seconds (40MB/s)
Sending 1 message of 80MB takes 80 seconds (1MB/s)
Anyone has an explanation for this? I would expect the larger message to go faster, sin... | Bug in Qt 4.5.3
..................................
|
5,577,559 | 5,577,715 | How to keep a C++ object inside Java code? Possible? | First I've got a legacy C++ library, and I'm migrating my app to Android with new UI.
During runtime, there might be multiple C++ objects created and destroyed dynamically. I built a set of JNI native methods to call into library to get that. But where should I keep those C++ objects? I have to keep track of them and f... | Yes, it's possible. You can store a pointer to your C++ object in a simple java int. That's exactly how SWIG does that.
|
5,577,663 | 5,577,704 | About base class in derived class initialization | guys. I see several cases like:
class Derived:public Base{
public:
Derived(...):Base(...){}
}
Is what situation or is there any principle that we should explicitly initialize the Base in the Derived ctor initialization list? Thanks
| In case if we need to pass the arguments of derived constructor to the base constructor, it can be used.
class foo
{
public:
foo() {}
foo( int num ) {}
};
class bar : public foo
{
public:
bar(int barNum): foo(barNum) {}
};
|
5,577,859 | 6,203,181 | How can I keep track of ActiveX controls created by a process? | I'd like to keep track of the ActiveX controls created by some process. To simplify the problem, I'd first like to monitor the current process only. I want to do this so that I can check whether any ActiveX control supports IOleWindow and if so, whether a given HWND belongs to that ActiveX control (so that I can map HW... | I ended up hooking CoCreateInstance and CoGetClassObject to track all COM objects being created.
|
5,577,874 | 5,577,946 | Is there a stl or boost function to determine if a string is numeric? | I'm very new to C++, boost etc.
I would like to know if there is already a function in boost or STL I can use to determine if a string is numeric.
Numeric strings may look like:
100
or
100.52
I know there are tons of examples how to write such a function but I would like to know if there is already a function I can use... | No, there's not a ready-made way to do this directly.
You could use boost::lexical_cast<double>(your_string) or std::stod(your_string) and if it throws an exception then your string is not a double.
C++11:
bool is_a_number = false;
try
{
std::stod(your_string);
is_a_number = true;
}
... |
5,577,950 | 5,578,705 | Keyword "typename" in Templates | Following is the code and quote is from the C++ Templates by Addison Wesley:
template <typename T>
class MyClass {
typename T::SubType * ptr;
…
};
Without typename, SubType would be considered a static member. Thus, it would be a concrete variable or object. As a result, the expression T::SubType ... | Here's another way to get the same error from g++:
class Foo { static const int x = 0;};
template <typename T> class MyClass
{
Foo::x * ptr;
};
and another:
class Foo { static const int x = 0;};
class MyClass
{
Foo::x * ptr;
};
But you get a different error for this:
// class Foo { static const int x = 0;... |
5,578,008 | 5,578,080 | Visual C++: possible to limit heap size? | I have a problem with an application I'm debugging. Steady state memory usage is a few hundred megabytes. Occasionally (after several hours) it gets into a state where its memory usage soars to many gigabytes. I would like to be able to stop the program as soon as memory usage this happens.
Where control passes thro... | You can set memory allocation and deallocation hooks, using _CrtSetAllocHook.
|
5,578,487 | 5,580,487 | pimpl: Avoiding pointer to pointer with pimpl | In this question I asked "pimpl: shared_ptr or unique_ptr" I've been convinced that the proper usage of the pimpl idiom is to use a unique_ptr, not a shared_ptr. It should act to the user as if there is no pointer at all, whereas quite clearly the shared_ptr introduces aliasing upon copying, which definitely acts like ... | There are a number of possible approaches depending on your constraints.
1. Create your own shared_my_pimpl class
Create a class shared_my_pimpl which has the same interface as my_pimpl but internally uses a shared_ptr instead of a unique_ptr. Now create a class shared_ptr_my_pimpl which holds a shared_my_pimpl and has... |
5,578,559 | 5,578,644 | Cross platform multithreading in C++? | Basically, the title explains it all; I'm looking to make a game in C++ and I want to use multithreading for stuff like the physics engine and keeping the animation smooth on the loading screen. I've seen a few multithreading libraries, but I'm wondering which is best for my application, which will work well on Windows... | If you can use c++0x threads, then use that.
If not, boost::thread is the best free multi-platform library.
|
5,578,607 | 5,579,049 | Typelists visitor pattern example | I'm interested in Typelists .
At this URLhttp://drdobbs.com/184403813 there is a good example of how using Typelists for creating a visitor pattern.
I have two questions about this example. My two questions are at the end of this topic.
Consider the code below :
void SomeOperation(DocumentItem* p)
{
if (TextArea* p... | What if you have 50 DocElement types? With the first example you need 50 if statements, with the second, you just need to have a typelist of 50 elements.
You can also think about what happens when you add another DocElement. In the first example, you need to go and change the if-else statements. With type-lists you can... |
5,578,619 | 5,579,127 | Executing UNIX commands using fork,execvp | I am trying to create a program that takes in an input file containing a list of UNIX commands and executes these commands in a particular order.
I am learning fork(), wait(), execvp() system calls and had some questions about the wait and forking pattern.
This is the structure I am using for executing processes. Proce... | The structure you propose does not allow for sequential execution, as you do not call wait until all nodes have been executed. You can use one of the variants of wait() which allow the WNOHANG option to check for termination of a child without blocking.
When you call fork() you need to check for -1 which indicates an e... |
5,578,631 | 5,578,817 | How do you stop reading integer from text file when encounter negative integer? | Im trying to write a simple code in c++ to read in integer from a text file, the code should stop reading when it encounter a negative integer. The txt file contains 1 positive integer on each line, and the last line is a negative integer.
My code right now using eof, and it reads in negative integer also, which I don... | hmm..
int data = 0;
while(inFile >> data && data >= 0)
{
// do stuff with data.
}
|
5,578,682 | 5,579,527 | Casting char * as int gives strange error | I've run into a slightly strange problem - I have a char array that I want to output as hex. I don't mind casting as int, but when I do, a lot of f's are added in front of some of the numbers. I have this code do my output for me:
for (int i = 0; i<(bmp.BytesPerRow*bmp.Height);i++) // once per color per pixel
{
if(... | The problem is that plain char's on your machine are signed. (If
you're not too concerned about portability, both g++ and VC++
have options to make plain char unsigned.) You need to first
cast the char to unsigned char, then cast the unsigned char to
int. Or, if you can change the data structures you're
outputting,... |
5,578,695 | 5,578,784 | Is there a way to safely delete QList of non-unique pointers to MyObject? | I know this kind of question has been asked to death but I would like to know if there is anyway to do what I stated in the question without using Boost library pointers etc. Basically I have the following piece of cleanup code that deletes objects pointed to by the pointers in the double-dimension QList ( QList< QList... | The easiest way is to create a temporary std::set<MyObject*>. Iterate over m_Data, and instead of deleting the pointers straight away, add them to the set. Next, delete all pointers in the set. There are no duplicates in a std::set.
You can safely delete a NULL pointer. No need to check that
|
5,578,842 | 6,303,645 | How to pass COM array to managed code? | I have a .Net application (VB in particular, although I would this to be as language agnostic as possible) that uses a COM object (made in C++).
I need to implement a event in COM that passes a char array from C++ to .Net. I guess I need to convert the array to a managed array;
How can I do this?
| This is what I was looking for:
Private Sub ComEventHandler(ByVal dataPtr As Integer, ByVal size As Integer) Handles myComObject.OnEvent
Dim managedData(0 To size - 1) As Byte
Dim data As IntPtr = dataPtr
If (size = 0) Then
Marshal.Copy(data, managedData, 0, size)
...
End If
...
End... |
5,579,028 | 5,579,065 | How to use switch with extern constants? | Some code.cpp file contains
extern const int v1;
extern const int v2;
extern const int v3;
extern const int v4;
int _tmain(int argc, _TCHAR* argv[])
{
int aee = v1;
switch (aee)
{
case v1:
break;
case v2:
break;
case v3:
break;
case v4:
break;
}
... | No. switch only works with fully defined integral type constants (including enum members and classes that unambiguously cast to integral type). here is a link to an old reference of MSDN, but what is says is still valid.
This link that I provided in a comment to another answer explains what optimizations compilers may ... |
5,579,641 | 5,579,675 | INT_[MIN|MAX] limit macros vs numeric_limits<T> | Is there any argument for using the numeric limits macros (e.g. INT64_MAX) over std::numeric_limits<T>? From what I understand numeric_limits is in the standard but the macros are only in C99 so therefore non-standard.
| If C++, use numeric_limits, end of.
EDIT: Okay, per the comment by James, not "end of." - exceptions are templates and case labels. But, I cannot see a use for having a case label for either min or max, or a template for them, but I guess I've not seen all possibilities...
I guess my point is that the numeric_limits te... |
5,579,667 | 5,579,737 | Replacing this macro | Given this macro
#define MAKE_TYPE(_a, _b, _c, _d) ((_a) | ((_b) << 8) | ((_c) << 16) | ((_d) << 24))
I'd like to replace it so that it takes an array[4] instead.
So that I can write MAKE_TYPE("ABCD") instead of the ugly MAKE_TYPE('A', 'B', 'C', 'D')
I'm using this in some at compile time to generate some constants.
B... | The error message means what it says: arrays can't appear in constant-expressions.
Template expressions must be constant-expressions, so arrays can't be in template arguments.
You could have a pointer to an array, but that's not what you want.
Ah, seeing as the limit is just four characters, you could use a multi-chara... |
5,579,782 | 5,579,856 | Is the volatile the correct way to inform the compiler about concurrent access to a variable | While doing concurrent programming I need to tell the compiler/optimizer that it may not cache the value of a variable, that is, it may change at any time. I am currently using the volatile keyword, but I am wondering if this is actually correct?
The standard states that volatile accesses may not be reordered, like IO... | Congratulations on figuring so many details out for yourself. Yes, volatile is not particularly useful for multithreaded programming, and constructs provided by your platform-specific multithreading library (e.g. pthreads) should always be preferred.
Specifically, you should use a read-write lock: an object which can b... |
5,580,139 | 5,580,313 | overloading stream operator >> for polynomials | how could I overload input stream operator for this code:
struct Node
{
int degree;
int coeff;
Node* link;
};
Node* cons (int c,int d,Node* p);
Node* doCancelation(int d,Node* p);
class polynomial
{
private:
Node* poly;
static const int CHAR='X';
char character;
public:
polynomial();
p... | Small remark: you have a memory leak in your constructor without arguments. First you allocate & create a new Node, then you set poly pointing to this Node to NULL. You just lost your single pointer to the allocated Node.
As for you question: assuming you get well-formed input, why don't you split the string at every ... |
5,580,253 | 5,580,411 | Get return type of member function without an object | I have a number of classes that I cannot modify. Each has a copy constructor, at least one other constructor, and a function foo() that returns some value. I want to make a class template that can derive from each of these classes, and has a data member that is the same type as the return type of foo() (sorry if I've... | You don't need that- remember that since decltype doesn't evaluate its argument, you can just call on nullptr.
decltype(((T*)nullptr)->foo()) footype;
|
5,580,549 | 5,580,612 | How check if string specifies directory? | Suppose there is a some string:
std::string some_string = "some_string";
And I want to know if chdir(some_string.c_str()) will return -1 or not without calling it. Is there quick way to do this?
P.S. I want my code to work also for windows, there I'm going to use _chdir()
| #ifdef WIN32
# include <io.h>
#else
# include <unistd.h>
#endif
int access(const char *pathname, int mode);
// check user's permissions for a file
int mode values:
00 - Existence only,
02 - Write-only,
04 - Read-only,
06 - Read and write.
Function returns 0 if the file has the given mode.
|
5,580,757 | 5,581,008 | What does *unspecified* means in C++ typedef statement? | I see statements like
typedef *unspecified* value_type;
typedef *unspecified* reference;
in the declaration of Boost::multi_array class.
namespace boost {
template <typename ValueType,
std::size_t NumDims,
typename Allocator = std::allocator<ValueType> >
class multi_array {
pu... | I'm assuming this in documentation, not compilable code, since it isn't compilable.
It's common to do this to indicate that the typedef is available for use, but the type that it aliases depends on the implementation and isn't considered part of the public interface.
In this case, the compilable header file contains de... |
5,580,921 | 5,580,953 | How can I make C++0x and __STRICT_ANSI__ get along? | I need to use popen in a project, but I get:
error: 'popen' was not declared in this scope
It looks like GCC defines __STRICT_ANSI__ under both -std=c++0x and (contrary to what little information I was able to find) -std=gnu++0x, which causes popen (and _popen) to be elided from stdio. Oddly enough, undefining __STRICT... | I'm simply undefining it on the commandline right away, this is not terribly "clean" but it works fine from what I can tell.
-std=gnu++0x -U__STRICT_ANSI__
There is probably a good reason why one should not do that, but it gives me what I want (C++0x plus GNU extensions, plus legacy stuff still works). I've been doing... |
5,581,337 | 5,581,489 | KDevelop4 : Setting up a project using cmake | I am using Kdevelop4, and would like to use a default CMake c++ project.
My plan is to partition my application into programs, several shared libraries, and I would like to have a separate project building unit tests (I am planing to use google test).
I have several questions :
How to modify default cmake file in orde... | 1) For shared library:
add_library(kdevbooklib SHARED source.cpp)
More info.
2) Link.
Update:
Root CMakeList.txt:
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
PROJECT(MyGreatProject)
SET(LIBRARY_OUTPUT_PATH ${MyGreatProject_BINARY_DIR}/bin CACHE PATH
"Single output directory for building all libraries.")
SET(EXECUTABLE_O... |
5,581,515 | 5,581,681 | Is there a number limit on opened win32 IStream object for IStorage created with StgCreateStorageEx? | I create an IStorage by StgCreateStorageEx function, with type: STGFMT_STORAGE.
Then I used the CreateStream method to create IStream objects (around 60).
I didn't call Release on all of the IStream interfaces, but when I call Seek on some of them, it returns STG_E_REVERTED.
However, if I create them and use them one b... | MSDN says:
The STGM_DELETEONRELEASE flag is not supported.
Opening the same stream more than once from the same storage is not supported. The STGM_SHARE_EXCLUSIVE sharing-mode flag must be specified in the grfMode parameter.
Did you release these streams before?
|
5,581,706 | 5,581,754 | Communicating between two processes | This has been discussed before, but I've struggled with the responses, so was hoping for a clearer answer tailored to my situation:
I'm developing an application in C++ under 32-bit Windows (minimum requirement is WinXP) which need to communicate across two processes.
The remit is that process 1 (p1) needs to start pro... | Mutexes in Win32 are cross-process synchronization. You could also look into using a condition variable, but I'm not sure if cross-process varieties of those exist.
|
5,581,859 | 5,609,676 | Retrieve performance counter value in a language-independent way | Under Windows, performance counters have different names, depending on the operating system language. For example, on an English Windows version, there is the performance counter \Processor(_Total)\% Processor Time. The same counter is called \Prozessor(_Total)\Prozessorzeit (%) on a German Windows version.
Is there an... | Each PerfMon counter is given a unique (per machine) integer ID to identify the PerfMon counter (however in the case of the standard counters this id is guaranteed to stay the same).
The information linking PerfMon counters id's to both their US English name and their Localized name is stored in the registry in the fol... |
5,582,102 | 5,582,156 | Stating constant arrays value in C++ | For example I have:
int boo[8];
boo[1] = boo[3] = boo[7] = 4;
boo[0] = boo[2] = 7;
boo[4] = boo[5] = boo[6] = 15;
How I should type it as constant values? I saw similar question but it didn't help me.
EDIT:
One more question what about if boo with indexes 0 1 3 4 5 6 7 is constant but boo[2] is not? is it possible to ... | Is this what you are looking for?
const int boo[] = { 7, 4, 7, 4, 15, 15, 15, 4 };
Get a non-const pointer to one entry in the array like this:
int * foo = (int*)&boo[2];
|
5,582,127 | 5,582,306 | Close() filedescriptor using Qt in Linux | Background information:
I have been writing code to control a device attached by a USB cable but emulating an RS-232 serial port.
The device in question is an Arduino microcontroller controlled servo pan and tilt stage (but that's not important).
I have managed to write characters to the USB emulated serial port using ... | Use:
::close(fd);
to use global close function against QWidget::close
|
5,582,154 | 5,582,174 | Compiling C++ code on Mac | I want to write very simple C++ programs on my Mac but I get errors. I don't have a lot of experience with C++ (and gcc) and the simple guides on the web also don't discuss this topic.
Please have a look at my simple hello world program:
erik2:~[03:38 pm]$ cat hw.cpp
#include <iostream>
int main ()
{
cout<<"Hello W... | You need to either add
using namespace std;
or qualify your use of symbols from that namespace as in
std::cout << "Hello, world!";
so make the symbol visible (and you also want to add a newline....).
|
5,582,678 | 5,590,598 | Coding AntiVirus using signatures-based technique | I want to code an AntiVirus for learning purposes. It will be signatures-based. I already wrote a scanner that loops through all system files and creats memory mapping for each file. What i am trying to do now, is to get a binary signature (in hex) from each malicious file (sample files) so i can compare it with the da... | Signatures generally ain't too big, and you can search them like this. However, keep in mind that if you get hundreds upon thousands of signatures (or more), it becomes unrealistic to re-start check for different signatures on each individual file. You could say that there are levels of each signature used by heuristic... |
5,582,850 | 5,623,680 | What was the exception that crashed my app, given a call stack with UnhandledExceptionFilter? | I was testing my app, and it crashed. I wasn't debugging it, so Windows Error Reporting kicked in (I was testing on a Windows XP virtual machine which doesn't have VS installed, so I think that's why the JIT debugger didn't show up). I fired up Visual Studio 2010 and remotely attached to the offending process. This is ... | If you already attached VS I would first save a dump file (Debug -> Save Dump As). Then maybe you could open this dump file in WinDbg and try to look for the exceptions context in memory. See for example http://blogs.msdn.com/b/slavao/archive/2005/01/30/363428.aspx but it goes more or less like this (taken from Advance... |
5,582,869 | 5,582,906 | How do I store a function to a variable? | I think they are called functors? (it's been a while)
Basically, I want to store a pointer to a function in a variable, so I can specify what function I want to use from the command line.
all the functions return and take the same values.
unsigned int func_1 (unsigned int var1)
unsigned int func_2 (unsigned int var1)
... | The simplest you can do is
unsigned int (*pFunc)(unsigned int) = func_1;
This is a bare function pointer, which cannot be used to point to anything other than a free function.
You can make it less painful if your compiler supports the C++0x auto keyword:
auto pFunc = func_1;
In any case, you can call the function wit... |
5,582,874 | 6,240,112 | dynamic cast throws pointer is not std::__non_rtti_object | I'm having problem with dynamic_cast. i just compiled my project and tested every thing in debug mode and then i tried compiling it in release mode, i have copied every configuration from debug mode exept optimization parameter which is now /o2, (while debuging i set it as /od) the project compiled but when it starts l... | In this case after many code changes I found out there has to be some bugs which show themselves when code is optimized (still don't know if it's compiler's mis optimization or my code has some problems but it's probably mine). and the main reason for that problem was with *l being NULL.
|
5,582,892 | 5,583,098 | Avoiding Error Flags when Reading Files | This is how I usually read files with std::ifstream:
while (InFile.peek() != EOF)
{
char Character = InFile.get();
// Do stuff with Character...
}
This avoids the need of an if statement inside the loop. However, it seems that even peek() causes eofbit to be set, which makes calling clear() necessary if I pla... | Typically, you would just use
char x;
while(file >> x) {
// do something with x
}
// now clear file if you want
If you forget to clear(), then use an RAII scope-based class.
Edit: Given a little more information, I'd just say
class FileReader {
std::stringstream str;
public:
FileReader(std::string filename... |
5,582,923 | 5,582,955 | temporary file stream | I'd like to create a temporary file stream.
Is there a c++ equivalent to C's tmpfile() function.
If not, how would I create one?
| You may want to see this.
|
5,583,088 | 5,979,987 | C++, Ogre3D, SFML, sharing resources? | Is it possible to somehow share the Ogre3D resources loaded in the Ogre::ResourceManager from resources.cfg with other parts of a programm? If possible with SFML that would be nice.
I know that CEGUI, for example, can do this automatically.
| Ogre by nature abstracts resources away from their file paths. This is because a resource may not necessarily come from the filesystem (it could be streamed over the network, or unpacked from a compressed archive). So no, without breaking encapsulation it's not possible to get the filesystem path from an Ogre resource.... |
5,583,160 | 5,583,211 | C++ signed char to double | I am new to C++ and am having an issue converting a signed char to a double. Initial idea was to convert the signed char to a const char* and use atof to return the double.
signed char x = '100';
const char * cChar = x;
std::cout << atof(cChar);
What can I try to resolve this?
| signed char x = 100;
double d = x;
cout << d;
const char * x = "100";
double d = atof(x);
cout << d;
'100' is wrong - you need either a const char * x = "100"; or a char x=100;
|
5,583,223 | 5,583,267 | C++ & Boost: How do I convert a dynamic bitset to a string? | So, the documentation says this:
template <typename Char, typename Traits, typename Block, typename Alloc>
basic_ostream<Char, Traits>&
operator<<(basic_ostream<Char, Traits>& os, const dynamic_bitset<Block, Alloc>& b)
Effects: Inserts a textual representation of b into the stream os (highest bit first). Informally, t... | to_string is a free function in the boost namespace, not a member function.
boost::dynamic_bitset<> bit_value(Config::HASH_WIDTH_IN_BITS, hash_value);
string buffer;
to_string(bit_value, buffer);
// here buffer contains the string representation of bit_value.
|
5,583,553 | 5,584,978 | Name mapping -- \\.\PhysicalDrive to \\.\SCSI | I'm developing in windows with C/C++ and I want to know is it possible to get an apropriate \\.\SCSI device name by \\.\PhysicalDrive ?..
For example, it's wonderful to know how to get that \\.\PhysicalDrive0 is the same that \\.\SCSI0.
| Look at the code which I posted in my answer to the question. The author of the question had changed the text of the question so many time and the last version of text clear nor really what the original problem was.
In the example, which C source code you can download here, I show how to get many kind of information ab... |
5,583,600 | 5,583,708 | const parameter problems | #include <iostream>
void f(const int * & p)
{
int i =0;
i = p[0];
std::cout << i << std::endl;
}
int main()
{
int * p =new int[1];
p[0] =102;
f(p);
return 1;
}
The gcc compiler gives error for this code:
prog.cpp: In function ‘int main()’:
prog.cpp:16: error: invalid initialization of re... | Going from int* to const int* requires creating a temporary const int* pointer and binding the reference const int*& to that temporary.
The Standard forbids doing that creating of a temporary for non-const references. You therefor need to make the reference const as you did your fix.
This is because non-const refere... |
5,583,646 | 5,583,689 | why D3DXCreateCylinder is not creating a cylinder? |
I am trying to make a ball trail.
rBallPos is correctly updating.
Following code is not working creating
a cylinder as ball's trail. How to
solve it?
LPD3DXMESH /*ID3DXMesh*/ ppMeshCylinder = NULL;
hr = D3DXCreateCylinder(g_d3d_device,0.1f,0.1f,0.1f,1,1,&ppMeshCylinder,0);
hr is FAILED here also hr != D3D_OK
D... | You need to pass in a pointer to LPD3DXMESH, so your mesh parameter should be &ppMeshCylinder instead of ppMeshCylinder. In fact, your compiler should have already warned you.
Update: Try passing in a larger value for Slices and Stacks, say 5 or 10. It's not possible to create a cylindrical mesh with just 1 polygon.
|
5,584,048 | 5,592,354 | How to add redmonnt.dll using AddMonitor() under Windows 7 64 bit | I'm trying to register redmon monitor on Windows 7 64 bit. Here is an example of code I use:
MONITOR_INFO_2 info;
info.pName = "RedmonMonitor";
info.pEnvironment = "Windows x64";
info.pDLLName = "redmonnt.dll";
SetPrivilege("SeLoadDriverPrivilege",TRUE);
AddMonitor(NULL, 2, (LPBYTE)&info);
It works perfectly on WinXP ... | Which version of redmonnt.dll you use? Is it 64-bit DLL or 32-bit version from the official site? The DLL will be loaded by spoolsv.exe which is 64-bit application on the 64-bit operation system. So you have to use 64-bit version of the DLL.
|
5,584,057 | 5,587,912 | Using Google Mock with boost::bind | I have a class whose constructor takes a Boost function, and I'd like to test it with Google Mock. The following code shows a sample class and my attempt to test it:
MyClass.h:
#include <boost/function.hpp>
class MyClass
{
public:
MyClass(boost::function<void()> callback);
void callCallback();
private:
boos... | I think this line is wrong:
MyClass myClass(boost::bind(&CallbackMock::callback, callbackMock));
The last parameter should be &callbackMock
|
5,584,088 | 5,584,120 | Curiously Recurring Templates? | I have a problem that Curiously Recurring Templates could help quite nicely, but I cant even get past a simple test.
template<typename T, int _size, typename OutterT>
class Foo {
};
template<typename T>
class Bar : public Foo<T, 2, Bar> {};
//typedef Bar<float> Vec2f;
int main()
{
return 0;
}
This results in ... | template<typename T, int _size, typename OutterT>
class Foo {
};
template<typename T>
class Bar : public Foo<T, 2, Bar<T> > {};
// ^^^
Bar<float> x;
Since Bar is a template, you must provide the template argument to instantiate it into a class.
|
5,584,115 | 5,584,149 | Macro "parameter" name mesh. Can it work? What am I doing wrong? | // MACROS
#define A_PROPERTY(TYPE, NAME) \
private: \
TYPE NAME; \
public: \
void SetNAME(TYPE theNAME) {NAME=theNAME;} \
TYPE GetNAME() {return NAME... | Use ## to stitch tokens.
#define A_PROPERTY(TYPE, NAME) \
private: \
TYPE NAME; \
public: \
void Set##NAME(TYPE the##NAME) {NAME=the##NAME... |
5,584,444 | 5,586,530 | Displaying multiple simultaneous Views of the same Document | How do I persuade the MFC Doc/View architecture to let me simultaneously display two different views of the same document?
For example, say my CDocument sub-class represents an archive of some description.
I want a UI where the names of all the entries in that archive are presented in a CListView sub-class in the left ... | SDI means "Single Document Interface", it restricts you to only one single document at a time but not in the number of views you can open for this document.
The probably most common approach to open multiple views in an SDI application are Splitter Windows.
You add one view to the CSingleDocTemplate (it doesn't matter ... |
5,584,788 | 5,584,849 | Is there a more elegant way to conditionally insert into a std::map of std::maps? | I have nested containers std::map<int, std::map<T, U> > and want to populate them properly, either inserting a new sub map or appending to the sub map if the integer key exists. So I came up with something like the following example:
int n = ...;
int m = ...;
obj get_some_random_obj(int i, int j); // returns som... | container[i][j] = get_some_random_obj(i,j);
map's operator[] inserts if the element isn't present.
|
5,584,829 | 5,587,569 | Get an array via function-param | I have an array declared as
Object array[N];
and a function as
void GetArray(void** array, size_t count)
{
*array = array;
*count = N;
}
I'm trying to call the function with this code:
size_t number;
GetArray(XXX, &number);
where is XXX what should I pass to get the array? Thank you
EDIT 1
Object *array
GetA... | Though I'm not 100% convinced that I understand your intent correctly,
if GetArray has to return Object array[N] itself, how about returning
Object* from GetArray?
For example:
size_t const N = 1;
Object array[N];
Object* GetArray(size_t* count)
{
*count = N;
return array;
}
EDIT:
As far as I see your edited ... |
5,584,888 | 5,726,047 | Visual Leak Detector does not work | I have just started using Visual Leak Detector for Visual C++ 2008/2010
When i run it on small app (just few line with undeleted allocations) it works just fine.
Now I want to run it into my bigger app (wxWidgets app, 2 threads), but when I include
#include <vld.h>
my app does not completely start up. It starts cycli... | Visual Leak Detector makes the App run VERY slowly, be patient.
Are you running a single binary file?
I'v had issues when my program was split into the main executable and libraries loaded on the run.
The solution was to do the #include everywhere, especially the executable.
Note that you can use VLDDisable and VLDEnab... |
5,584,902 | 5,585,189 | Conversion of Fortran to C++ | I want to write an object oriented program. I do not know much about it. It looks for me that it is somewhat similar to subroutine in Fortran. I have created a sample program below. May you help me out translating it into C++ codes please?
c Program in Fortran to calculate area and perimeter of a rectangle
implicit do... | I'm not into Fortran, but this looks like what you are getting at (If it's not what you wanted, please clarify):
#include<vector> // allows you to use the C++ STL std::vector (think of it as a better array)
// calculates the area of a rectangle
double rectangle_area( const double height, const double width )
{
ret... |
5,584,975 | 5,585,157 | A tidy way of bundling checking for allocation failures and returning errors if so | I'm working in C++ but its on Brew which doesn't support exceptions.
There's going to be lots of code of the form:
X* x = new X;
if (!x)
return NoMemoryErrorCode;
Is there a nice elegant way of condensing the above 3 lines into one? Something along the lines of:
X* x = ReturnIfNoMemory(new X);
I could do that wi... | As return only returns from the current function to its caller, you cannot really shorten this code without the preprocessor.
E.g:
#define newOrReturn(x, t) t * x = new t; if (!x) return NoMemoryErrorCode
newOrReturn(x, int);
|
5,585,038 | 5,600,874 | D3DX11SaveTextureToFile with shared resources | I'm using shared resources to send textures from one D3D11 device to another, so that I can copy the back buffer over the second device and use the second device context to save that texture to a file. This seems to be working, but when I save the texture, it saves an empty PNG.
I tried saving the texture with the prim... | Here is how I solved the problem. Turns out, using the D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX misc flag doesn't allow to save the texture to a file. So I used the D3D11_RESOURCE_MISC_SHARED flag instead with a regular mutex, without using the DXGIKeyedMutex stuff.
Copy the back buffer to shared texture and create a shar... |
5,585,054 | 5,585,224 | C++/CLI - Is it possible to check a POP3 email account and receive messages? | Is it possible to check a POP3 email account and receive messages in C++/CLI? If so, how would this be done? I'm quite new to this, so if anyone who answers could do so in layman's terms, that would be great.
| Which one is it? C++ or CLI? If you're after C++, there are plenty of pop3 libraries available. Google is your friend. If you want a good CLI one, try fetchmail. It can poll from multiple sources and has a lot of delivery options.
|
5,585,152 | 5,585,194 | Invalid conversion from 'int' to 'double*' | I have this line of code:
int g = modf(ans*power, 1)*10;
And it is giving me the error:
Invalid conversion from 'int' to 'double*'.
ans is defined as:
double ans = 1.0/d;
power is defined as:
int power = pow(10,x);
and the x that power is using is defined as:
for(int x = 0; x < 50; x++) {
I don't see where I am u... | modf(ans*power, 1) is bad
double smthng = 1.0; modf(ans*power, &smthng) is good.
http://linux.die.net/man/3/modf
|
5,585,195 | 5,601,968 | how to build a hello word like application using Qt and VS2010 | I have read many answers both here and on other places on the net, but I'm still unable to build / run a small hello world like application using VS2010 and the latest Qt opensource (4.7.2) for VS2008.
Here are the steps I've done, and of course restarted where needed:
installed VS2010
installed VS2010 SP1
downloaded... | After a lot of reading and trial and error, I made it work and I wrote a guide about it here:
How to build Qt for Visual Studio 2010
|
5,585,270 | 5,585,297 | Deletion of data possibly held in two different places | I have a program doing something like the following:
class SomeObject{}
{
void function(int x, int y);
void function(SomeOtherObject *z);
SomeOtherObject *ptrToObj;
}
SomeObject::function(int x, int y)
{
ptrToObj = new SomeOtherObject(x, y);
}
SomeObject::function(SomeOtherObject *z)
{
ptrToObj =... | Use a shared_ptr, either the one from Boost or the one in a recent C++(0x) library. shared_ptr does reference counting for you.
|
5,585,308 | 5,585,328 | Is C++ guaranteed to call a certain constness of member function? | If I have the following:
class A {
int foo() const {
j++;
return i;
}
int& foo() {
return i;
}
int i;
mutable int j;
};
then obviously something like
A a;
a.foo() = 5;
calls the non-const version. But what conditions need to be met to make sure that a call is to the cons... | const function gets called when the object itself is const.
int i = static_cast<const A>(a).foo(); //calls const function
Also see this code for better understanding: (must read the comments)
void f(const A &a) //a is const inside the function
{
int i = a.foo(); // calls const function
}
void h(A &a) //a is non-co... |
5,585,315 | 5,643,089 | Profiler Windows x32 problem | I run Windows XP SP3 on my virtual machine.
There I use Visual C++ Express a CLR profiler for .net 2.0
I run x86 profiler(choosing between x86 and x64), choose simple Visual C++ application which outputs 1000 times "Hello world" string.
What the profiler does is shows the message "Waiting for application to start comm... | A CLR profiler cannot profile native C++ code, only CLR (Common Language Runtime) the virtual box that runs .Net code.
Try downloading the free edition of AQTime at http://smartbear.com/products/free-tools/aqtime-standard/
That one should be able to profile your C++ code (if you follow some rules, you might need to hav... |
5,585,377 | 5,623,425 | VC++ hangs and freezes computer upon completion of compilation | When the compiling of a project is complete (or at least when it says it does), I receive no window, no error message, or anything; VC++ freezes up and my computer basically stops responding altogether.
After about five minutes, Task Manager finally pops up and I'm able to close the program. Upon doing that, I see thi... | As suggested by Hans Passant, disabling avast! solved the problem.
|
5,585,436 | 5,585,464 | Using interface in C++ for dependency injection | Assume I have the following abstract class and use it as an "interface" in C++:
class IDemo
{
public:
virtual ~IDemo() {}
virtual void Start() = 0;
};
class MyDemo : IDemo
{
public:
virtual void start()
{
//do stuff
}
};
Then in the class that need to have a handle to the interface (con... | Try:
Project::Project(IDemo* demo)
: _demo(demo)
{}
But If the demo object is never going to change for the lifetime of the project then I prefer to pass by reference:
class Project
{
public:
Project(IDemo& d)
: demo(d)
{}
private:
IDemo& demo;
};
Then use it like thi... |
5,585,532 | 5,585,683 | C++ int to byte array | I have this method in my java code which returns byte array for given int:
private static byte[] intToBytes(int paramInt)
{
byte[] arrayOfByte = new byte[4];
ByteBuffer localByteBuffer = ByteBuffer.allocate(4);
localByteBuffer.putInt(paramInt);
for (int i = 0; i < 4; i++)
arrayOfByte[(3 - i... | Using std::vector<unsigned char>:
#include <vector>
using namespace std;
vector<unsigned char> intToBytes(int paramInt)
{
vector<unsigned char> arrayOfByte(4);
for (int i = 0; i < 4; i++)
arrayOfByte[3 - i] = (paramInt >> (i * 8));
return arrayOfByte;
}
|
5,585,592 | 5,585,727 | C++ genetic programming: Invoking a linker/compiler, executing the compiled program and piping input / output | This is a generic question, and although I'm pretty sure some of it's parts have been answered I want opinions rather than a broad discussion. I intend to do a master thesis on evolutionary computation and genetic programming, and I would like opinions from experts on Linux/C++ whether it would be possible to create so... | Yes, it is possible to do this, and actually quite simple. You output source code to a temporary file (mkstmp), you fork/exec a compilation process (that outputs to a temporary file), you fork/exec the resulting program, before that you dup2 and pipe to plug an input and an output. It is basic Unix programming, nothing... |
5,585,692 | 5,585,713 | "Delete" vs. "Remove" | I'm implementing a method in my container class that removes/deletes one value from the array. For example:
// | 532 | 422 | 134 | 762 |
// | 0 | 1 | 2 | 3 |
MyObject.Remove(1); // Or MyObject.Delete(1);
// | 532 | 134 | 762 |
// | 0 | 1 | 2 |
Which word is more commonly-used for this type of thing?
| The standard library containers use "erase". "Delete" might be confused with deleting a memory allocation. The standard library algorithms with "remove" in the name don't actually change the size of the container (see http://en.wikipedia.org/wiki/Erase-remove_idiom).
|
5,585,725 | 5,585,880 | Splitter CreateStatic issue | I have next error when I tried to create a static splitter in MainFrame class.
Error C2653: 'CMyView' : is not a class or namespace name c:\projects\mt\mt\mainfrm.cpp 200 1 MT
I have tried to add #include "MainFrm.h" a the top of the MainFrm.cpp but it make another error about CMyDoc. How I can solve this issue?
... | You need to include the header where you defined CMyView in the MainFrm.cpp file. Make sure you don't include MyView.h in MyDoc.h, and MyDoc.h in MyView.h. That would create a cyclic dependency; use forward declaration if needed, to avoid such cycles.
|
5,586,214 | 5,586,678 | How to convert (char *) from ISO-8859-1 to UTF-8 in C++ multiplatformly? | I'm changing a software in C++, wich process texts in ISO Latin 1 format, to store data in a database in SQLite.
The problem is that SQLite works in UTF-8... and the Java modules that use same database work in UTF-8.
I wanted to have a way to convert the ISO Latin 1 characters to UTF-8 characters before storing in the ... | ISO-8859-1 was incorporated as the first 256 code points of ISO/IEC 10646 and Unicode. So the conversion is pretty simple.
for each char:
uint8_t ch = code_point; /* assume that code points above 0xff are impossible since latin-1 is 8-bit */
if(ch < 0x80) {
append(ch);
} else {
append(0xc0 | (ch & 0xc0) >> 6);... |
5,586,323 | 5,586,945 | Storing multiple messages in one protocol buffer binary file | I have repeating messages which I want to store in a single file. Currently I have to wrap this repeating message in another message. Is there a way around this?
package foo;
message Box {
required int32 tl_x = 1;
required int32 tl_y = 2;
required int32 w = 3;
required int32 h = 4;
}
message Boxes {
repeate... | Here's what "Techniques" section of the Protocol Buffers documentation says about repeated messages:
If you want to write multiple messages
to a single file or stream, it is up
to you to keep track of where one
message ends and the next begins. The
Protocol Buffer wire format is not
self-delimiting, so proto... |
5,586,355 | 11,335,566 | C++: Getting a temporary file, cross-platform | I'm looking for a cross-platform way of getting designated a temporary file. For example in linux that would be in the /tmp dir and in Windows in something akin to C:\Users\Username\AppData\Local\Temp.
Does a cross-platform (Boost?) solution to this exist?
EDIT:
I need this file to exist until the program terminates. t... | The Boost Filesystem library, from version 3 of that library, can be used to create a temporary file name. It also offers a crisp solution. Indeed, the following C++ code should be platform independent:
// Boost.Filesystem VERSION 3 required
#include <string>
#include <boost/filesystem.hpp>
boost::filesystem::path tem... |
5,586,377 | 5,586,413 | How to access the 'previous' element in a C++ list iterator loop? | I'm trying to access the previously iterated element in a loop going through all the elements of a list.
To be more specific, my loop looks like this:
for (iter=list_object.begin(); iter!= list_object_.end(); iter++)
{
function_1(*iter);
function_2(*PREVIOUS_VALUE_IN_THE_LIST);
}
How do I access this previ... | std::list is only bidirecitonally iterable, so you can only move the iterator one position at a time. You thus need to create a new iterator:
iter_copy = iter;
--iter;
Obviously, you are responsible for ensuring that a previous element actually exists before you decrement the iterator.
In C++0x, this functionality is... |
5,586,400 | 5,619,260 | astyle did not indent lines ended with . or -> | I tried to use astyle to stylize my code, but when it came to
some_structure[some_index].
method_call(some_parameters);
it would turn it into
some_structure[some_index].
method_call(some_parameters);
I am using --style=ansi. I did not see any corresponding options in help file.
Can you help?
| astyle can't recognize and indent your code because of the newline, even Uncrustify (http://uncrustify.sourceforge.net/) which has tons of options, can't.
you can use UniversalIndentGUI (http://universalindent.sourceforge.net/) to see the changes live and save a config file for you favorite code beautifier.
|
5,586,459 | 5,586,474 | If I want to use std::shared_ptr, which header to include? | In c++0x shared_ptr will be moved from tr1 into std. So which header to include to get it?
I am using g++ 4.5 (ubuntu 10.10)
| You'll find it in <memory> now.
|
5,586,568 | 5,598,528 | OpenGL Issue Drawing a Large Image Texture causing Skewing | I'm trying to store a 1365x768 image on a 2048x1024 texture in OpenGL ES but the resulting image once drawn appears skewed. If I run the same 1365x768 image through gluScaleImage() and fit it onto the 2048x1024 texture it looks fine when drawn but this OpenGL call is slow and hurts performance.
I'm doing this on an And... | Finally solved the issue. First thing to know is what's the maximum texture size allowed for the device:
GLint texSize;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize);
When I ran this the texture size max for the Motorola Milestone was 2048x2048, which was fine in my case.
After messing with the texture mapping to no en... |
5,586,595 | 5,588,633 | Problem recompiling using make command in ubuntu | I m trying to modify some C++ files in ns2 and then recompile using make command. Although new .o file is created after make, the output is similar to that of previous C++ file (before modifying). can someone suggest what may be the reason behind it.
| Make sure you're running your newly built ns2 executable -- if you just type ns2, you'll get the installed ns2 binary on the system, which you haven't changed (unless you do a make install and even then it might install it in a different place, leaving the old one where it is).
Generally you'll need to run ./ns2 if you... |
5,586,733 | 5,586,833 | How do I use the new c++0x regex object to match repeatedly within a string? | I have a string:
"hello 1, hello 2, hello 17, and done!"
And I want to apply this regular expression repeatedly to it:
hello ([0-9]+)
And be able to iterate through the matches and their capture groups somehow. I've used the "regex" stuff successfully in c++0x to find the first match for something in a string and ins... | Don't use regex_match, use regex_search. You can find examples here: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339.
This should do the trick (notice I'm typing directly in the browser, didn't compile it):
#include <iostream>
#include <regex>
int main()
{
// regular expression
const std::regex pa... |
5,586,747 | 5,587,012 | Design Pattern For Making An Assembler | I'm making an 8051 assembler.
Before everything is a tokenizer which reads next tokens, sets error flags, recognizes EOF, etc.
Then there is the main loop of the compiler, which reads next tokens and check for valid mnemonics:
mnemonic= NextToken();
if (mnemonic.Error)
{
//throw some error
}
else if (mnemonic.Text ... | I've written a number of assemblers over the years doing hand parsing and frankly, you're probably better off using a grammar language and a parser generator.
Here's why - a typical assembly line will probably look something like this:
[label:] [instruction|directive][newline]
and an instruction will be:
plain-mnemoni... |
5,587,152 | 5,587,323 | How to overload the ->* operator? | I tried this, and some variations on it:
template<class T>
class Ptr {
public:
Ptr(T* ptr) : p(ptr) {}
~Ptr() { if(p) delete p; }
template<class Method>
Method operator ->* (Method method)
{
return p->*method;
}
private:
T *p;
};
class Foo {
public:
void foo(int) {}
int ba... | The return of operator->* represents a function in the process of being called, with the only missing parts being the parameters. Thus, you must return a functor that invokes the given function on the given object with the given parameters:
// PTMF = pointer to member function
template<class Obj>
struct PTMF_Object{
... |
5,587,166 | 5,587,210 | How to run functions from context menu in QGraphicsItem | I am trying to implement a context menu in my QGraphicsItem subclass like so:
void ImagePixmapItem::right_clicked(){
qDebug("Got here!");
}
void ImagePixmapItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event){
QMenu menu;
QAction *removeAction = menu.addAction("Remove");
QAction *markAction =... | The QMenu is deleted when the menu object goes out of scope.
Try this:
void ImagePixmapItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
std::auto_ptr<QMenu> menu(new QMenu(address_of_parent_widget));
QAction *removeAction = menu->addAction("Remove");
QAction *markAction = menu->addAction("Mar... |
5,587,207 | 5,587,262 | Why put void in params? | What's the reason for putting void inside of the params?
Why not just leave it blank?
void createLevel(void);
void createLevel();
| The void in the parenthesis are from C. In C a function with empty parentheses could have any number of parameters. In C++ it doesn't make any difference.
|
5,587,258 | 5,587,478 | safe std::tr1::shared_ptr usage | Is this approach unsafe?
#include <tr1/memory>
Foo * createFoo()
{
return new Foo(5);
}
int main()
{
std::tr1::shared_ptr<Foo> bar(create());
return 0;
}
Or would it be preferable for createFoo to return a shared_ptr<Foo> object?
| The example is safe: if the shared_ptr constructor throws an exception, it delete's its pointer argument before throwing (draft standard, 20.9.11.2.1).
Whether create should return a shared_ptr depends on what its clients may reasonably want to do with its result. If all they ever do is wrap it in a shared_ptr, then re... |
5,587,299 | 5,587,367 | Difference Between Class Operators | I am reading into C++ a little bit and was wondering if someone could explain some differences of some of the class operators to me. The operators in question are:
* & . ->
I understand some of them, however, I fail to see the difference between some. For example:
*x
&x
x.y
(*x).y
x -> y
Can someone use an example and... | Take this small structure as given for my samples:
struct MyStruct {
int y;
};
*x dereferences the pointer x. The return value is a reference to the object pointed to by x:
MyStruct* x = ...;
MyStruct xval = *x;
// or
MyStruct& xref = *x;
// read up on references to understand the latter
&x takes the address of ... |
5,587,930 | 5,587,948 | Function signature differences in C++11 | Considering C++11's lambdas with the following code,
template <typename M>
void call(void (*f)(M), M m)
{
f(m);
}
int main()
{
call<int>([](int n) { }, 42); // OK
int r;
call<int>([&](int n) { r = n; }, 42); // KO
}
is there a signature difference between the lambdas that makes the second one incom... | Only a captureless lambda can be implicitly converted to function pointer.
A lambda that captures variables cannot be converted to a function pointer because it has state that needs to be maintained (the captured variables) and that state cannot be represented by a function pointer.
The type M cannot be inferred from t... |
5,587,962 | 5,860,707 | CMFCPropertyGridProperty with multi line edit box | How to create a multi line property with edit box? I need one more property that will show text in multi line box.
CMFCPropertyGridProperty* pGroup1 = new CMFCPropertyGridProperty(_T("Appearance"));
pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("Name"), (_variant_t) _T(""), _T("Specifies the text that will be dis... | It seems that multi-line properties are not implemented in MFC Property Grid. You can create a custom property with a button and show your own dialog with multi-line edit control when user click this button.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.