question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,495,977 | 6,496,103 | What legitimate reasons exist to overload the unary operator&? | Okay, I've been inspired to do some head punching. Seems like overloading operator& leads to not a small amount of pain.
What legitimate cases exist for overloading it?
(Can't say I've ever done that....)
| I seem to remember something like a smart pointer class which overrode operator& because it wanted to return the address of the contained pointer rather than the address of the smart pointer object. Can't remember where I saw it or whether it seemed like a good idea at the time.
Aha, remembered: Microsoft's CComPtr.
Ed... |
6,496,242 | 6,496,393 | Mutexes in multithread Linux application | Could you help me to understand how to use mutexes in multithread Linux application, where:
during data writing it is need to lock variable on write and read
during data reading from the variable it is need to lock it on write.
So it is possible to read simultaneously, but writing opertion is a single opertaion in th... | You're asking about something that is a bit higher level than mutexes. A mutex is a simple, low-level device. When you lock a thread with a mutex, the CPU is either executing code in the thread that obtained the lock or it is executing some other process entirely. In other words, the mutex has locked out all other thr... |
6,496,304 | 6,496,372 | Errors while trying to use matlab engine from VC++ | I'm Using MATLAB R2010a
I used this this tutorial in order to call matlab function from C++ and i did every thing said in the tutorial and i compiled the project successfully but when i tried to run it, it requires many dlls which i added them in windows 7 system32:
icudt24l.dll
icuin24.dll
icuio24.dll
icuuc24.dll
icu... | You don't need to put those files in the System32 directory. All you need to do is add the path
C:\Program Files\MATLAB\R2011a\bin\win64
to your system path (google how to do this for your version of windows -- it is subtly different between XP and Vista/7). If you aren't using the 64bit version of matlab, modify the ... |
6,496,320 | 6,496,455 | What does this colon do in an enum declaration? | I did a search for this question thinking that somebody must have asked it before. I did not turn up any results, so if it has been, please post the link and feel free to close the question.
I ran across this code in EASTL:
enum : size_type { // size_type = size_t
npos = (size_t... | This is a Microsoft extension that lets you choose the base type of the enum values. For example, this lets you specify that values are unsigned (Microsoft's compilers usually choose signed by default) or that they only occupy 8 or 16 bits (Microsoft normally defaults to 32 bits).
The syntax is documented here: http://... |
6,496,349 | 6,496,431 | C++/CLI Dll with C# Connection problem | I have 3 projects in one solution.
I have :
a native C++ dll,
a C# Winform,
and a proxy C++/CLI without pure mode to do the link between the 2 others projects (and use the native function in the managed code in C#)
So when I launch the application all work. But when I push the button "Generer" in my winform wich exec... | One reason can be you are trying to load a native 32-bit dll in a 64-bit process. Make sure you have platform target set to x86 in your app to force your application to run inside WoW64.
|
6,496,499 | 6,496,654 | How do I operate on objects in a list based on their run time type, not their base type? | In my program I have a base Object class and a vector. I have an operation that I want to perform on each Object*, however the operation is dependent on the Object*'s most derived class. Therefore, I use the visitor pattern. However, I've found that the visitor pattern leads to a high amount of coupling; whenever I add... | I'm going to read between the lines and guess that your most derived objects have member functions that are unique to them and don't exist in any of the other derived objects, which is why you don't want to add them to the base class.
You can use dynamic_cast to see if a pointer belongs to the most derived class, then ... |
6,496,524 | 6,496,558 | Hide a C++ code block from Intellisense | In order to work around some Intellisense deficiencies in MSVC++ 2010, I would like to "hide" some code block from Intellisense, but not from the compiler. For example:
#ifndef INTELLISENSE
void foo(); // compiled, but skipped by Intellisense
#endif
I'm looking for the exact name of this INTELLISENSE macro, if such a ... | The proper macro for VC++ 2010 is __INTELLISENSE__, as described in this blog article: Troubleshooting Tips for IntelliSense Slowness
|
6,496,545 | 6,496,703 | trivial vs. standard layout vs. POD | In layman's terms, what's the difference between trivial types, standard layout types and PODs?
Specifically, I want to determine whether new T is different from new T() for any template parameter T. Which of the type traits is_trivial, is_standard_layout and is_pod should I choose?
(As a side question, can any of thes... | I don't think it can be done in truly layman's terms, at least without a lot of extra explanation. One important point is static vs. dynamic initialization, but explaining that to a layman would be several pages in itself...
PODs were (mis-)defined in C++98. There are really two separate intents involved, neither expre... |
6,496,628 | 6,497,920 | Is it possible for STL set to be faster than STL multiset for preventing duplicate entries? | Good afternoon, We are currently using STL multimap and STL set to cache memory mapped file regions. We would like our cache to have only unique entries. We wondering if there is a way for STL set and STL map to be faster than STL multiset and STL multimap for preventing duplicate entries.
We are using the follow... | There's a lot of stuff to read here, and optimization of the complex container types is a tricky problem. I've spent a fair bit of time working on similar problems, so I'll try to point out some things that have helped me.
Firstly, the usual way to make your code faster is don't use binary trees when vectors will do. T... |
6,496,629 | 6,497,944 | How should I iterate through a binary file in c++? | TL;DR
What would be a good way, in C++ and using STL idioms, to iterate through a binary file to read, transform, and then again write out the data? The files can be pretty large (several hundred MB) so I don't want to load the entire file into memory at one time.
More context
I am trying to improve a utility which pe... | I'd handle this by overloading operator>> and operator<< for your Record type:
struct Record {
struct header {
int length;
int version;
}
header h;
std::vector<char> body;
};
std::istream &operator>>(std::istream &is, Record &r) {
is.read((char *)&r.h, sizeof(r.h));
body.resiz... |
6,496,912 | 6,497,126 | Does placement-new introduce a sequence point? | Consider the following line of code:
new (p++) T();
If the constructor T() throws an exception, is p guaranteed to have already been incremented?
| From 5.3.4 [expr.new] (quoting from n3242):
11 The new-placement syntax is used to
supply additional arguments to an
allocation function. If used, overload
resolution is performed on a function
call created by assembling an argument
list consisting of the amount of space
requested (the first argument) and ... |
6,497,068 | 6,497,320 | Socket application does not work over the internet | I've got a problem in socket programming. I'm currently writing a simple server/client application which asks connecting clients to answer a survey (I'm following the exercises in the book: TCP/IP Sockets in C: Practical guide for Programmers). It works fine in my local network (using localhost to connect), but I can't... | The code makes usage of getaddrinfo and need a hostname not a IP address.
|
6,497,070 | 6,497,092 | Using camera rotation to make quad always appear in front of the camera (c++/opengl) | I'm trying to make a quad appear always in front of the camera, I'm trying to start by aligning it with the camera on the x-z plane and making sure it always faces the camera. I used this code...
float ry = cameraRY+PI_2;
float dis = 12;
float sz = 4;
float x = cameraX-dis*cosf(ry);
float y = cameraY;
float z = camera... | Check out this old tutorial on Lighthouse3D. It describes several "billboarding" techniques, which I believe are what you want.
|
6,497,141 | 6,497,184 | how to determine the size of virtual base class and derived classes from it? | #include <iostream>
using namespace std;
class base1{};
class base2{virtual void show(){}};
class test1{ };
class test2{virtual void show(){}};
class derv1:public virtual base1{};
class derv12:public virtual base2{};
class derv2:public virtual base2, public test1{};
class derv22:public virtual base2, public virt... | The reason that sizeof(base1) and sizeof(test1) are 1 is solely to prevent a most-derived object from having size 0. That's all the standard forbids. Base class sub-objects are allowed to have size 0 (that is, allowed to occupy no bytes), and hence adding base1 as a base doesn't necessarily have to add anything to the ... |
6,497,176 | 6,497,272 | Best technique to handle vertices in OpenGL? C++ | I am implementing a map renderer for Quake. I am currently running through the arrays of vertices and sending them one at a time. I was told that by using vertex arrays, I can greatly speed up the rendering process by sending vertices in a batch. Now, I have just looked at display lists and finally VBO's or vertex buff... | When they say "client/server" communication, they are not talking about a internet network.
Client = The CPU
Server = The GFX hardware
These are two separate pieces of hardware. While they are (usually) attached to the same motherboard, they still need to communicate with each other. A graphics card doesn't usually h... |
6,497,374 | 6,550,361 | Emacs cc-mode indentation problem with C++0x enum class | Emacs cc-mode does not appear to yet recognize the type-safe enum class introduced in C++0x. The result I get is a double indentation for second, third, etc enums:
enum class Color {
Blue,
Red,
Orange,
Green
};
What I would like is:
enum class Color {
Blue,
Red,
Orange,
... | This is the problem:
cc-mode relies somewhat on the assumption that keywords are single words. Adding support for enum_class instead of enum class would just be a matter of changing a few regexps.
Instead Emacs treats this as a class. The correct way of solving this would be teaching Emacs that this is an enum. But tha... |
6,497,772 | 6,498,020 | C++/CLI: Why is there no Managed->Unmanaged transition in this scenario? | Let's say I have a C++/CLI assembly compiled with the /clr switch. In that assembly, there are managed classes which call unmanaged (plain C++) classes defined in the same assembly. When you are debugging using Visual Studio, and you look at the call stack, it shows you where Managed->Unmanaged and Unmanaged->Managed t... | Probably because you didn't tell the compiler that you wanted the 'unmanaged code' to compile to machine code. With /clr in effect, all code gets compiled to IL. It has no trouble with standard C++ code, there are just a few language constructs that are not supported.
If you mixed the code in a source code file then ... |
6,497,976 | 6,498,003 | Defining an Indeterminate Number of Instances of a Class | Oftentimes in a program I am going to write, a user's action is used to create a new instance of a class. I don't know how many instances I will need, so how can I create instances at runtime and have a way to access each one individually? I have searched the forums, but I can't understand any of the answers that have ... | You can create an array (or vector) of classes, add any number of object instances to it, and access them using [] operator
#include <vector>
class A // class declaration
{
public:
A();
void print();
};
vector <A> v; // creating vector
v.push_back(A()); // adding instance 0
v.push_back(A()); // adding ... |
6,498,039 | 6,498,085 | How to create array of pointers in C++ | In class Node:
class Node {
public:
int data;
int numchild;
Node** nodelist;
Node(int data, int s);
};
I want an array of pointers (nodelist) to other nodes, which have edges from this node.
Is the following way of constructing such an array (and the above way of declaring it) a correct and the best... | Generally you shouldn't reinvent the wheel. Raw arrays are almost always the wrong way to go. Have a look at the various containers from the STL, i.e. std::vector, std::list. I woud guess that in your case a std::vector might be the best solution.
If you want to stick with the raw array, a quick warning: new Node*[s] d... |
6,498,076 | 6,498,113 | Erase function in Binary Search Tree | Can someone tell me what the following lines do
else if ( obj < retrieve() )
{
return ( left() == 0 ) ? 0 : left()->erase( obj, left_tree );
}
else
{
return ( right() == 0 ) ? 0 : right()->erase( obj, right_tree );
}
in the code block below:
template <typename Comp>
int Binary_search_node<Comp>::er... | erase appears to be implemented recursively. At each stage, we test whether the object to erase is equal to the current object, or whether we need to go down into the left or right child.
If the child that we want to go into does not exist (left() == 0 or right() == 0), then we cannot erase the object (because it's no... |
6,498,098 | 6,498,128 | Are there any Sorted Collections in C++? | In Smalltalk, you can create a sortedCollection, which is to say that you can add an element and it would insert it into the correct location.
Is there anything like this in C++? Or even better is there anything like a sortedQueue, such that when you add an element, it would sort it into a queue like structure that yo... | You seem to be looking for the std::priority_queue, which is located in the <queue> header file. With push(), you can insert an element into the priority queue; with top(), you will get the currently largest element in the queue (or the smallest one, depending on how you implement operator<); and with pop(), you will r... |
6,498,235 | 6,498,423 | INFO Format reference from (boost property tree) |
I'm searching for a way to write complex data configurations for my application.
I don't really like xml or json for that job for different reasons.
But I found a format that is kind of perfect for the job, it's implemented in boost property tree library and is referenced as "INFO" format(
http://www.boost.org/doc... | Did you look at the Boost docs on this? I doubt there's a better reference. As noted in the doc:
It provides a simple, efficient format
that can be used to serialize property
trees that are otherwise only stored
in memory. It can also be used for any
other purpose, although the lack of
widespread existing ... |
6,498,284 | 6,498,336 | Find debugging printf to remove it | I ran into some problem that I want to solve efficiently and maybe some of you will learn from this too.
I made a mistake, because I debbuged my application using printf( or in my case probably std::cout) debbuging.
It went well and I removed my bug and got to other problems.
Now I am at a stage where I want my debuggi... | If it's a printf - do a macro that will call printf adding to it the file name and line number (these are __FILE__ and __LINE__). Just name the macro printf and call ::printf for the original function.
If it's cout - a bit trickier, but you can try to put breakpoint there and see where it's called from, you'll find it ... |
6,498,479 | 6,498,557 | How would I create a structure that allows me to define multiple objects with multiple values? | I need to create a structure that allows me to define an x number of points (the number of points changes at run time) in a 3-D coordinate system. Each point has an x, y, and z value. So far I have a basic structure like this, but I need it to be able to have multiple points, each with their own values.
struct point {
... | If point_num is a non-contiguous but unique identifier you could use std::map<int, point> and remove the identifier from the struct. That way you get O(log(N)) lookup using the index.
If point_num values are unique and contiguous, use std::vector<point> - again the id field is superfluous, as the location in the vec... |
6,498,575 | 6,499,306 | How to read data from cin and send on socket while async_accepting from that socket? | I currently have a server using Asio like the example here. Currently, it works as intended in that every packet it receives from the client is responded to by the session::handle_read function.
However, I want to modify the server so that it can also accept data from the command line and send that across the packet to... |
I want to modify the server so that it
can also accept data from the command
line and send that across the packet
to the client
Use a posix::stream_descriptor to read from STDIN_FILENO. See this previous question and answer for a more complete example and solution.
|
6,498,585 | 6,498,884 | Numeric division using BCD format | I've two std::deque objects containing (unpacked) BCD numbers. Each byte is one BCD digit. The size is not limited, but there is a MAX_SCALE = 10, so 1 / 3 should result in 0.3333333333. For both objects, the scale and sign is saved:
class Numeric
{
std::deque<uint8_t> m_digits;
size_t m_scale; // indicates how m... | You can use Newton's method to find 1 / a.
Let f(x) = 1 / x - a, you want to find f^{-1}(0).
Then
x_{n + 1} = x_n - f(x_n) / f'(x_n)
converges to f^{-1}(0). This gives us
x_{n + 1} = x_n - (1 / x_n - a) / (-1 / x^2)
therefore
x_{n + 1} = x_n * (2 - a * x_n)
converges to 1 / a. You test convergence with the criterio... |
6,499,007 | 6,499,203 | Circumventing template specialization | Suppose I am a user of a Certain Template Library (CTL) which defines a template, named, say, Hector
template <class T>
class Hector {...};
And in its documentation it gives many guarantees about Hector template behavior.
But then it also defines a specialization for a certain type Cool
template <>
class Hector<Cool>... | Are you able to use the related template Reque that doesn't have the undesired specialization? Otherwise I think you'd need to create a wrapper for Cool so that the specialization isn't used.
|
6,499,036 | 6,499,127 | Kernel parameter passing in CUDA? | I have a newbie doubt regarding how do CUDA kernels work.
If have the following code (which use the function cuPrintf taken from here):
#include "cuPrintf.cu"
__global__ void testKernel(int param){
cuPrintf("Param value: %d\n", param);
}
int main(void){
// initialize cuPrintf
cudaPrintfInit();
int a... | The declaration void testKernel(int param) says that param is passed by value, not by reference. In other words, the stack contains a copy of a's value, not a pointer to a. CUDA copies the stack to the kernel running on the GPU.
|
6,499,056 | 6,499,085 | abstract declarator Node* used as declaration | I am using an abstract class SetOfInt; where a Btree baseclass inherits from. The declaration of the virtual function find gives me a compiler error and I cannot figure out why?
This is the exact error:
SetOfInt.h:21: error: expected unqualified-id before 'virtual'
SetOfInt.h:21: error: abstract declarator 'Node*' ... | The return types should go after the virtual keyword.
i.e.
virtual void add(int x);
instead of
void virtual add(int x);
|
6,499,199 | 6,499,299 | Applying bitwise shift operators to signed types: UB and Impl. defined | C++03 standard tells us that the result of applying the bitwise shift operators to signed types can be UB and Impl. defined for negative values. My question is following: why for operator << it has undefined behaviour, while for operator >> it is just implementation defined ? Is there a strict reason why the result of ... | According to 5.8/2 (admittedly in C++ 98 which is all I have access to):
The value of E1 << E2 is E1
(interpreted as a bit pattern)
left shifted E2 bit positions; vacated
bits are zero filled. If E1 has an
unsigned type, the value of the result
is E1 multiplied by the quantity 2
raised to the power E2, red... |
6,499,263 | 6,499,281 | Will default-constructing an integer array zero-initialize it? | If I have a structure with an array member, and I explicitly call the default constructor of the array in the structure's constructor, will the elements get default-constructed? (In the case of an integer array, this would mean getting zero-initialized).
struct S
{
S() : array() {}
int array[SIZE];
};
...
S ... | Yes (highlighting mine):
(C++03 8.5)
To value-initialize an object of type T means:
if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
if T is a non-union class type wi... |
6,499,413 | 6,499,537 | Does STL or BOOST provide any clean way to get the sort order without reordering original sequence? | I'd like to find the sort order of a vector, for example, without reordering the vector.
I can think of several ways to do this, I'm wondering if I'm missing some built-in STL or BOOST way to do this.
I imagine if the functionality were available the code would end up looking something like this:
std::vector<float> uns... | You would do something like this:
template<typename T>
class SortOrder
{
public:
SortOrder(const std::vector<T> *_sortArray) : sortArray(_sortArray) {;}
bool operator()(int lhs, int rhs) const
{
return sortArray[lhs] < sortArray[rhs];
}
private:
const std::vector<T> *sortArray;
};
//To do... |
6,499,441 | 6,499,685 | Port structure to class | I'm using the Allegro 5 framework. When I need to create an event queue I have to call 'al_create_event_queue' and check for errors, and to destroy it 'al_destroy_event_queue'. Since it is the same mechanism I have to use for each object to be created, it is quite boring.
My question is: there is a way to 'port' a stru... | Of course you can... simply put the code to create the structure in the constructor, and the code to delete it in the destructor.
struct MyQueue {
MyQueue() : queue(al_create_event_queue() { }
~MyQueue() { al_destroy_event_queue(queue); }
ALLEGRO_EVENT_QUEUE* queue;
private:
MyQueue(const MyQueue&);
MyQue... |
6,499,502 | 6,499,540 | Why would anyone want to overload the & (address-of) operator? |
Possible Duplicate:
What legitimate reasons exist to overload the unary operator& ?
I just read this question, and I can't help but wonder:
Why would anyone possibly want to overload the & ("address-of") operator?
SomeClass* operator&() const {
return address_of_object;
}
Is there any legitimate use case?
| If you're dealing with any sort of wrapper objects, you might want or need to transparently forward the access to the wrapper to the contained object. In that case, you can't return a pointer to the wrapper, but need to overload the address-of operator to return a pointer to the contained object.
|
6,499,548 | 6,500,939 | Animation of list items/redrawing Qt QListView | What I'd like to achieve:
A visual indication to draw attention to newly added items in a QListView. I had in mind having the background color 'throb' once (fading from a color to the background).
The setup
I have a model/view using QListView displaying QStandardItems. Qt version 4.7
What I've tried:
I've created a new... | The standard practice to include animations into code is to use state machines.
Animations in Qt cannot be achieved using QtStylesheets. Either use QML or use QStyledItemDelegate and a state machine.
/*CustomItemDelegate*/
int state;
enum states{
animating,
normal
}
void setstate(int... |
6,499,886 | 6,499,910 | glutBitmapString/glutStrokeString seem to require const unsigned char* - strings don't work | Ubuntu 11.04, G++, freeglut and GLUT.
I don't understand this at all. Here's the error I get:
whatever.cc:315:59: error: cannot convert ‘std::string’ to ‘const unsigned char*’ for argument ‘2’ to ‘void glutStrokeString(void*, const unsigned char*)’
and if I try glutBitmapString:
whatever.cc:315:59: error: cannot conve... | There is no automatic conversion of an std::string to a char const*. However, you can use std::string::c_str() to get the char const* out of an std::string.
e.g. glutBitmapString(GLUT_BITMAP_HELVETICA_18, scoreString.c_str());
Note: The answer you linked to doesn't say that you can use std::string. The example it gives... |
6,500,102 | 6,500,135 | What STL container should i use to walk a tree? | I dont know whether bidirectional means i can write rbegin() or if i can decrease an iterator.
I have a tree that is forward only which isnt a problem. I'd like to walk it which is. What i am doing at the moment is every time i visit a branch i push current_iterator. Now the problem is i am iterating through a branch a... | Deque iterators are random-access. You can increment and decrement them.
The problem is probably that you tried to decrement the iterator returned by begin. Doing that is not guaranteed to give you the end of the list — deques aren't circular. (I think it's undefined behavior, so it could give you the end, but I doubt ... |
6,500,199 | 6,500,209 | How to pass a struct as a pointer? [C++] | I have a struct that I'm passing through CreateThread
packetargs *args;
args->s=s;
args->buf=buf;
args->len=len;
args->flags=flags;
args->to=to;
args->tolen=tolen;
CreateThread(NULL,0,mThread,args,0,NULL);
But when I receive it in my Thread function, it crashes the application(Because the information is wrong):
DWORD ... | You forgot to allocate any memory for your struct:
packetargs *args = new packetargs;
(Of course, you'll need to delete it at some point.)
|
6,500,245 | 6,500,278 | Parse error in code: expected ' ; ' before ' { ' token -- what is causing this? | The error I'm getting is error: expected ' ; ' before ' { ' token
I tried fixing the code by adding ; after if (thisisanumber==5) as well as after else (thisisanumber!=5). While this solves the first error it creates another error that says error: ' else ' without a previous ' if '. I'd really love to know what error I... | You don't need another condition as there are only two cases - just use else { ... } and it will catch all cases in which thisisanumber==5 is false.
The structure of an if statement is:
if (condition) { ... }
else if (another condition) { ... }
// ... more conditions
else { ... all cases in which no previous conditio... |
6,500,387 | 6,500,405 | Can I iterate a map from a desired key? | I have map. I need to iterate it not from the beginning, but from the desired key.
I tried it as;
int candidate_s;
map<int, vector<int> >::iterator map;
for(map = a_list.begin()+candidate_s; map! = a_list.end(); map++){
cout<<map->first<<"= ";
for(vector<int>::iterator vec=map->second.begin(); vec!=ma... | On the assumption that candidate_s is of the type of the std::map's key:
std::map<int, vector<int> >::const_iterator startIt = a_list.find(candidate_s);
for(; startIt != a_list.end(); ++startIt) {
//Do stuff
}
|
6,500,476 | 6,507,566 | Using QT to view streaming images from camera | I have a software that sends JPGs over the network to a GUI client that is supposed to display those images. I basically want to display them to a qt window but I'm having problems with how qt displays consecutive JPGs. I made a test to see if I'm getting the image correctly by printing it to a file and that checks out... | Because you are in a infinite loop, the Qt may not have chance to handle event. Could you try to call QCoreApplication::processEvents after you setPixmap?
|
6,500,669 | 6,500,800 | Pass an array of wchar by reference | I want to make a function to allocate memory to an array. Suppose I have this:
PWSTR theStrings[] = { L"one", L"two", L"three" };
void foo(PWSTR a, int b) {
a=new PWSTR[b];
for(int i=0;i<b;i++) a[i]=L"hello";
return;
}
int main() {
foo(theStrings,4);
}
My question is, how do you make the function foo... | There are two thing you must do to make this work:
Firstly, you must use a dynamically allocated array, rather than a statically allocated array. In particular, change the line
PSWTR theStrings[] = { L"one", L"two", L"three" };
into
PWSTR * theString = new PWSTR[3];
theString[0] = L"one";
theString[1] = L"two";
theStr... |
6,500,707 | 6,500,949 | Cant get output result using cvCornerHarris() | I just want to try the openCV function -- cvCornerHarris. Here is my c++ code:
//image file
char imagePath[256] = "./images/lena512color.tiff";
printf("%s\n", imagePath);
IplImage* srcImg = cvLoadImage(imagePath, 1);
if(NULL == srcImg){
printf("Can not open image file(s).\n");
return -1... | It's all about parameters! People tend to believe that there are magical parameters that will work for all types of images and scenarios. Unfortunately, this doesn't happen in the real world.
The parameters used to process one image may not produce the same level of results when applied to other type of image. Now, con... |
6,500,872 | 6,500,884 | Function overriding in native C++ | Is the following code the correct way to call a base class's overridden function from a derived class's function?:
#include "stdafx.h"
#include <iostream>
class BaseClass
{
public:
virtual void foo()
{
std::cout << "BaseClass::foo()" << std::endl;
}
};
class DerivedClass : BaseClass
{
public:
v... | No, your call using __super::foo() is employing a Microsoft language extension.
Instead you can write BaseClass::foo().
Or if you have a typedef BaseClass Base, then Base::foo().
Cheers & hth.,
|
6,501,145 | 6,501,356 | Can we build a SSO solution by openLDAP only? | Can we build a sso solution by openLDAP only? or SSO need at least openLDAP + Kerberos (or something like?) If openLDAP is OK, how can we get the credential of current user to be authentication by other application through LDAP API? Is there any C++ api?
| If by SSO you mean one password at the beginning of the day, and none until you leave, LDAP can't easily do that alone. It can help you consolidate passwords, so you only have to remember one (which is nice), but you still have to enter it repeatedly unless you do a lot of engineeering on top of that.
Kerberos can act... |
6,501,178 | 6,501,188 | If a POD is wrapped inside a class, does it give the same effect? | Following are 2 different interpretations:
char c; // 1
struct MyChar { char c; }; // 2
If I do new MyChar[100], will it allocate 100 bytes in all platform ? Adding non-virtual constructor/destructor and/or operators will make any effect on the size of MyChar ?
| MyChar may have unnamed padding bytes after c, so no, it isn't guaranteed that sizeof(MyChar) is 1.
|
6,501,228 | 6,502,221 | API Hooking which takes effect across entire process - both EXE and DLLs | I have an application consists of a single EXE and multiple DLLs. After reading Windows via C/C++, I try to perform hook on Sleep function in one of the DLL, and expecting the hook will work across both EXE and all DLLs. Note that, CAPIHook code is getting from Windows via C/C++'s sample code
In DLL Project
void WINAPI... | This is because the original CAPIHook does not replace local IAT (in your case, the DLL project which contains binaries for CAPIHook).
The reason behind this was to protect itself from infinite recursion which lead to stackoverflow (which the users will also post question in SO :D).
To ensure that any subsequent modul... |
6,501,317 | 6,501,764 | Vector or element causing a segfault? | I am getting a segmentation fault in my program and gdb tells me it is in this function on the line of
parent->getChildren().push_back(temp);
in
void Tree::add(Position& value, Node*& parent) {
Node* temp = new Node(value, parent);
parent->getChildren().push_back(temp);
}
I have added cout statements before t... | That can't be an "element problem" because you just push_back(Node*). That can't fail.
So I see 2 possible "vector problems":
Problem with parent-> because parent is not allocated.
Problem with getChildren(). because it returns a reference to non-existing vector.
Try to check both of them.
|
6,501,374 | 6,501,433 | Inner class template circular reference | Does anyone knows how you can trick the C++ compiler to compile something like that (with the condition that TheObservedObject remains inside MyClass ):
template< typename Type >
class Observabile
{
public:
typename typedef Type::TheObservedObject TheObject;
void Observe( TheObject& obj ) {}
};
class MyClass :... | Sadly, that is not directly possible, as MyClass, at the point of instantiation of Observable, is not yet complete and as such you can't access any typedefs. You can work around this by adding a small wrapper:
template< typename Type, typename Wrapper >
class Observable
{
public:
typename typedef Wrapper::TheObserve... |
6,501,546 | 6,520,953 | Favorite/Best A.X=B Solver that Supports Long Doubles? | I am hoping to repeatedly hammer an X=B(A^-1) problem. That is, solve a linear system. For C++, which numerical solvers have support for 128bit long doubles (quads)?
Using C style arrays is a major plus as all my 2D data is stored as a single std::vector.
I was hoping to compile the code on linux with either GCC or IC... | Many C++ linear algebra libraries are based on templates, including NT2, Boost.uBLAS, Eigen (see What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs? for links). Thus, they should be able to support quads if your compiler/library can do maths with quads. F... |
6,501,830 | 6,503,715 | Machine learning data structure best practices for input | I am working to develop a C++ machine learning library for some of my own work, and I was curious about best practices for representing input data. Right now, I am thinking about using an DataManager class that handles the I/O operations for reading the data in from file, from a stream, etc. In developing this, I reali... | Some learning problems are on sparse data, that is data with a large number of possible features most of which are zero. In this case it is much more efficient to only store features which are non-zero.
This is usually the case with SVM libraries, such as LibSVM, which stores vectors as a list of (feature_index, featu... |
6,502,071 | 6,502,166 | Vector of Object Pointers, general help and confusion | Have a homework assignment in which I'm supposed to create a vector of pointers to objects
Later on down the load, I'll be using inheritance/polymorphism to extend the class to include fees for two-day delivery, next day air, etc. However, that is not my concern right now. The final goal of the current program is to ju... | A vector of pointers can be reused for storing objects of sub-classes:
class Person
{
public:
virtual const std::string& to_string () = 0;
virtual ~Person () { }
};
class Student : public Person
{
const std::string& to_string ()
{
// return name + grade
}
};
class Employee : public Person... |
6,502,173 | 6,502,494 | Preprocessor tomfoolery (stringifying a #include) | Note: This question has nothing to do with OpenCL per se... check the last paragraph for a succinct statement of my question. But to provide some background:
I'm writing some C++ code that makes use of OpenCL. I like to keep the source for my OpenCL kernels in their own files, to keep coding and maintenance easy (as op... | The most relevant part of the Standard is §16.3/10:
The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between... |
6,502,418 | 6,502,485 | how does istringstream operator>> return value work? | This example reads lines with an integer, an operator, and another integer. For example,
25 * 3
4 / 2
// sstream-line-input.cpp - Example of input string stream.
// This accepts only lines with an int, a char, and an int.
// Fred Swartz 11 Aug 2003
#include <iostream>
#include <sstream>
#include <string>
usin... | The basic_ios class (which is a base of both istream and ostream) has a conversion operator to void*, which can be implicitly converted to bool. That's how it works.
|
6,502,430 | 6,502,524 | Displaying decimal values in Qt using qreal Data Type | Is there a way to get decimal values using qreal in Qt??
just like this:
qreal decimal;
average = 3/2;
the output should definitely 1.5 but instead i am getting 1 as result.
can anyone help me??
| @andro, you could do (x*1.0)/y or (qreal)x/y
|
6,502,677 | 6,506,401 | C++/Tk: How to create slider and receive its value updates? | So I look at C++/Tk for as a GUI library. I see "lots" of examples - 6. I like its style but I do not see how to create a slider/trackbar. I want such a trackbar that on its value change to have my function called and tb value sent to it. How to do such thing with C++/Tk?
| You want a scale widget (which should be enough that you can find it in the docs) and you need an extra callback function which takes no arguments, reads the current value from the scale, and dispatches to your real function. That extra callback function will be configured into the scale via -command, much as the exist... |
6,502,688 | 6,502,703 | Is delete necessary in a destructor? | I have the following code and I'm wondering if that delete b is necessary here ?
Will my operating system automatically clear that area of memory allocated ?
class A
{
B *b;
A()
{
b = new B();
}
~A()
{
delete b;
}
};
Many thanks.
| Yes, you have to delete every object created with new that you own. In this very case it looks like class A owns that very instance of class B and is responsible for calling delete.
You'll be much better off using a smart pointer for managing class B instance lifetime. Also note that you have to either implement or pro... |
6,502,733 | 6,506,333 | C++/Tk: can we create an executable that would run with out requiering end user to have any special TcL interpriter installed? | What are step by step instructions for compiling C++/Tk program into executable that would run on other users machines not requiring that end users to install any additional software, are there any entirely static link options for TCL tk?
| Tcl and Tk work just fine when built statically; this is a supported (but not default) configuration. Just get the source releases and configure them with --disable-shared to ensure that they build the right type of library for you.
Colin's answer links to most of what you need to know about coding to use Tcl and Tk fr... |
6,502,754 | 6,502,936 | How can I programmatically get the amount of memory currently available from C/C++ code? | In my middleware software layer I am receiving a lot of crashes due with the message,
page allocation failure. order:10, mode:0xd1
As I understand the crash can occur due to number of reasons, running out of dynamic memory for further allocations or Memory fragmentation.
The backtrace which follows the message is not ... | The message you have shown indicates a failure to allocate memory for a kernel allocation, not a userspace allocation. It is a request for a 4MB (this is what order = 10 means) block of contiguous physical memory. This is a very large kmalloc() request, and it is not surprising that it fails (likely due to memory fra... |
6,502,828 | 6,502,854 | What does "default" mean after a class' function declaration? | I've seen default used next to function declarations in a class. What does it do?
class C {
C(const C&) = default;
C(C&&) = default;
C& operator=(const C&) & = default;
C& operator=(C&&) & = default;
virtual ~C() { }
};
| It's a new C++11 feature.
It means that you want to use the compiler-generated version of that function, so you don't need to specify a body.
You can also use = delete to specify that you don't want the compiler to generate that function automatically.
With the introduction of move constructors and move assignment oper... |
6,503,136 | 6,503,620 | QueryInterface fails with E_ACCESSDENIED | The following method is a DCOM server method. The COM client and server is running in different WinXP machines. The COM client calls RegisterClient method to register callback interface. The problem is QueryInterface method fails with error code E_ACCESSDENIED. What could be the reason for the issue?
STDMETHODIMP CGEME... | When you get an E_ACCESSDENIED, it means you have a permissions problem (don't waist your time on firewalls or registrations - the former will raise errors telling you the service is not available, and the latter will tell you the class is not registered or so). COM relies on Windows permissions, so this is what you sh... |
6,503,376 | 6,503,602 | can compiler reorganize instructions over sleep call? | Is there a difference if it is the first use of the variable or not. For example are a and b treated differently?
void f(bool&a, bool& b)
{
...
a=false;
boost::this_thread::sleep...//1 sec sleep
a=true;
b=true;
...
}
EDIT: people asked why I want to know this.
1. I would like to have some way t... | We can't really tell. On scenario could be that the compiler has full introspection to your function at the calling site (and possibly does inline it), in which case it can jumble your function with the caller, and then do optimizations appropriately.
It could then e.g. completely optimize away a and b because there i... |
6,503,586 | 6,504,578 | What does ## in a #define mean? | What does this line mean? Especially, what does ## mean?
#define ANALYZE(variable, flag) ((Something.##variable) & (flag))
Edit:
A little bit confused still. What will the result be without ##?
|
A little bit confused still. What will the result be without ##?
Usually you won't notice any difference. But there is a difference. Suppose that Something is of type:
struct X { int x; };
X Something;
And look at:
int X::*p = &X::x;
ANALYZE(x, flag)
ANALYZE(*p, flag)
Without token concatenation operator ##, it exp... |
6,503,594 | 6,503,688 | Difference between { 0 } & { { 0 } } for a structure |
Possible Duplicate:
What is the meaning of double curly braces initializing a C-struct ?
for this following structure,
typedef struct matrix
{
float data[16];
} matrix;
Is there any difference between,
matrix test1 = {0};
and
matrix test1 = { { 0 } };
when it comes to initializing the data member of the str... | With matrix test1 = { 0 } you will initialize test1 with all zero's and with matrix test1 = { { 0 } } You will initialize test1.data. with all zero's in this case it does the same actually since you don't have any other data definitions in your struct :)
|
6,503,736 | 6,503,801 | number of templated parameters in a boost::tuple | I am using boost::tuple for my code.
Suppose that I want to store an equivalent of a structure having 3 members
typedef boost::tuple< std::string, int, double > my_struct;
Is there any way of method to call on the tuple that will give me the number of members contained so in this case 3?
My goal here is to monitor w... | Use the ::boost::tuples::length<T>::value helper function.
See documentation.
|
6,503,773 | 6,504,265 | What is the purpose of std::common_type? | I started looking at std::common_type and am not exactly sure about its purpose and its functionality.
A few things still strike me as odd:
Order of arguments is important: common_type<Foo, Bar, Baz> might be different from common_type<Baz, Foo, Bar>. Either might compile, the other might not. While this is clear from... | std::common_type was introduced for use with std::duration --- if you add a std::duration<int> and a std::duration<short> then the result should be std::duration<int>. Rather than specifying an endless stream of allowed pairings, the decision was made to delegate to a separate template which found the result using the ... |
6,503,901 | 6,503,987 | How to call a c function from name , which is stored in a char* pointer? | I wanted to dynamically call a function by its name , e.g , suppose have the following function and string:
void do_fork()
{
printf ("Fork called.\n");
}
char *pFunc = "do_fork";
Now i need to call do_fork() just by *pFunc. So is that possible ?
Either C/C++ code is welcomed , many thanks !
| Neither C nor C++ have enough reflection to do this out of the box, so you will have to implement your own scheme.
In C++, the more or less canonical way to do that is using a map of strings to function pointers. Something like this:
typedef void (*func_t)();
typedef std::map<std::string,func_t> func_map_t;
// fill ... |
6,503,903 | 6,503,931 | Multiple IFs with the same return | I've seen some code that looks like this:
if (a) return false;
if (b) return false;
if (c) return false;
return true;
Is there any difference in performance between the above and
if (a || b || c) return false;
else return true;
In general, what would be the preferred case to handle this? Maybe without the else in my... | It all comes down to how the compiler compiles the code. For all practical purposes, they are identical. (As long as you make sure to use short-curcuited OR "||")
|
6,504,211 | 38,978,273 | Is it possible to include a library from another library using the Arduino IDE? | I'm trying to write an Arduino library (effectively a C++ class) which itself references another library I have installed in my Mac's ~/Documents/Arduino/libraries directory.
At the top of the .cpp of the library I'm writing, I've tried
#include <ReferencedLibrary.h>
and
#include "ReferencedLibrary.h"
... neither of ... | This issue was solved in the Arduino 1.6.6 release. The release notes of 1.6.6 mention that library to library dependencies have been fixed.
Library to library dependencies: when your sketch imports a library, and that library uses another, the IDE will find out without you having to add a useless #include to your ske... |
6,504,579 | 6,504,650 | Porting VC++ inline assembler to x64 (of a __stdcall hook) | I need to port the inline assembler to be able to compile on x64.
I'm trying to get familiar with the x64 Intrinsics etc but I guess someone being into it could easily help me out.
void __stdcall Hook(P1, P2)
{
__asm pushad
static void* OriginalFunctionPointer =
GetProcAddress(GetModuleHandleA("Some.dl... | seems you need a hooking library like this one(or this if you want a C++ API) along with a function proto, then no inline assembly is needed, in 32 or 64-bit mode. also, those pushad/popad's aren't needed when you are doing inline assembly.
typedef void (__stdcall*myfp)(int,int);
void __stdcall MyHook(int arg1, int arg... |
6,504,611 | 6,504,784 | when do global variables allocate their memory? | It's been bothering me for a while but I didn't find any good resource about this matter. I have some global variables in my code. It's obvious that they are initialized in some order but is the memmory needed for all those objects reserved before any initialization take place?
here is the simple example of what might ... | Variables declared at namespace scope (as opposed to in classes or functions) have the space for the objects themselves (sizeof(ObjectType)) allocated by the executable (or DLL) loader. If the object is a POD that uses aggregate initialization, then it typically gets its values set by having the linker write those valu... |
6,504,706 | 6,505,443 | errors compiling Qt with Intel C++ compiler for Win32, what am I doing wrong? | I have opened MSVS 2010 command prompt, from where I've run ips-vars.cmd from Intel Parallel Studio (which sets up environment for ICC), from where I called:
configure -ltcg -debug-and-release -graphicssystem opengl -mp -platform win32-icc -no-s60
And got this:
Creating qmake...
Microsoft (R) Program Maintenance Uti... | The option -Yu means "use precompiled header".
Seems like you haven't first created a precompiled file (-Yc). And that one should probably not end in .h.
|
6,504,730 | 6,504,770 | Can I get count from a hash_map while adding some items to it? | For both windows and linux:
In multi-threaded application, in case I do not care the very exactly when getting the count of a hash_map, then can I safely call {hash_map}.size() while still allow other threads to add/delete items on that {hash_map}?
Thank you.
| No
The STL containers (if that's what you're using) are not thread-safe.
size() is likely to walk the buckets and count the numbers. Modifying that data structure while another thread walks it is dangerous (that is, dangerous like a drunk elephant in a minefield).
I'd recommend wrapping your hash_map with some functio... |
6,504,782 | 6,505,023 | How to merge two cells of a qtable row? | I have created a table using qtablewidget. I would like to selectively merge cells of some rows. Is there any built-in function for that(sorry, I couldn't find one)? Otherwise, please specify how it can be done. Thanks
| You could use the setSpan function of QTableView (which QTableWidget inherits) to achieve something like that for rows and columns.
That is, unless you're looking to really just merge individual cells. I'm not sure that can be achieved with setSpan, but have a look at it anyway.
|
6,505,074 | 6,505,281 | emacs: Force parsing of local variables of a buffer | I have an Emacs-lisp script that creates two buffers with some content, asking the user the name of the buffer. The text of the file is inserted in the newly created buffer by the name given by the user. Here is the code snippet:
(with-current-buffer (find-file-noselect
(read-file-name "C++ exam... | (normal-mode t) sets the mode for the current buffer, as if it had just been visited.
|
6,505,461 | 6,505,517 | Function returning pointer to itself? | Is it possible in C++ to write a function that returns a pointer to itself?
If no, suggest some other solution to make the following syntax work:
some_type f ()
{
static int cnt = 1;
std::cout << cnt++ << std::endl;
}
int main ()
{
f()()()...(); // n calls
}
This must print all the numbers from 1 to n.
| struct function
{
function operator () ()
{
//do stuff;
return function();
}
};
int main()
{
function f;
f()()()()()();
}
You can choose to return a reference to function if needed and return *this;
Update: Of course, it is syntactically impossible for a function of type T to return T* o... |
6,505,606 | 6,505,683 | C++ Read Binary file containing numbers of type double | I have a binary file that contains numbers of a type double.
The example input file is available here: www.bobdanani.net/download/A.0.0
I would like to read the file and print the numbers in it.
This is what I have done:
char* buffer;
int length;
string filename = "A.0.0";
ifs.open (filename.c_str(), ios::in | ios::... | While I could be wrong, since you said the number is separated by a tab/space, I'm willing to be this is actually ASCII data, and not raw binary data. Therefore the best way to work with the floating point value would be to use the operator>> on the ifstream object and then push that into a double. That will do an au... |
6,505,723 | 6,505,787 | How to make it clear when an object does not exist in C++? | I have a class which depending on the state of the application and user options may not always be able to exist in any meaningful state.
What is the best way to make it clear when the object does not exist?
Two ideas I've thought of so far and why I don't believe they are not the answer:
A smart pointer set to NULL wh... | I think you want the NULL Object pattern.
You inherit from your base class, a "null" implementation of it. So it has the same methods and properties as the main object but doesn't do anything. Then have an instance of this as a constant. Whenever your variable is not in a usable state assign it to the null object. Noth... |
6,505,891 | 6,505,946 | Class defined in separate file | Is it possible to create an object in file A.cpp if its class is defined in file B.cpp?
What I mean is, you can use extern to access a variable initialized in another file. Is there anything similar for classes?
| No. The class definition must be visible to the compiler in the current translation unit if you actually instantiate/use that class.
Usually you have the definition of the class in a header file that will be included in every .cpp that needs to use that class. Notice that usually methods inside a class definition are o... |
6,505,963 | 6,506,163 | C++ return type when I don't know if it's temporary | Suppose that Foo is a rather large data structure. How should I write a const virtual function that returns an instance of Foo, if I don't know whether the inherited classes will store the instance of Foo internally; thus, allowing a return by reference. If I can't store it internally, my understanding is I can't retur... | You're interested in the difference between a value return and a const reference return solely as a matter of optimization, but it isn't. There's a fundamentally different meaning between returning a different value each time, vs. returning a reference each time, quite possibly to the same object, which quite possibly ... |
6,506,367 | 6,506,550 | Visual C++ 2010 - fatal error LNK1169: one or more multiply defined symbols found | this is a program :
#include <iostream>
using namespace std;
int main() {
cout << "Enter a number";
int i;
cin >> i;
try {
if( i == 0 ) throw 0;
if( i == 2 ) throw "error";
} catch( int i ) {
cout << "can't divide by 0";
}
catch( ... ) {
cout << "catching other exceptions";
}
}
On compiling ... | Actually there is no error in this code.
Number of source files could be the problem.
Try this code as a new project in the same compiler or try deleting the files from the source files option in the left side of Text Area (i.e where you are writing your code)
This should compile then.
|
6,506,381 | 6,507,314 | Trying to open an input in PortMidi | I'm trying to open a midi port to read events from a midi keyboard in C++ using PortMidi. I have found the device id for the keyboard using GetDeviceInfo but can't open the input.
The function looks like this:
Pm_OpenInput ( PortMidiStream ** stream,
PmDeviceID inputDevice,
... | The documentation states
stream is the address of a
PortMidiStream pointer which will
receive a pointer to the newly opened
stream.
So modify your code to do exactly what it says.
PortMidiStream *stream; /* A PortMidiStream pointer */
Pm_OpenInput(&stream, 12, NULL, 128, NULL, NULL); /* Pass the address of the ... |
6,506,395 | 6,506,455 | How can I write on the toolbar in Visual C++ 6? | I have a toolbar in my application and I want to write my current date on it. In the same height as all the icons of the toolbar are put.
| This rather sounds like something you'd like to put on the status bar, not the toolbar. But in any case, you could add a static control to the toolbar and display the current date in that control.
|
6,506,635 | 6,507,680 | multiple ::setTimer in c++ | I need more than one timer using the ::SetTimer function having the same EventID. Is this possible/a good idea to create multiple window handles with ::CreateWindow, and then assign each timer to the created window handles? Any other choices?
Edit: Anyway, I only want to know what happens here:
int eventID = 0;
hWnd1 ... | From http://msdn.microsoft.com/en-us/library/ms644906%28v=vs.85%29.aspx
The timer identifier, nIDEvent, is
specific to the associated window.
Another window can have its own timer
which has the same identifier as a
timer owned by another window. The
timers are distinct.
|
6,506,659 | 6,506,716 | Is there anything like "std::and" or "std::or"? | Given a container of boolean values (An example is std::vector<bool>), is there a standard function that returns true if all the values are true ("and") or true if at least one value is true ("or"), with short circuit evalutation ?
I digged trough www.cplusplus.com this morning but couldn't find anything close.
| You can implement by:
AND:
std::find(vector.begin(), vector.end(), false) == vector.end() // all the values are true
OR:
std::find(vector.begin(), vector.end(), true) != vector.end() //at least one value is true
|
6,506,717 | 6,506,757 | char array compilation error | What is the problem in my code? It does not compile..
class FileNames
{
public:
static char* dir;
static char name[100];
static void Init3D()
{
FileNames::dir = "C://3D//";
FileNames::name = "abc";
}
};
| You cannot assign to an array, so FileNames::name = "abc" fails (char arr[4] = "abc" works, however, because this is a direct initialization, not assignment). Either use a char* here as well, or use strcpy to copy data to the array or better a std::string which avoids many of the downsides of raw strings.
Most importan... |
6,506,836 | 6,510,356 | What happens if delete[] p fails? | Suppose I have a pointer to a dynamically allocated array of 10 elements:
T* p = new T[10];
Later, I want to release that array:
delete[] p;
What happens if one of the T destructors throws an exception? Do the other elements still get destructed? Will the memory be released? Will the exception be propagated, or will ... | I can not see it explicitly called out in the standard:
Just that they will be called in reverse order of creation
5.3.5 Delete [expr.delete]
6 If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of ... |
6,506,898 | 6,506,993 | c++ linux system command | I have the following problem:
I use in my program this function:
system("echo -n 60 > /file.txt");
it works fine.
But I don't want to have constant value. I do so:
curr_val=60;
char curr_val_str[4];
sprintf(curr_val_str,"%d",curr_val);
system("echo -n curr_val_str > /file.txt");
I check my string... | you cannot concatenate strings like you are trying to do. Try this:
curr_val=60;
char command[256];
snprintf(command, 256, "echo -n %d > /file.txt", curr_val);
system(command);
|
6,506,948 | 6,507,127 | find_if on a string array | I am finding all strings from an array depending on the first letter:
#include<iostream>
#include<algorithm>
#include<string>
int main(){
const std::string strArray[] = {"an","blau","Bo","Boot","bos","da","Fee","fern","Fest","fort","je","jemand","mir","Mix",
"Mixer","Name","neu","od","Ort","so"... | iterator is not valid in 3rd case.
In this case iterator = strArray + 23 and point to element placed after array.
Look the fixed code.
|
6,507,208 | 6,507,271 | std::deque memory use | I have implemented a simple statistical engine to return rolling mean and variance using a deque to provide a data queue.
The deque is constructed with a number of entries equal to the rolling number of values.
When a new value arrives the oldest value is popped of the front and the new one pushed onto the back.
I nee... | Essentially, any dynamically sized container allocates memory from the heap. Another question provides an overview over the implementation of the deque.
But in your particular case, the queue always has the same size. If you hit problems with the deque, it might be beneficial to implement a simple fixed-size queue usin... |
6,507,372 | 6,507,435 | Must the IUnknown interface be re-implemented by every new COM class? | Sorry if this question seems obvious for everyone, but I am very new to COM. From the tutorial I see here http://www.codeguru.com/cpp/com-tech/activex/tutorials/article.php/c5567, it seems like every COM class created in C++ must implement its own QueryInterface, AddRef and Release. Since these methods should have basi... | FTA:
"I believe that every programmer who wishes to understand the basic principles behind COM, must write atleast one simple COM object using plain C++ , i.e. without the aid of templates and macros that comes along with MFC/ATL."
To answer your question: Yes, every COM component must implement IUnknown, it's the fo... |
6,507,511 | 6,508,450 | Qt round rectangle, why corners are different? | I try to draw a round rectangle with drawRoundedRect method directly in a QPixmap (no render engine involve here exept pure Qt one ...), I double check the size of the rectangle versus the size of my pixmap :
Pixmap : QSize(50, 73)
Rectangle: QRect(0,0 48x11)
See plenty of space ...
EDIT: some code
pixmap = QPixmap... | It looks like you're not using anti-aliasing (i.e. the QPainter::Antialiasing render hint). This is a Qt quirk that occurs without it. From what I've seen/heard, the Qt devs aren't terribly concerned with fixing this (most people want anti-aliasing anyway).
The work-around (besides just using anti-aliasing) is to dra... |
6,507,686 | 6,507,907 | Check if one range is a subrange of another range in a nice, STL-ish way | Suppose we have two ranges r1 = [first1, last1) and r2 = [first2, last2)
Let's say that r2 is a subrange of r1 iff there exists such i>=0 that
[first1 + i, first1 + i + last2 - first2) is a valid range
for all j in [0, last2 - first2) the following holds:
*(first1 + i + j) == *(first2 + j)
A nested loop can easily ... | I think std::search is what you're looking for. From http://www.cplusplus.com/reference/algorithm/search/ [std::search] "Searches the range [first1,last1) for the first occurrence of the sequence defined by [first2,last2), and returns an iterator to its first element."
|
6,507,705 | 6,509,192 | Callbacks from C++ back to C# | say I have a C++ library function for computing PI:
// pi.h:
#ifdef BUILDING_DLL
#define DLL_MACRO __declspec(dllexport)
#else
#define DLL_MACRO __declspec(dllimport)
#endif
namespace Cpp {
class PI {
public:
static double DLL_MACRO compute();
};
};
// pi.cpp:
#include "pi.h"
#include <cmath>
double
Cpp... | I would take a function pointer/delegate approach as well:
// pi.h:
#pragma once
#ifndef DLL_MACRO
#ifdef BUILDING_DLL
#define DLL_MACRO __declspec(dllexport)
#else
#define DLL_MACRO __declspec(dllimport)
#endif
#endif
namespace Cpp {
typedef void (__stdcall *ComputeProgressCallback)(int);
class PI {
pub... |
6,507,865 | 6,508,055 | How to negate boost::lambda:bind? | Let's say I have this type:
typedef boost::function<bool (Foo)> filter_function;
And a vector of those "filter functions":
std::vector<filter_function> filters;
If want to call all the filter functions, one by one, and only the the last call returned true.
Inspired by a previous question, I ended up writing:
bool Bar... | You can simply negate the return value.
bool Bar::filterFoo(Foo& foo)
{
return (std::find_if(filters.begin(), filters.end(), !boost::lambda::bind(boost::lambda::_1, foo)) == filters.end());
}
or you can use lambda from c++0X
bool Bar::filterFoo(Foo& foo)
{
return (std::find_if(filters.begin(), filters.end(), [... |
6,507,984 | 6,511,775 | Streaming ZIP file won't open in OSX | I'm creating a class to stream a ZIP file from PHP.
The output is absolutely fine when opening in WinRAR, Windows compressed folder, BetterZip etc but when opening in the OSX Unarchiver all I get out is a .cpgz file and nothing else.
I've read the ZIP specification over and over again and cross-checked against my heade... | To answer my own question, the problem is that OSX does not like 2 things. 1) Appending the additional metadata (size, CRC etc) to the end of directory records as this is not strictly necessary (but within the spec). And 2) it does not support storage method 0x00 (store), files must be at the very least DEFLATED to be ... |
6,508,188 | 6,552,355 | filestream processing in c++(tellg() function) | i wrote the following code....
#include< iostream>
#include< fstream>
using namespace std;
int main()
{
ifstream in("text1.dat",ios::in);
enum choice{zero=1, credit, debit, exit};
choice your;
int balance;
char name[50];
int option;
while(cin>>option)
{
if(option==exit)
break;
switch(option... | You are observing the same behavior as many other novice C++ programmers. Read for example this question.
What happens is that in.eof() is set to true after you've tried to read something from in and the operation failed because there was no more data. When a read operation fails due to end-of-file, it sets both, eofbi... |
6,508,226 | 6,519,602 | What would be a proper name for the concept of setting up and tearing down a unit-test context? | Basically all unit-testing frameworks I've used, be it in C++ or C# (or anything else, I guess), have had the concept of setup and teardown to establish reusable contexts for many test cases.
Right now I'm doing some related work (EDIT: this work has nothing to do with testing, but the setup/teardown concept is the sam... | I ended up using context instead of configurator. It better describes the concept.
|
6,508,255 | 6,906,814 | Historical time to GMT\UTC with DST | Similar to:
Convert historical time to GMT
This time my scenario is:
I need to convert some string times in the format "2011061411322100" into GMT. The problem is that the times are coming from another PC and is a historical time. So I am not getting the times in real time so I cannot simply get the GMT from the local ... | You ABSOLUTELY must know what the reference timezone was on the source data. Simply saying it was local time on the source machine doesn't provide enough info.
Consider (for one example out of many): The DST rules changed in the US in 2007, and any date calculations spanning across that range must take that into accoun... |
6,508,278 | 6,634,550 | pointers with OpenMP | i am trying to use OpenMP in my program (i am newbie using OpenMP) and the program return in two places errors.
Here is an example code:
#include <iostream>
#include <cstdint>
#include <vector>
#include <boost/multi_array.hpp>
#include <omp.h>
class CNachbarn {
public:
CNachbarn () { a = 0; }
uint32_t Get_Next... | Concerning your first problem:
Your function Validity is a perfect way to achieve below serial performance in a parallel loop. However, you already gave the correct answer. You should fill independent vectors for each thread and merge them afterwards.
inline void CNetwork::Validity() {
#pragma omp parallel for
for ( u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.