question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,765,019 | 3,765,059 | How to retrieve a reference from a boost ptr_vector? | I have two classes: an Object class, and an ObjectManager class. The ObjectManager class stores "Objects" via a ptr_vector container. There are some instances where I need to retrieve references to these stored pointers to perform individual actions on them. How would I go about doing so?
Compilable Pseudo Code:
#inclu... | Convert your container to use shared_ptr as the member:
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
class Object
{
public:
int m_Id;
Object(int id) : m_Id(id) { }
};
class ObjectManager
{
private:
typedef boost::shared_ptr<Object> ObjectPtr;
typedef std::vec... |
3,765,026 | 3,765,188 | boost compressed matrix basics | I am confused on how the boost::compressed_matrix works. Suppose I declare the compressed_matrix like this:
boost::numeric::ublas::compressed_matrix<double> T(1000, 1000, 3*1000);
This allocates space for 3*1000 elements in a 1000x1000 matrix. Now how do I give it the locations which are the non-zero elements? When an... | compressed matrix has an underlying linear container (unbounded_array by default, but you can make it bounded_array or std::vector if you want), which contains all non-zero elements of the matrix, in row-major (by default) order. That means that whenever you write a new non-zero element to compressed matrix, it is inse... |
3,765,167 | 3,766,566 | How to filter out untouched code in C++ | For dissecting/understanding huge template-heavy code base it would really useful to have a tool that tells me what class/code have made it to the final binary.
For example if there are two class A and B in the code but I only end up instantiating only A then I would somehow like to know filter out B. Are there any too... | Use some profiler/code coverage tools. Some versions of MS Visual Studio ship with profiler. Then there are several commercial profilers/coverage tools like Intel VTune. On *nix with GCC there is the gcov.
|
3,765,556 | 3,765,567 | Template programming in C++ | I am having trouble getting to grips with programming using templates in C++.
Consider the following files.
C.h
#ifndef _C_H
#define _C_H
template <class T>
class C {
public:
C();
virtual ~C();
}
#endif _C_H
C.cpp
#include "C.h"
template <class T>
C<T>::C() {
}
template <class T>
C<T>::~C() {
}
I try i... | When using templates, the source code is required to be available whenever the type is instantiated, because otherwise the compiler can't check that the template code will work for the given types. Dividing it into a .cpp and a .h file won't work, because the other .cpp files only know about the .h file.
You basically ... |
3,765,587 | 3,765,746 | Can I call select on a datagram socket without using blocking I/O | Can I call select before recv_from on a socket that is blocking?
| Yes. select() supports both blocking and non-blocking sockets.
|
3,765,602 | 3,765,657 | returning an iterator | How i return iterator form function :
i worte this :
.
..
template<class S,class T> class Database {
public:
.
..
map<S,Node<T>*> m_map::iterator Find (S keyToFind);
.
..
....
private:
.
..
map<S,Node<T>*> m_map;
..
.
};
.
..
template<class S,class T>
map<S,Node<T>*> m_map::iterator Find (S keyToFind) {
map<S,Nod... | This should be:
template<class S,class T>
typename map<S,Node<T>*>::iterator Find(S keyToFind) {
typename map<S,Node<T>*>::iterator itMap;
itMap = m_map.find(KeyToUpDate);
return itMap;
}
and
typename map<S,Node<T>*>::iterator Find (S keyToFind);
typename is needed because iterator is a dependent type, se... |
3,765,654 | 3,765,889 | how to use Dijkstra c++ code using array based version | I need to use (not implement) an array based version of Dijkstras algo .The task is that given a set of line segments(obstacles) and start/end points I have to find and draw the shortest path from start/end point.I have done the calculating part etc..but dont know how to use dijkstras with my code.My code is as follows... | Dijkstras
This is how Dijkstra's works:
Its not a simple algorithm. So you will have to map this algorithm to your own code.
But good luck.
List<Nodes> found; // All processed nodes;
List<Nodes> front; // All nodes that have been reached (but not processed)
// This list is sorted... |
3,765,678 | 3,766,212 | Creating Timers in C++ using Lua | I was wondering whether the following setup would work for a small game:
Lets assume I have the following functions registered to Lua like so:
lua_register(L, "createTimer", createTimer);
lua_register(L, "getCondition", getCondition);
lua_register(L, "setAction", setAction);
Where: (leaving the type checking behind)
i... | You may want to change the condition string to "return getCondition()<=5" otherwise the string chunk will not compile or run. Then check the boolean return value on the stack when the luaL_doString() returns successfully. Something like this:
// this function is called in the game-loop to loop through all timers in the... |
3,765,877 | 3,765,974 | How to cut off leading digits? C++ | How can I cut off the leading digits of a number in order to only display the last two digits, without using the library. For example:
1923 to 23
2001 to 01
1234 to 34
123 to 23
with only
#include <iomanip>
#include <iostream>
Thanks!
| If you're just working with integers I'd suggest just doing mod %100 for simplicity:
int num =2341;
cout << num%100;
Would display 41.
And if you need a leading zero just do:
std::cout << std::setw(2) << std::setfill('0') << num%100 << std::endl;
|
3,766,150 | 3,947,920 | Using C++ for backend calculations in a web app | I'm running a PHP front end to an application that does a lot of work with data and uses Cassandra as a data store.
However I know PHP will not give me the performance I need for some of the calculations (as well as the management for the sheer amount of data that needs to be in memory)
I'd like to write the backed st... | More details about how much data your computations will need would be useful. Thrift does seem like a reasonable choice. You could use it between PHP, your computation node, and the Cassandra backend. If your result is small, your RPC transport between PHP and the computation node won't make too much difference.
|
3,766,218 | 4,849,090 | Boost GIL image constructors | I'm currently trying to figure out how to use the Generic Image Library included in Boost. Right now, I just want to use the library to store pixel data and use the Image IO to write PNGs. I'm having trouble understanding just how to set up the object however.
The hpp says
image(const point_t& dimensions,
std::si... | it sounds like you solved your problem in the meantime, but just for the record... here are some pointers to information about your problem:
First of all you may have missed the second constructor of boost::gil::image, which offers explicit access to the horizontal and vertical dimensions without the need of the point... |
3,766,340 | 3,766,627 | When do I need the Windows SDK and what is .NET for? | I am a student and after taking some introductory programming courses in Java, C, and just finishing up a book on C++, I would like to start developing applications for Windows.
I have done my best to page through google and find the answers I need, but I seem to be at a loss.
When would I need the Windows SDK over jus... |
When would I need the Windows SDK over just the regular API?
The SDK includes headers, libraries, tools, etc., that give you access to the API (and to .NET, for that matter). For example, a typical API-based program will start with #include <windows.h> -- but without the SDK, you don't have a copy of Windows.h to in... |
3,766,538 | 3,766,550 | Casting void *user_data to object | how do I cast void *something to an object in standard C++?
Specifically I want want to cast void *userdata
to std::map<String, void*>
Is this possible? I am trying:
//void *user_data is a parameter of this function (callback)
std::map <String, void*> user_data_n; //this line is ok
user_data_n = static_cast<std::map<St... | When you're casting from a void *, your result will be a pointer too. So the map declaration should be:
std::map <String, void*> *user_data_n;
Second, you should use reinterpret_cast for such (potentially dangerous) casts:
user_data_n = reinterpret_cast<std::map<String, void *> *>(user_data);
Update:
As others sugges... |
3,766,740 | 3,769,269 | Overriding a default option(...) value in CMake from a parent CMakeLists.txt | I am trying to include several third-party libraries in my source tree with minimal changes to their build system for ease of upgrading. They all use CMake, as do I, so in my own CMakeLists.txt I can use add_subdirectory(extern/foo) for libfoo.
But the foo CMakeLists.txt compiles a test harness, builds documentation, a... | Try setting the variable in the CACHE
SET(FOO_BUILD_SHARED OFF CACHE BOOL "Build libfoo shared library")
Note: You need to specify the variable type and a description so CMake knows how to display this entry in the GUI.
|
3,767,162 | 3,767,247 | Is if(double) valid C++? | I just ran into this line of code:
if( lineDirection.length2() ){...}
where length2 returns a double. It kind of puzzles me that 0.0 is equivalent to 0, NULL, and/or false.
Is this part of the C++ standard or is it undefined behaviour?
| It is a very much Standard Behavior (Boolean Conversion)
$4.12/1 - "An rvalue of arithmetic,
enumeration, pointer, or pointer to
member type can be converted to an
rvalue of type bool. A zero value,
null pointer value, or null member
pointer value is converted to false;
any other value is converted to true... |
3,767,372 | 4,123,813 | OS X 10.6.4 + Eclipse 3.5 + latest CDT not outputting cout/printf to console | I spend most of my time in Eclipse these days, so I thought I would check out what Eclipse's C++ support was like (I usually use Xcode on Mac and Visual Studio for Windows).
I found the CDT package for Eclipse 3.5, so I installed it.
Everything installed properly and the default C++ "Hello World" project compiled nicel... | Just tried this in Helios 3.6 and it works. Must be a 3.5 problem.
|
3,767,511 | 3,767,558 | portable threading APIs | I know of three portable threading C++ APIs :
Qt
boost::thread
GNU Pth
Apart from possible licensing issues involved, how do these compare in:
actual portability (mostly interested in Linux and Windows)
capabilities
programming ease-of-use
support/development activity of the library
And: are there more like these t... | boost::thread is portable and actively supported, but most importantly it's going to be in the Standard C++0x Library. So I recommend this library for general-purpose threading.
|
3,767,552 | 3,767,615 | how to use Exceptions in C++ program? | hey , i am trying to inherit the exception class and make a new class called NonExistingException:
i wrote the following code in my h file:
class NonExistingException : public exception
{
public:
virtual const char* what() const throw() {return "Exception: could not find
Item";}
};
in my code before i am se... | I would do this:
// Derive from std::runtime_error rather than std::exception
// runtime_error's constructor can take a string as parameter
// the standard's compliant version of std::exception can not
// (though some compiler provide a non standard constructor).
//
class NonExistingVehicleException : public std::runti... |
3,767,757 | 3,767,915 | What is the meaning of "difference of memory address?" | Consider
#include <cstdio>
int main() {
char a[10];
char *begin = &a[0];
char *end = &a[9];
int i = end - begin;
printf("%i\n", i);
getchar();
}
#include <cstdio>
int main() {
int a[10];
int *begin = &a[0];
int *end = &a[9];
int i = end - begin;
printf("%i\n", i);
ge... | the compiler will automatically calculate pointer arithmetic based on type of pointer, which is why you cant perform operation using void* (no type information) or mixed pointer type (ambiguous type).
In MSVC2008 (and in most other compiler i believe), the syntax is interpreted as calculate the amount of element differ... |
3,767,842 | 3,767,906 | Is there a general smart pointer like auto_ptr and shared_ptr that doesn't need C++0x? | I'm wanting a non-reference counted smart pointer that can combine some of the useful aspects of auto_ptr and shared_ptr. I think that C++0x's unique_ptr is ultimately what I'd need, but I need something that will compile on Visual Studio 2008 and Xcode (gcc 4.2).
The functionality I need is:
Usable in factory metho... | Edit: In my original answer, I failed to understand that boost::shared_ptr is not acceptable to you (probably for performance reasons).
auto_ptr does, as you note, support forward declaration. You need to include the header for the referenced class in those places that may destroy the object referenced by the auto_ptr.... |
3,767,869 | 3,767,883 | Adding message to assert | I'm looking for a way to add custom messages to assert statements.
I found this questions Add custom messages in assert? but the message is static there. I want to do something like this:
assert((0 < x) && (x < 10), std::string("x was ") + myToString(x));
When the assertion fails I want the normal output plus for exam... | You are out of luck here. The best way is to define your own assert macro.
Basically, it can look like this:
#ifndef NDEBUG
# define ASSERT(condition, message) \
do { \
if (! (condition)) { \
std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
<< " line " <... |
3,768,339 | 3,768,426 | Mixing component based design and the model-view(-controller) pattern | 'm developing a 2D game and I want separate the game engine from the graphics.
I decided to use the model-view pattern in the following way: the game engine owns game's entities (EnemyModel, BulletModel, ExplosionModel) which implement interfaces (Enemy, Bullet, Explosion).
The View receives events when entities are c... | I'll give my two cents worth. From the problem you're describing, it seems to me that you need an abstract class that will do the operations that are common amongst all of your classes (like the get_xy, which should apply to bullet, enemy, explosion, etc.). This class is a game entity that does the basic grunt work. In... |
3,768,392 | 3,768,412 | Deleting objects from template list | I have a template list say,
List<SuperClass*>* mList;
for(int i = 0;i < mList->ElementsCount();i++)
mList->DeleteElementAtIndex(i);
in mList objects of subclasses are added.
While on deleting object from the list,
should I need to convert the object into corresponding subclasses and call the delete method?
| No, calling the delete operator on each pointer without explicit conversion is enough, but you must make sure that the destructors of the classes in the class hierarchy are declared as virtual (it's enough to mark just the one of the base class as such). In this way, the call to the destructor will be a virtual call, s... |
3,768,395 | 3,768,450 | What is the default operation of the '=' operator? | I have a class, Number, which represents a double with two digits after the dot. Before I overloaded the = operator I ran some tests and got a little confused:
int main(int argc, char **argv) {
Number *w = new Number(1.111);
Number *q = new Number(3.444);
*w = *q;
std::cout << w->GetNumber() <<std::endl... | The default operation of the assignment operator is memberwise assignment:
class Foo
{
int i;
std::string s;
Bar b;
public:
Foo& operator=(const Foo& that)
{
i = that.i;
s = that.s;
b = that.b;
return *this;
}
};
If that's exactly what you need, you don't have ... |
3,768,662 | 3,768,678 | lifetime of declaration within a loop | I have a loop as follows
while(1)
{
int i;
}
Does i get destroyed and recreated on the stack each time the loop occurs?
| Theoretically, it gets recreated. In practice, it might be kept alive and reinitalized for optimization reasons.
But from your point of view, it gets recreated, and the compiler handles the optimization (i.e, keep it at it's innermost scope, as long as it's a pod type).
|
3,768,724 | 3,768,820 | std::map clear() performance in debugger? | The attached, trivial, test program tests the performance of emptying a simple std::map. Using MSVC 2008 and 2010, the debug build will take <30seconds when executed from a command prompt but almost 3 minutes when executed from within the debugger. The call to clear() is entirely responsible for the difference. If I br... | Trying setting the environment variable _NO_DEBUG_HEAP=1 in the program's initial environment. This disables Windows' internal debug heap, which might make it harder to debug memory corruption problems.
This KB article mentions the flag, and you can infer that the default (low-fragmentation heap) is disabled if the pro... |
3,768,862 | 3,768,890 | C++ single template specialisation with multiple template parameters | Hallo!
I would like to specialise only one of two template types. E.g. template <typename A, typename B> class X should have a special implementation for a single function X<float, sometype>::someFunc().
Sample code:
main.h:
#include <iostream>
template <typename F, typename I>
class B
{
public:
void someFunc()
... | You have to provide a partial specialization of the class template B:
template <typename I>
class B<float, I>
{
public:
void someFunc();
};
template <typename I>
void B<float, I>::someFunc()
{
...
}
You can also just define someFunc inside the specialization.
However, if you only want to specialize a function... |
3,768,916 | 3,770,850 | Finding link time bottlenecks | A question I haven't seen answered that I'm finding very interesting. All the other threads seems to discuss forcing the problem, ie switching to dynamic linking or just distributing the workload. I'm more interested in actually finding out what's causing linking to take so long.
The problem is that I don't really see... | Found an excellent article series on this on http://gameangst.com/?p=46 , which goes into rather fine detail on what affects link times. At the end the author also supplies a program that he calls symbol sort ( at http://gameangst.com/?p=320 ). This is the program I was looking for, as it greatly aids in pinpointing wh... |
3,769,088 | 3,769,100 | Two classes -How to access the object of one class from another? | I have two classes, TProvider and TEncrypt. The calling application will talk to the TProvider class. The calling application will call Initialise first to obtain the handle mhProvider. I require access to this handle later when i try to perform encryption, as the TEncrypt class donot have access to this handle mhProvi... | Either you pass the handle to TEncrypt via a (constructor/method) parameter, or you make it available via a global variable. I would prefer the former, as global variables make the code harder to understand, maintain and test.
Availability may also be indirect, e.g. you pass an object to TEncrypt::Encryption() which pr... |
3,769,604 | 3,769,645 | Is calling a function as default argument okay? | Background: When working with time, I wanted to pass "now" as an argument when it is known
and ask the system if it is not yet known, so I passed it to an argument which as default calls the time-function.
This seems to work with GCC (4.1.2) as illustrated in the following code (it looks a bit weird, but examples with ... | Yes, functions are permitted as default arguments. See the example in 8.3.6/5 of the 2003 standard
|
3,769,757 | 3,773,861 | How can I draw a selection rectangle on the screen with Qt? | How can I draw a selection rectangle on my screen with Qt in X11?
I want to be able to drag a rectangle on my screen (outside of the application) and then save the whole rectangle.
Thanks in advance.
| Part of the solution will involve using the grabWindow() function of QPixmap like so:
QPixmap::grabWindow(QApplication::desktop()->winId());
Qt has an example program for this here.
There rest of the solution, drawing the area to grab, can probably be achieved by either using a full screen transparent window to render... |
3,769,781 | 3,772,377 | std::pair of references | Is it valid to have a std::pair of references ? In particular, are there issues with the assignment operator ? According to this link, there seems to be no special treatment with operator=, so default assignement operator will not be able to be generated.
I'd like to have a pair<T&, U&> and be able to assign to it anot... | No, you cannot do this reliably in C++03, because the constructor of pair takes references to T, and creating a reference to a reference is not legal in C++03.
Notice that I said "reliably". Some common compilers still in use (for GCC, I tested GCC4.1, @Charles reported GCC4.4.4) do not allow forming a reference to a ... |
3,770,397 | 3,770,473 | C/C++ header to java | Is there any good tool to generate java (+JNI support if needed) from a header file so that a C or C++ library can be used as-is. Kind of a reverse of javah. The real functionality would be in the C/C++, the Java would be only a shim on top for certain users.
I'm no expert on JNI but as far as I can see Javah forces y... | For C, you can use JNA. You do have to declare function signatures redundantly in Java, but do not have to write any glue code. JNA is very easy to use.
For C or C++, you can use SWIG. SWIG is a little more complex to use, but automatically generates Java wrappers for C++ classes. I'm enjoying it.
|
3,770,457 | 3,770,593 | What is memory fragmentation? | I've heard the term "memory fragmentation" used a few times in the context of C++ dynamic memory allocation. I've found some questions about how to deal with memory fragmentation, but can't find a direct question that deals with it itself. So:
What is memory fragmentation?
How can I tell if memory fragmentation is a... | Imagine that you have a "large" (32 bytes) expanse of free memory:
----------------------------------
| |
----------------------------------
Now, allocate some of it (5 allocations):
----------------------------------
|aaaabbccccccddeeee |
----------------------------------
... |
3,770,475 | 3,770,515 | function pointer without typedef | Is it posible to use the type of a prefiously declared function as a function pointer without using a typedef?
function declaration:
int myfunc(float);
use the function declaration by some syntax as function pointer
myfunc* ptrWithSameTypeAsMyFunc = 0;
| Not as per the 2003 standard. Yes, with the upcoming C++0x standard and MSVC 2010 and g++ 4.5:
decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0;
|
3,770,498 | 4,713,979 | Cmake compile with Frameworks on Mac OSX and treat .cpp files like .m/.mm | I'm looking for a tip to get the following to work, here is my CMakeLists.txt
# cmake_minimum_required(2.8.2)
project(boilerplate)
# base files
set(src_files
src/greet.h
src/main.cpp
)
# if on OSX, these files are needed
if(APPLE)
SET(CMAKE_EXE_LINKER_FLAGS "-framework Foundation -w")
set(src_files
${... | This turned out to be rather easy once I understood what was supposed to be happening under the hood:
set(CMAKE_CXX_FLAGS "-x objective-c++")
Which tells gcc that you want to set the language property (-x language, in man gcc) to Objective-C++.
You can also do this for individual files with:
set_source_files_propertie... |
3,770,630 | 3,770,794 | C++ - Detect whether a file is PNG or JPEG | Is there any fast way to determine if some arbitrary image file is a png file or a jpeg file or none of them?
I'm pretty sure there is some way and these files probably have some sort of their own signatures and there should be some way to distinguish them.
If possible, could you also provide the names of the correspon... | Apart from Tim Yates' suggestion of reading the magic number "by hand", the Boost GIL documentation says:
png_read_image throws std::ios_base::failure if the file is not a valid PNG file.
jpeg_read_image throws std::ios_base::failure if the file is not a valid JPEG file.
Similarly for other Boost GIL routines. If you... |
3,770,654 | 3,772,653 | Parameterized Factory & product classes that cannot be instantiated without the Factory | I'm working on implementing a Factory class along the lines of what is proposed in this response to a previous question:
Factory method implementation - C++
It's a Factory that stores a map from strings to object creation functions so I can request different types of objects from the factory by a string identifier. Al... | If I understand you correctly I think you can put some of what you want in the METADECL macro I mention in my answer you link to, ie define a static creator function that is a friend or declare it as a static method. This will make it possible for you to restrict the constructor from public use etc.
Below I try to poin... |
3,770,781 | 3,770,817 | Why is sizeof(string) == 32? | What is the overhead in the string structure that causes sizeof() to be 32 ?
| Most modern std::string implementations1 save very small strings directly on the stack in a statically sized char array instead of using dynamic heap storage. This is known as Small (or Short) String Optimisation (SSO). It allows implementations to avoid heap allocations for small string objects and improves locality o... |
3,770,842 | 3,770,873 | How to use an unknown (int-like) type as index into std::vector? | I'm using a type Id which is defined in another part of the code I'm using:
typedef int Id;
Now I am provided many objects, each of which comes with such an Id, and I would like to use the Id as index into a std::vector that stores these objects. It may look something like this:
std::vector<SomeObj*> vec(size);
std::p... | You can pass any integral type as an index for std::vector. If it doesn't match std::vector<T>::size_type (which is typically unsigned long) then the value will be implicitly converted.
|
3,770,939 | 4,955,842 | Simple frame by frame video decoder library | I'm looking for a simple c/c++ lib that would allow to extract the first frame of a video as a uchar array. And have a simple fonction to access the next one.
I know of FFMPEG but it requiere to play with packet and things like that, and i'm surprised that nowhere on the net i can find a lib that allow something like :... | Here's an example with OpenCV:
#include <cv.h>
#include <highgui.h>
int
main(int argc, char **argv)
{
cv::VideoCapture capture(argv[1]);
if (capture.grab())
{
cv::Mat_<char> frame;
capture.retrieve(frame);
//
// Convert to your byte array here
//
}
... |
3,771,208 | 3,772,234 | Reference collapsing? | By trying to solve this problem, something made me wonder. Consider the following code:
template <typename T>
struct foo
{
foo(T const& x) : data(x) {}
T data;
};
It seems that I can construct an object of type foo<T const&> without error, the hypothetical T const& const& being understood as T const&.
It seem... | In C++03, it was not legal to do the following
typedef int &ref;
ref &r = ...; // reference to reference!
This frequently causes problems for people compiling with really strict or older C++03 compilers (GCC4.1 as well as Comeau 8/4/03 do not like the above) because the Standard function object binders do not take ca... |
3,771,307 | 3,771,408 | Reopen connected datagram socket | I have a connection protocol that has been defined by our customer. Data are sent between two linux computers using UDP and TCP protocols. The IP addresses and ports are fixed on startup.
We are sending messages at 200 Hz and I have been using connect to save some time on the transmissions.
My problem is that if there ... | The underlying socket layer might hold the port & IP address still open, even after your call to close. Try some of the following:
do a sleep(10) (or more) between the close and the call to doConnect again
configure the sockets using setsockopt with the SO_LINGER set to off
This actually happens more commonly with TC... |
3,771,406 | 3,771,766 | call to C and c++ both in a single java program | hi all is it possible to declare to native methods in java so that one method is defined in c and other method is defined in c++.m getting confusion in it . please help me in this.
| Yes. As long as the interface uses the standard C calling convention, Java doesn't really care in which language it's implemented. That means you have to surround the declarations in an extern "C" block if you happen to be writing C++:
#include <jni.h>
#ifdef __cplusplus
extern "C" {
JNIEXPORT jstring MyNativeMethod(JN... |
3,771,449 | 3,771,618 | STL Map Value Constructors | I have a class X that I would like to put into an STL map of type std::map. An STL map needs to have X stored in memory somewhere so I'm looking for an efficient (run time and memory) way to create X and store it in the map.
I noticed that the following code where x is an object of type X and stlMap is a map of type ... | Try stlMap.insert( map<string, X>::value_type("test", x) ):
#include <iostream>
#include <string>
#include <map>
using namespace std;
class X
{
public:
X() { cout << "X default constructor" << endl; }
~X() { cout << "X destructor" << endl; }
X( const X& other ) { cout << "X copy constructor" << endl; }
X& operator=( ... |
3,771,467 | 3,771,526 | Is this use of nested vector/multimap/map okay? | I am looking for the perfect data structure for the following scenario:
I have an index i, and for each one I need to support the following operation 1: Quickly look up its Foo objects (see below), each of which is associated with a double value.
So I did this:
struct Foo {
int a, b, c;
};
typedef std::map<Foo, doub... | To answer the headline question: yes, nesting STL containers is perfectly fine. Depending on your usage profile, this could result in excessive copying behind the scenes though. A better option might be to wrap the contents of all but top-level container using Boost::shared_ptr, so that container housekeeping does no... |
3,771,643 | 3,771,681 | C++: mixture between vector and list: something like std::rope? | When storing a bunch of items and I don't need random access to the container, I am using an std::list which is mostly fine. However, sometimes (esp. when I just push back entries to the back and never delete somewhere in the middle), I wish I had some structure with better performance for adding entries.
std::vector i... | Have you considered using std::deque? Its elements are not stored contiguously but it does allow random access to elements; if you are only inserting elements at the beginning or end of the sequence, it may give better performance than a std::vector.
|
3,771,654 | 3,799,197 | Clickable menu item with submenu in Qt | I am writing in Qt 4.6. I am wondering if it's possible to achieve such a menu item, that it's possible to be triggered, but also has a submenu. Clicking it triggers associated action, hovering it causes submenu to appear.
| This behavior is a bit confusing, but i am trying to develop a UI with as little clicking as possible. Although a bit unexpected, this behavior makes it a bit faster to use when you get used to it.
I haven't wrote that in my previous message, but i am writing in c++, and i have no idea about python... Anyway i managed ... |
3,771,754 | 3,771,881 | What is an efficient way of back-tracking in greedy best search algorithm? | I coded a greedy search algorithm , but it goes to an infinite loop as its not able to back - track , and reach the final state . How can a back-tracking be done in C++ in the most optimal way !
while(!f1.eof() )
{
f1>>temp1>>time;
A[i].loc_name=temp1;
A[i].time_taken=t... | int algo(int value, int stopValue, list<int> & answer)
{
if(value == stopValue)
{
return 0;
}
if(value > stopValue)
{
return 1;
}
if(algo(value+2, stopValue) == 0)
{
answer.push_back(2);
return 0;
}
if(algo(value+1, stopValue) == 0)
{
... |
3,771,784 | 3,772,621 | Struct containing std::string being passed to lua | I have working C++ code using swig which creates a struct, passes it to lua (essentially by reference), and allows manipulation of the struct such that the changes made in the lua code remain once I've returned to the C++ function. This all works fine until I add a std::string to the struct, as shown here:
struct stuff... | You need to add %include <std_string.i> to your SWIG module. Otherwise, it does not know how to map a Lua string to an C++ std::string.
A common problem that people encounter is that of classes/structures containing a std::string. This can be overcome by defining a typemap. For example:
%module example
%include "std... |
3,771,975 | 3,772,019 | Learning C++ from PHP | I have PHP background and want to start learning C++. How should I proceed?
| Start at the start. The similarities between PHP and C++ will take about half an hour to get through ("this is an object, this is a loop, ..."), and there are subtle differences which will kill you if you're not paying attention during that half hour. Learning C++ will take months to years, depending what you mean by "... |
3,771,976 | 3,772,975 | C++: automatic initialization | I find it sometimes annoying that I have to initialise all POD-types manually. E.g.
struct A {
int x;
/* other stuff ... */
A() : x(0) /*...*/ {}
A(/*..*/) : x(0) /*...*/ {}
};
I don't like this for several reasons:
I have to redo this in every constructor.
The initial value is at a different place t... | There is a proposal for C++0x which allows this:
struct A {
int x = 42;
};
That is exactly what I want.
If this proposal is not making it into the final version, the possibility of delegating constructors is another way of at least avoiding to recode the initialization in every single constructor (and at the same ... |
3,772,120 | 3,772,188 | Howto call an unmanaged C++ function with a std::vector as parameter from C#? | I have a C# front end and a C++ backend for performance reasons.
Now I would like to call a C++ function like for example:
void findNeighbors(Point p, std::vector<Point> &neighbors, double maxDist);
What I'd like to have is a C# wrapper function like:
List<Point> FindNeigbors(Point p, double maxDist);
I could pass a ... | The best solution here is to write a wrapper function in C which is limited to non-C++ classes. Non-trivial C++ classes are essentially unmarshable via the PInvoke layer [1]. Instead have the wrapper function use a more traditional C signature which is easy to PInvoke against
void findNeigborsWrapper(
Point p,
do... |
3,772,233 | 3,772,400 | Win32 SetForegroundWindow unreliable | I have a rather complex series of applications which depend on the ability to switch applications in the foreground.
My problem is, every 5 or 6 times of switching the applications in the foreground, it simply fails to bring the application forward. GetLastError does not report any issues. Often times I see the correct... | Your AttachThreadInput() hack is (I think) a known way to defeat the focus stealing counter-measures in Windows. You are using the wrong handle though, you want to attach to the thread that currently has the focus. Which won't be hApp, you wouldn't need this code otherwise.
Use GetForegroundWindow() to get the hand... |
3,772,331 | 3,772,392 | How does this work? copying anything into an array of bytes (chars) | struct MyRect
{
int x, y, cx, cy;
char name[100];
};
int main()
{
MyRect mr;
mr.x = 100;
mr.y = 150;
mr.cx = 600;
mr.cy = 50;
strcpy(mr.name, "Rectangle1");
MyRect* ptr;
{
unsigned char bytes[256];
memcpy(bytes, &mr, 256);
ptr = (MyRect*)bytes;
}
... | ptr is still pointing to the address of bytes. Or, what was once called bytes. Even though you've put bytes into its own block and the variable is semantically inaccessible outside of that block, the memory sticks around unmodified until the function exits. This is a typical implementation technique, but is undefined b... |
3,772,431 | 3,772,560 | Runtime Error : RunTime Error : map/set iterators incompatible | void Manager::Simulate(Military* military, Shalishut* shalishut,char* args[]){
Simulation* simulation = Simulation::GetInstance();
Time* time = Time::GetInstance();
multimap<int,Task*>::const_iterator itTasks;
itTasks = simulation->GetTasks().begin();
while(itTasks != simulation->GetTasks().end()){
... | Does GetTasks() create a new map/set when it is called, and returns that? Or does it return a copy of a set where a reference would be appropriate?
If this is the case, then each call to GetTasks() returns a new object that is independent of previously returned objects. Comparing an iterator of one of these objects wit... |
3,772,640 | 3,772,712 | How to do binary search in a std::multiset without constructing a key_type object? | I have a container like this:
// Sort functor
struct SortByTime :
std::binary_function<const TimeSortableData &, const TimeSortableData &, bool>
{
bool operator()(const TimeSortableData & a, const TimeSortableData & b) const
{
return a.GetTime() < b.GetTime();
}
};
// Container that sorts by time... | I suppose that if your keys are so expensive to construct that you worry about creating a temporary dummy key, you can always change your code to use an std::multimap instead. Let the key be something cheap to construct, such as an integer or time_t or whatever GetTime() returns, and then the data_type could be the la... |
3,772,664 | 3,773,636 | Intersection of two `std::map`s | Given that I have two std::maps, say:
map<int, double> A;
map<int, double> B;
I'd like to get the intersection of the two maps, something of the form:
map<int, pair<double,double> > C;
Where the keys are the values in both A and B and the value is a pair of the values from A and B respectively.
Is there a clean way u... | #include <map>
#include <utility>
template <typename KeyType, typename LeftValue, typename RightValue>
std::map<KeyType, std::pair<LeftValue, RightValue>>
IntersectMaps(const std::map<KeyType, LeftValue>& left,
const std::map<KeyType, RightValue>& right) {
std::map<KeyType, std::pair<LeftValue, Right... |
3,772,701 | 3,772,726 | Parameters in Visual Studio c++ 2010 | I just installed Visual Studio C++ 2010 Express (BTW. great ide). I have to make simple application, but I will open it from command prompt, and I need using parameters. So my question is: how to using parameters in Visual C++ .NET 2010 Express? I need one string and some int. It's special creator to do this or I must ... | To debug your program with command line arguments, use Project + Properties, Debugging, Command Arguments setting.
Click around some more to get familiar with what's there, you'll need it sooner or later. Press F1 if things sound mysterious.
|
3,772,702 | 3,772,727 | error: using typedef-name after class | I can't figure out what the actual problem is with this.
typedef struct _actor
{
...
} _actor, Actor;
class Actor
{
...
};
I get this weird error message actor.cpp:31: error: using typedef-name ‘Actor’ after ‘class’.
Any idea what I did wrong here? Thank you :)
| You are not allowed to define the symbol Actor more than once. The typedef statement already defines the symbol Actor as an alias for struct _actor before you attempt to declare a class with the same name.
I'm guessing you're using the gcc compiler. I get the following errors when I compile with gcc:
../src/main.cpp:11... |
3,772,867 | 3,772,980 | Lambda capture as const reference? | Is it possible to capture by const reference in a lambda expression?
I want the assignment marked below to fail, for example:
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string strings[] =
{
"hello",
"world"
};
static const size_t num_strings = sizeof(stri... | const isn't in the grammar for captures as of n3092:
capture:
identifier
& identifier
this
The text only mention capture-by-copy and capture-by-reference and doesn't mention any sort of const-ness.
Feels like an oversight to me, but I haven't followed the standardization process very closely.
|
3,772,948 | 3,773,198 | Disable accelerator table items in MFC | I need to temporarily disable a few items from an accelerator table when the input focus is on a CEdit field.
My application has some commands associated with keyboard keys (A, S, D, etc.) and I need to disable those while the user is entering text in the field.
| You could try CopyAcceleratorTable to get the ARRAY of ACCEL structures then edit out the ones you don't want, Call DEstroyAcceleratorTable on the current table. Then use CreateAcceleratorTable to create the new table with the edited accelerator table.
Edit: This link may be useful.
|
3,773,015 | 3,773,137 | Using "unique()" on a vector of vectors in C++ | I hope this is not a duplicate question, but if it is, feel free to point me in the right direction.
I have a vector<vector<int> >.
Is it possible to use unique() on this? Something like:
vector<vector<int> > myvec;
//blah blah do something to myvec
vector<vector<int> >::interator it = unique(myvec.begin(), myvec.end()... | Yes, as long as your vector is sorted. See unique () STL documentation for details.
Here is an example of usage:
#include <vector>
#include <string>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
int main ()
{
vector< vector<string> > v;
v.push_back (vector<string> ());
v... |
3,773,047 | 3,773,077 | Accepting nested variadic class templates as arguments to function template | I'm trying to make a function template that will accept two (or more) of the nested variadic class templates listed below, as arguments, and put them into another data structure that will accept different types (pair or tuple is what I'll most likely use). Here are the classes and subclasses, along with the usage of m... | This will not work because Entity<Args>::InnerEntity is a non-deduced context. Means that ArgsA... and ArgsAInner... cannot be deduced, likewise for the other parameter. This is because before the compiler can deduce Args, it has to know what type InnerEntity is a member of, but to know that, it has to deduce Args.
Yo... |
3,773,378 | 3,854,954 | Passing const char* as template argument | Why can't you pass literal strings in here? I made it work with a very slight workaround.
template<const char* ptr> struct lols {
lols() : i(ptr) {}
std::string i;
};
class file {
public:
static const char arg[];
};
decltype(file::arg) file::arg = __FILE__;
// Getting the right type declaration for this was... | Because this would not be a useful utility. Since they are not of the allowed form of a template argument, it currently does not work.
Let's assume they work. Because they are not required to have the same address for the same value used, you will get different instantiations even though you have the same string liter... |
3,773,385 | 3,773,838 | What to use for typedef struct array in c++ | I have been implementing a visual debugger in my application using another bit of source code. I ran into an issue when I stumbled across them using this..
struct DebugVertex
{
gkVector3 v;
unsigned int color;
};
typedef utArray<DebugVertex> Buffer;
I found the free library that they are using for utArray, h... | From all standard sequence STL containers probably vector & deque are closest to an array (at least to me, I associate random access with arrays...).
The only problem you would have is that STL containers have different naming conventions for the internal typedefs like: iterator, pointer, value type & so on. If you rea... |
3,773,396 | 3,773,458 | Declare variables at top of function or in separate scopes? | Which is preferred, method 1 or method 2?
Method 1:
LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
GetClientRect(hwnd, &rc);
... | Variables should be declared as locally as possible.
Declaring variables "at the top of the function" is always a disastrously bad practice. Even in C89/90 language, where variables can only be declared at the beginning of the block, it is better to declare them as locally as possible, i.e. at the beginning of smallest... |
3,773,568 | 3,773,682 | Any way to resolve C4772 errors without having to register DLLs? | I am maintaining a VS2010 project which has a number of cross-referenced COM libraries. I am trying to configure the project in such a way that it is buildable from a random workstation which has VS2010 installed. The workstation could be both 32 and 64 bit, so if I configure project to "register output", the build wil... | Try import the referenced A.tlb first, or list it in the import of B.tlb using the include() option.
Only #import the parts of the interface you plan to use if you can avoid bringing in other references unnecessarily.
|
3,773,786 | 3,773,825 | Get event viewer logs with win api in c++ | My application need to save event viewer logs to a specified directory and it has to be done with win api. Application and System logs are required.
EDIT: EvtExportLog - I found out that I can't use this function because minimal requirements are Win Server 2008, and I need this to work on Win Server 2000 and Win Server... | You can enumerate the available channels on the system using EvtOpenChannelEnum, EvtNextChannelPath and EvtClose (documentation). These APIs (EvtNextChannelPath specifically) will return paths in an appropriate format for EvtExportLog.
|
3,773,814 | 3,774,265 | CUDA Project Structure | The template and cppIntegration examples in the CUDA SDK (version 3.1) use Externs to link function calls from the host code to the device code.
However, Tom's comment here indicates that the usage of extern is deprecated.
If this the case, what's the correct structure for a CUDA project such as the template example or... | Depends what your host code is. If you end up mixing C and C++ you still need the externs. For details see this guide.
Update: the content from the above link has been moved [here] (https://isocpp.org/wiki/faq/mixing-c-and-cpp).
|
3,774,108 | 3,774,150 | Python vs Lua for embedded scripting/text processing engine | For a project I'm currently working on, I'm looking to embed a scripting engine into my C++ code to allow for some extensibility down the line. The application will require a fair amount of text processing and the use of regular expressions within these scripts.
I know Lua is generally the industry darling when it com... | if you need specifically what is commonly known as 'regular expressions' (which aren't regular at all), then you have two choices:
go with Python. it's included regexp is similar enough to Perl's and sed/grep
use Lua and an external PCRE library
if, on the other hand, you need any good pattern matching, you can stay... |
3,774,204 | 3,774,277 | difference between interface inheritance and implementation inheritance | I found those two terms in the book of Meyers, but what is the difference?
| Interface inheritance is public inheritance, while implementation inheritance is private inheritance.
If class B publicly inherits from A, B is an A: it inherits the whole interface of A, and a (reference/pointer to) a B object can be automatically be upcasted to A, and used wherever an object of A is expected. However... |
3,774,216 | 3,774,232 | Visual C++ 2008 - breakpoint cannot be hit | I am trying to dissect a legacy application through debugging, but I can't get the breakpoint to hit in certain places of the application. The application has a c# GUI frontend and a c++ backend.
I am trying to put a breakpoint in a c++ project of the solution. There are a couple of c++ projects, but I cannot set a br... | It sounds like you need to enable unmanaged code debugging. Try the follownig
Right click on the C# project and select Properties
Go to the Debug tab
Check "Enable Unmanaged Code Debugging"
|
3,774,316 | 3,775,045 | C++ unhandled exceptions | Does C++ offer a way to 'show' something visual if an unhandled exception occurs?
What I want to do is to make something like assert(unhandled exception.msg()) if it actually happens (like in the following sample):
#include <stdexcept>
void foo() {
throw std::runtime_error("Message!");
}
int main() {
foo();
}
I ... | There's no way specified by the standard to actually display the message of the uncaught exception. However, on many platforms, it is possible anyway. On Windows, you can use SetUnhandledExceptionFilter and pull out the C++ exception information. With g++ (appropriate versions of anyway), the terminate handler can acce... |
3,774,346 | 3,774,532 | Which is better for local IPC, POSIX message queues (mqueues) or Unix domain (local) sockets? | Is it better to use POSIX message queues or Unix domain sockets for local IPC communication?
I have worked with Unix sockets between machines (not domain) and I remember that making and breaking the connection would cause sockets to linger awhile before they finally went away. Moreover, if you wanted a "reliable" excha... | UNIX domain sockets do not have to "linger" in a TIME_WAIT-like status, since that wait time is used in case there are stray packets from the connection still wandering around the Internet. The concern doesn't apply locally.
UNIX domain sockets can be either SOCK_STREAM (like TCP) or SOCK_DGRAM (like UDP), with the ad... |
3,774,408 | 3,774,455 | How to add a 'new' class to a vector | I am writing a server in C++ and created a class called client to store information about connected clients. I wanted to store the clients in a vector. I have a call
clients.push_back(new client(addr,fd));
to add a client object to the vector clients. I get the following error on compile
server.cpp:67: error: no matc... | You almost certainly just want to get rid of the new so it's:
clients.push_back(client(addr, fd));
In Java you have to explicitly new all your objects, but in C++ you not only don't need to, but generally want to avoid it when/if at all reasonable.
|
3,774,647 | 3,774,844 | Instantiating an ActiveX Object | I have imported an ActiveX library into my project in Visual Studio 2008 using:
#import "TeeChart8.ocx" named_guids
Now I would like to create objects exposed by the ActiveX library. However, I am having trouble understanding the API.
There are two files that were created after I built the project with the #import, a... | When it's a simple COM object, you can use the following (assuming a coclass named TChart to go with the interface named ITChart):
ITChartPtr chart(__uuidof(TChart));
For more information on using the ITChartPtr type defined by the _COM_SMARTPTR_TYPEDEF macro in the .tlh file generated by the #import statement, see co... |
3,774,825 | 3,775,517 | eclipse compiling error | I just installed cygwin and eclipse on my win7 x64 machine, and after importing my code from svn, I get this weird error:
**** Build of configuration Default for project platform ****
make all
g++ -O2 -g -Wall -fmessage-length=0 -c -o platform.o platform.cpp
process_begin: CreateProcess(C:\cygwin\bin\g++.exe, g++ -... | C:\cygwin\bin\g++.exe is a Cygwin symbolic link pointing to either g++-3.exe or g++-4.exe. Native Windows functions such as CreateProcess() don't understand Cygwin symbolic links though. Hence you need to configure Eclipse to execute g++-3.exe or g++-4.exe directly.
|
3,774,858 | 3,774,877 | Artificially Limit C/C++ Memory Usage | Is there any way to easily limit a C/C++ application to a specified amount of memory (30 mb or so)? Eg: if my application tries to complete load a 50mb file into memory it will die/print a message and quit/etc.
Admittedly I can just constantly check the memory usage for the application, but it would be a bit easier if... | Read the manual page for ulimit on unix systems. There is a shell builtin you can invoke before launching your executable or (in section 3 of the manual) an API call of the same name.
|
3,774,931 | 3,774,952 | "Unresolved External Symbol" errors when creating object in C++ | I'm a pretty seasoned programmer but I'm just now diving into C++ and it's... well... more difficult than PHP and Python. I keep having unresolved external errors when trying to create an object from some classes. It's broken up into multiple headers and files but here is a basic idea from one of my classes:
die.h:
#if... | You declared a constructor for Die but never defined it.
Also, you almost certainly want throwDie to be virtual if you intend to override its behavior in derived classes, and you should never use using namespace std; in a header file (and many people, including me, would argue that you shouldn't use it at file-scope at... |
3,775,147 | 4,009,490 | Is it possible to do a reduction on an array with openmp? | Does OpenMP natively support reduction of a variable that represents an array?
This would work something like the following...
float* a = (float*) calloc(4*sizeof(float));
omp_set_num_threads(13);
#pragma omp parallel reduction(+:a)
for(i=0;i<4;i++){
a[i] += 1; // Thread-local copy of a incremented by something in... | Only in Fortran in OpenMP 3.0, and probably only with certain compilers.
See the last example (Example 3) on:
http://wikis.sun.com/display/openmp/Fortran+Allocatable+Arrays
|
3,775,229 | 3,778,624 | Is there a way to have a process created by CreateProcess open within another window? | I want to be able to open a GUI application using CreateProcess in a main process and have the GUI display in a window I create from within the main process. Does anyone know how to achive this? Thanks!
| If you are in control of both applications then yes.
This is how screen savers display in the screen saver control panel - the control panel passed the dialogs window on the command line, and the .scr file - which is just a simple exe - creates its window as a child using the given hwnd as its parent.
Capturing a previ... |
3,775,414 | 3,775,417 | Assignment of data-member in read-only structure, class in STL set | The minimal example of the problem I'm having is reproduced below:
#include <set>
using namespace std;
class foo {
public:
int value, x;
foo(const int & in_v) {
value = in_v;
x = 0;
}
bool operator<(const foo & rhs) const {
return value < rhs.value;
}
};
int main() {
foo y(3);
set<foo> F;
F.i... | Objects in a set are immutable; if you want to modify an object, you need to:
make a copy of the object from the set,
modify the copy,
remove the original object from the set, and
insert the copy into the set
It will look something like this:
std::set<int> s;
s.insert(1);
int x = *s.begin(); // (1)
x+= 1; ... |
3,775,427 | 3,775,524 | deleting object pointer referring by two pointers | I have an object say.
ClassA *obj1 = new ClassA;
ClassA *ptr1 = obj1;
ClassA *ptr2 = obj1;
When I do delete ptr1;, will it affect ptr2? If so what can be the correct solution for this?
| (assuming obj2 is supposed to be obj1)
ClassA *x defines a pointer that can point to objects of type ClassA. A pointer isn't an object itself.
new ClassA allocates (and constructs) an actual object of type ClassA.
So the line Class A *obj1 = new ClassA; defines a pointer obj1 and then sets it to point to a newly alloc... |
3,775,504 | 3,775,519 | How is the debug information organized and what does it contain? | How is the debug information organized in a compiled C/C++ program?
What does it contain?
How is the debug information used by the debugger, e.g. gdb, and how can I read the debug information better than nm or objdump?
| The debugging information depends on the operating system - gdb uses whatever the native format is. On many UNIX-like systems, debugging information is stored in DWARF format. You can use libdwarf and dwarfdump to examine this information.
EDIT: On Linux readelf -w a.out will print all DWARF debug info contained in t... |
3,775,744 | 3,775,778 | GCC Tree STL data containers |
Possible Duplicate:
remove_if equivalent for std::map
Yesterday i wrote a program, which use multiset for storing elements like this:
std::multiset < boost::shared_ptr < CEntity > > m_Entities;
Then i try to use standard algorithm remove_if like this:
std::remove_if(m_Entities.begin, m_Entities.end(), MarkedForDest... | You can not use std::remove_if algorithm on an associative container. You need to a write a for loop and use the erase method to remove the elements. See this similar question remove_if equivalent for std::map for more details.
|
3,775,887 | 3,775,966 | Speed difference between global and object variable | Is it faster to access a global or object variable?
In C++, I'm referring to the difference between
::foo
and
this->foo
In x86 assembler, this basically translates to
mov eax, offset foo
vs
mov eax, dword ptr[edx+foo]
All data in both cases is expected to be in cache.
(I know the difference if any will be tiny, and... | You need to test and time both.
However, do this knowing that you've made other decisions in your app that will have a greater performance impact by several orders of magnitude than this.
To human eyes the Global is faster to access, however what the compiler decides to put where, and how the processor decides to cache... |
3,775,965 | 3,779,616 | Bitwise Manipulation or Bitwise Programming | I know the concepts of bit-wise operators, bit manipulation, 2's complement etc. But when it comes to solving something using bit manipulation it does not strike me. I takes me time to wrap my head around them.
I thought it would help if I looked at some questions regarding bit operators/bit manipulation but it left m... | Answers given so far are nowhere near useful. But the link given by Naveen helped me a bit. Quite a lot of examples given here. I am trying to learn from them. Maybe it'll help others.
Bit Hacks
UPDATE: I have been going through the examples given in the link above. They were good.
Also I stumbled on - Resource for B... |
3,776,108 | 3,776,161 | Calling unmanaged C++ Class DLL from C# | How can I call unmanaged C++ Class DLL from C#?
| You may want to create a managed C++ wrapper for that class, compile it with /clr (common language runtime support) and then you can use it in C#.
You may also want to look at PInvoke.
|
3,776,159 | 3,792,951 | Hangs on CreateDialogIndirect in CWinThread derived class | I'm new to multithreading.
I created a class inherit from CWinThread called CMyUIThread, and also a dialog called CMyInfoDlg which has a text and a progress ctrl. I would to show modeless dialog in new created thread. Below is partial code:
BOOL CMyUIThread::InitInstance()
{
// TODO: perform and per-thread initializat... | Best advice: check the call stack. You can get the public Windows symbols from MS servers, and see what's hanging specifically. Best guess is maybe a messaging deadlock, or perhaps something to do with the CWnd*. Gotta look at the call stack, though, and see what's really pending.
|
3,776,272 | 3,776,307 | EnableMenuItem Function Is not Working With the parameter MF_GRAYED | Have created a ATL COM project through which I am inserting Menu Items to The rightclick menu like this:
STDMETHODIMP CSimpleShlExt::QueryContextMenu (
HMENU hmenu, UINT uMenuIndex, UINT uidFirstCmd,
UINT uidLastCmd, UINT uFlags )
{
gHMenu=hmenu;
UINT uCmdID = uidFirs... | Try this:
EnableMenuItem(gHMenu,ITEM_ID,MF_DISABLED | MF_GRAYED);
ITEM_ID should be the resource ID of the menu item.
Or:
EnableMenuItem(gHMenu,ITEM_POSITION,MF_DISABLED | MF_GRAYED | MF_BYPOSITION);
where ITEM_POSITION is the zero-indexed position of the menu item.
Note that after calling EnableMenuItem, you may nee... |
3,776,482 | 3,777,727 | Qt Dependency Visualizer | I have a lot of classes which interact with other classes through signal&slot mechanism, composition, inheratance etc.
I wonder, is there any tool which visualizes(such as:UML-like diagrams) dependencies between classes in source code especially for Qt based codes?
Thanks.
| One such tool is codedrawer for C++(http://www.codedrawer.com/).It is not specifically for QT though, but I hope it should work as per your need. Actually I am myself looking our for tools which are similar in nature, adding the link for followup just in case some good stuff shows up.
Code refactoring
|
3,776,485 | 3,776,624 | Marshal C++ int array to C# | I would like to marshal an array of ints from C++ to C#. I have an unmanaged C++ dll which contains:
DLL_EXPORT int* fnwrapper_intarr()
{
int* test = new int[3];
test[0] = 1;
test[1] = 2;
test[2] = 3;
return test;
}
with declaration in header extern "C" DLL_EXPORT int* fnwrapper_intarr();
I am th... |
[DllImport("wrapper_demo_d.dll")]
public static extern IntPtr fnwrapper_intarr();
IntPtr ptr = fnwrapper_intarr();
int[] result = new int[3];
Marshal.Copy(ptr, result, 0, 3);
You need also to write Release function in unmanaged Dll, which deletes pointer created by fnwrapper_intarr. This function must accept IntPtr ... |
3,776,492 | 3,777,718 | How to utilize SECURITY_DESCRIPTOR in InitializeObjectAttributes() | Could someone provide me an example of utilizing SECURITY_DESCRIPTOR in InitializeObjectAttributes()? I plan to use them with NtCreateKey(). I couldn't find any example on the Internet.
Thanks in advance.
| The last parameter of InitializeObjectAttributes() can be just well documented SECURITY_DESCRIPTOR. You can use for example ConvertStringSecurityDescriptorToSecurityDescriptor to convert Security Descriptor String Format to SECURITY_DESCRIPTOR. You can create SECURITY_DESCRIPTOR without usage of security descriptor def... |
3,776,510 | 3,776,599 | Windows C++ App crash | I have a Windows C++ app that crashes on user computers from time to time. I didnt write the app and it doesnt have its own logging. Is there a tool / utility I could use that is able to log some useful information when the application exits (e.g. the file and line number where the crash occurred)? The end user's compo... |
"the file and line number where the crash occurred"
That would be possible only if the code were built with debug information included. If your users are prepared to install VC++ Express, they could attach to the process with its debugger after the crash, but without the source they will simply see assembler code, a... |
3,777,007 | 3,777,039 | Three exception-handling Versions, which one is preferable? | I'm implementing a Zip-Wrapper (zlib minizip) and asking myself how i should
handle exceptions properly. I'm thinking of three versions. Which one would
you prefer, or is there a version i didn't thought about?
The task of the function Install is to get a Zip-File from a Web-Server,
unpack its content and delete the do... | None of the three. Use RAII:
class FileGuard {
public:
FileGurad(const std::string & filePath)
: m_FilePath( filePath )
{}
~FileGuard() {
delete(m_FilePath); // must not throw an exception
}
private:
std::string m_FilePath;
};
Usage:
void Install() {
guard FileGuard(getFile("upd.zi... |
3,777,031 | 3,777,051 | What prevents C++ from being a strict superset of C? |
Possible Duplicate:
“C subset of C++” -> Where not ? examples ?
I'm aware that C++ is not a strict superset of C. What language features prevent C++ from being a superset of C?
| The elephant in the room: the following is valid C but not valid C++.
int typename = 1;
Substitute your favorite C++ reserved word.
|
3,777,076 | 3,777,194 | Solve Fibonacci Sequence Recursively returning void in function | My professor has asked us to write a program that uses recursion to solve a fibonacci sequence. This is all pretty normal, but he's asked us to make our function return void. I've been working at this for a few days now and can't find a way to do this.
I have:
void fibonacci(double *n,double *x,double *y,double *resu... | Since this is a homework, I won't provide working code, although a few points here:
Using a reference is simpler than using pointers
You really need to increase the result, not set it to 0 or 1. Therefore you need to pass to first function call by reference an int with assigned value of 0.
Consider the formula: f(n) =... |
3,777,121 | 3,777,243 | How to access Windows shell context menu items? | In Windows Explorer, you right click on a file, a context menu shows up which contains built-in items like 'Send to...' and/or 3rd party actions such as 'zip file with Winzip'. My question are:
How to obtain the full list of available menu items for a specific file?
For each menu item, how to get the caption?
How to i... | The key to obtain the Shell Context menu is use the IContextMenu interface.
check this great article Shell context menu support for more details.
UPDATE
for delphi examples you can see the JclShell unit from the JEDI JCL (check the DisplayContextMenu function) and the ShellCtrls unit included in the samples folder of ... |
3,777,184 | 3,777,262 | Rotate 2D rectangular array in-place | I have an non-square array like this:
const int dim1 = 3, dim2 = 4;
int array[12] = { 1, 2, 3,
4, 5, 6,
7, 8, 9,
10,11,12};
and I need to convert it to:
{3,6,9,12,
2,5,8,11,
1,4,7,10}
that is, rotate/shuffle it counter-clockwise (or clockwise, the algorithm shou... | You can transpose the matrix in-place (see http://en.wikipedia.org/wiki/In-place_matrix_transposition) and then reverse the rows which is trivial.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.