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,684,630 | 6,685,812 | C++ Inheritance and how to pass and maintain subclass data through a superclass | Alright, wasn't quite sure how to word the question and couldn't find any duplicates that I think really address this situation.
Essentially I have a super class that gets extra data appended to it through a subclass. The container class for this data recognizes only the super class and adjust characteristics based on ... | If you start mixing low level memory allocation with malloc()/free(), and C++ objects, you will run into a lot of troubles, while making your code almost unreadable.
You should create a new object with new on a proper constructor, which automatically 1) allocates memory and 2) initializes the struct. To properly free ... |
6,684,641 | 6,685,259 | Recording What-You-Hear audio in Windows 7 |
Possible Duplicate:
Windows Vista/7: How to sample output audio mix?
How to record what-you-hear audio stream in Windows with C/C++?
The solution should be compatible with Windows 7 where, AFAIK, some changes has been introduced about that. As a result, some programs (CamStudio) are unable to record W-Y-H sound whil... | You can do so with WASAPI. There's a loopback sample available that I used a while back to learn how. It will only work on Vista and up, though -- not XP.
I've not tried to do it pre-Vista, so I don't know for sure why any old APIs would stop working.
|
6,684,759 | 6,685,186 | Why doesn't std::set<K, C, A>::erase take a const_iterator? | It appears that according to ISO 14882 2003 (aka the Holy Standard of C++) std::set<K, C, A>::erase takes iterator as a parameter (not a const_iterator)
from 23.3.3 [2]
void erase(iterator position);
It might also be noteworthy that on my implementation of STL which came with VS2008, erase takes a const_iterator whic... | This was a defect. Since C++11, set<K,C,A>::erase takes a const_iterator:
iterator erase(const_iterator position);
This paper from 2007 illustrated that error and showed implementations to avoid it. I am not sure if this paper is the reason for the change in the standard, but it's probably a good guess.
|
6,684,766 | 6,684,784 | What does an If statement followed by a semicolon instead of curly brackets mean in C++? | I was recently looking at some vp8 sample decoder code when I came upon this.
for(y=0; y<img->d_h >> (plane?1:0); y++) {
int iLength = img->d_w >> (plane?1:0);
iFrameCursor += iLength;
if(fwrite(buf, 1, iLength, outfile)); //This semicolon
buf += img->stride[plane];
}
Any idea what the if statemen... | The semicolon here is the same as if you had said { }. It is just an empty statement.
The following lines of code all do the same thing:
if(fwrite(buf, 1, iLength, outfile));
if(fwrite(buf, 1, iLength, outfile)) { }
fwrite(buf, 1, iLength, outfile);
This is probably an error.
|
6,684,867 | 6,685,134 | Extract REG_MULTI_SZ value from registry and store in string array c++ | There is a REG_MULTI_SZ value that I would like to stick in an array of strings so that my program can do other things with them. I've never used C++ to access the registry so I'm a bit lost after following some examples. I'm using VS10.
Is there a simple way to do this? Thanks.
| First: run RegQueryValueEx to get type and necessary memory size:
Single byte code:
DWORD type, size;
vector<string> target;
if ( RegQueryValueExA(
your_key, // HKEY
TEXT("ValueName"),
NULL,
&type,
NULL,
&size ) != ERROR_SUCCESS )
return;
if ( type == REG_MULTI_SZ )
{
vector<char> temp(size)... |
6,684,929 | 6,685,013 | Segmentation fault. 0xb7d9e768 in memmove () from /lib/libc.so.6 | GDB gives me the above error WRT my C++ program. Nowhere I have used any memory function including new and delete etc.
I want to understand the 'MEANING' of this error.
| If run your program under gdb, you should be able to print out the backtrace and see what part of your code is causing the segmentation fault. memmove() may being called indirectly through a different system call.
|
6,684,968 | 6,684,997 | Looking for an easy way to reinitialize a struct | I have a struct called CoolStruct:
struct CoolStruct
{
int id;
uint32 type;
uint32 subtype;
String name;
};
I have a vector of these structs as well:
std::vector<CoolStruct> coolVector;
I want to create a bunch of structs which have predefined values to push_back into this coolVector. I'd like to kee... | how about:
CoolStruct t1 = {1, EQData::EQ_EFFECT_TYPE_PARAMETRIC, 0, T("Parametric")};
coolVector.push_back(t1);
CoolStruct t2 = {2, EQData::EQ_EFFECT_TYPE_FILTER_LOW_PASS,EQData::EQ_FILTER_TYPE_FILTER_BUTTERWORTH_12DB, T("Low Pass")};
coolVector.push_back(t2);
In C++0x, I think you should be able to do:
CoolStruct t;... |
6,685,070 | 6,690,217 | a question about tcl testing | I have a question about Tcl, we are using Tcl to write some test cases for c and c++ application. I saw some Tcl test cases are:
if {0} { #START:HELLO1
//some code here
}#END:HELLO1
if {0} { #START:HELLO2
//some code here
}#END:HELLO2
if {0} { #START:HELLO3
//some code here
}#END:HELLO3
How does these code works? #S... | Those are very odd looking tests by Tcl terms. If they'd read like this (with the extra semicolon):
if {0} { #START:HELLO1
//some code here
};#END:HELLO1
Then they'd just be blocked out code that does nothing (literally; Tcl won't attempt to generate code for it, just as a C or C++ compiler is unlikely to do much for ... |
6,685,411 | 6,685,779 | Other ways to change tab order programmatically in a dialog | I'm trying to track down why some of my dynamically created child controls in a Windows dialog are out of order when it comes to navigating them with the tab key. In the absence of anything else fiddling with them, the order should be defined by the order in which they are added into the dialog, but one specific type ... | That's pretty much it - in a standard dialog, the tab order is just the z order, except that you can control where to start in the z order. If you've got a couple of controls that always end up at the end of your tab order, something is manipulating the z order to put them there.
If the dialog or controls are non-stan... |
6,685,435 | 6,685,479 | install g++ and compile issues | Can I use gcc to compile C++ program? Is there any difference with using g++ instead?
On an exisitng system, I type "man g++", the system returns "no manual entry for g++". But it has gcc installed. Is that possible to install g++ from existing gcc library directly; or I have to download g++ instead?
| You can use gcc to compile C++ programs as long as you set the proper flags and/or use the right extensions on your source-files (i.e., use .cpp), but that's only if the C++ development tools, such as libstdc++ have been installed ... and that typically means that g++ is available as well. So if you don't have the C++... |
6,685,457 | 6,685,693 | Header file inclusion static analysis tools? | A colleague recently revealed to me that a single source file of ours includes over 3,400 headers during compile time. We have over 1,000 translation units that get compiled in a build, resulting in a huge performance penalty over headers that surely aren't all used.
Are there any static analysis tools that would be ab... | The output of gcc -w -H <file> might be useful (If you parse it and put some counts in) the -w is there to suppress all warnings, which might be awkward to deal with.
From the gcc docs:
-H
Print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the
#... |
6,685,470 | 6,686,225 | getting alpha by subtracting two images with different backgrounds | I am using a program what can render color images but only without alpha information. I would like to get alpha information from those images by using two and subtracting them. I can set the background to different colors.
My idea is that if I render an image with black background and an other one with white, then I ca... | this might be good enough if your object differs enough from the background but this looks like it might be exactly what you asked for
EDIT: the second one ends up with this command line (replace the stuff in <> with your images)
convert <image1> <image2> -alpha off \
\( -clone 0,1 -compose difference -comp... |
6,685,515 | 6,685,669 | ADL without templates | Can one show me an example of ADL without using templates? Never seen something like that. I mean something like here. Specifically I am interested in example in which it leads to some pitfall like in mentioned.
EDIT:
I think Tomalak's answer can be extended to pitfall. Consider this:
namespace dupa {
class A {
... | I can't show you something leading to a pitfall, but I can demonstrate ADL working without templates:
namespace foo {
struct T {} lol;
void f(T) {}
}
int main() {
f(foo::lol);
}
Note that lol's type has to be a class-type; I originally tried with a built-in, as you saw, and it didn't work.
|
6,686,055 | 6,687,273 | Catching keyPressEvent in multiple selected QGraphicsItems | I have a set of QGraphicsItems in a QGraphicsScene in which I've set the drag mode to RubberBandDrag. I would like to be able to 'rubber band' select multiple QGraphicsItems and then hit the delete key, which should call keyPressEvent() in all selected items. Unfortunately, keyPressEvent is only being called in at most... | You have to assign keyPressEvent() to QGraphicsScene (not for QGraphicsItems) and delete all selectedItem with out any problems.
|
6,686,074 | 6,686,200 | How to launch a thread without waiting for response in C++? | There is a CreateThread() call within a for loop, and I want all the threads to be launched one after another and each thread writes data to a object.
`$while (ii != mapOServs.end())
{
Array_of_Thread_Handles[i] = CreateThread(NULL,0,MyThread, &args[i] , 0 , NULL);
}
But the threads don't start until i... | The threads are indeed "started" immediately --- Windows will create the necessary internal structures, allocate the stack and so forth, and add them to the scheduler's run list. However, they won't necessarily be scheduled immediately.
In particular, the thread doing the launching will likely keep running until it has... |
6,686,270 | 6,686,300 | How do I timeout a recv() function in c++? | I have a program running on a server communicating with another program running on the client. They both send data and files back and forth.
I notice that whenever there is a socHandler.read() (function to read data coming in on socket), it gets stuck waiting for data to arrive.
This is what the function looks like.
i... | Call select() to query if the socket has any pending data before then calling recv() to read it.
|
6,686,279 | 6,686,842 | How to form a Concave shape out of Convex shapes? | i'm trying to get around the rule of only being able to form convex shapes in the SFML c++ library.
To do this I'm planning on testing given vertices, and if concave,
splitting the vertices into groups, testing each groups' concaveness,
and repeating until a full set of concave shapes results that look
just lik... | You can test for a shape being a convex hull by going round all the edges and checking the next edge is always moving in the same direction (left/right handed). This is a quick and cheap algorithm. There is an implementation of this here: en.wikipedia.org/wiki/Graham_scan
If you don't have a convex hull, perform a pack... |
6,686,287 | 6,686,373 | BSD Sockets - Using send and recv | I am trying to implement a simple chat program in linux using bsd sockets. Right now I am just trying to send and receive one message to the server from a client. Whenever I run the code, recv returns -1 and the errno code is 22.
Server code -
struct sockaddr name;
char buf[80];
int main(int agrc, char** argv) {
... | Aside from all other problems in your code, you are trying to read on the wrong file descriptor - it should be new_sd, not sock, which is a server socket and can only accept() new connections.
Edit 0:
Big boo-boo:
if( new_sd = accept(sock, &name, (socklen_t*)&adrlen) < 0) { ...
This is equivalent to:
if( new_sd = (acc... |
6,686,868 | 19,360,565 | Opencv color mapping with direct pixel access | I have a gray scale image that I want to display in color by mapping the gray scale values with a color palette (like colormap in Matlab).
I managed to do it by using OpenCV cvSet2D function, but I would like to access to the pixels directly for performance reasons.
But when I do that the image has strange colors. I tr... | I'm posting this to close the question like asked in the comments of my question.
The answer was:
I found out my error... In fact it's RGB but that wasn't the problem, I had color values at 256 instead of 255... Really sorry... I guess asking the question helped me found the answer
Thank you
|
6,687,048 | 6,687,066 | C/C++ building steps | Could someone please describe, what happens beneath the linking stage of lib_xxxx libraries under *nix-like systems when using ./configure and make commands?
Actually, I have a concrete question:
What happens behind the linking stage in makefiles compared to simply archiving the required .o object files?
So, I'm pretty... | Not all ar utilities are created equal. libtool hides different options, etc., required by different toolchains, and also supports creation of both shared and static libraries.
|
6,687,107 | 6,687,127 | Difference between std::pair and std::tuple with only two members? | Is there a difference between an std::pair and an std::tuple with only two members? (Besides the obvious that std::pair requires two and only two members and tuple may have more or less...)
| There are some differences:
std::tuple is not required by the standard to ever be standard-layout. Every std::pair<T, Y> is standard-layout if both T and Y are standard-layout.
It's a bit easier to get the contents of a pair than a tuple. You have to use a function call in the tuple case, while the pair case is just ... |
6,687,115 | 6,687,299 | when would failbit be set while executing a getline function call in c++ | when would getline in c++ fail?
I have a big snippet of code which I am unable to paste in its entirety for multifarious reasons. I am trying to read from a file , which I know exists and contains data, using getline in C++. But getline fails returning error 123-invalid name(output of getlasterror). I looked up the err... | If the fail bit is set, it is probably because you didn't successfully open the file. Check whether ifFile.is_open() returns true; if not, then then probably indicates that the file is not open correctly. You might not have permissions, or you may need to escape the string properly, or the file may be locked.
You sho... |
6,687,162 | 6,687,233 | C++ some questions on boost::unordered_map & boost::hash | I've only recently started dwelling into boost and it's containers, and I read a few articles on the web and on stackoverflow that a boost::unordered_map is the fastest performing container for big collections.
So, I have this class State, which must be unique in the container (no duplicates) and there will be millions... | This is a bit muddled.
What you say are not "things that you can do to speed things up"; rather, they are mandatory requirements of your type to be eligible as the element type of an unordered map, and also for an unordered set (which you might rather want).
You need to provide an equality operator that compares objec... |
6,687,251 | 6,687,402 | How to provide a trivial class constructors for members of a union? | How can I provide a class that has constructors as part of a union?
I've read that any class that has a trivial constructor can be part of a union. Especially with c++0x, I thought unions are supposed to be unrestricted. Why is this float4 class not suitable? How can I do this?
struct float4
{
union
{
... | VC2010 doesn't implement that part of the C++0x spec yet.
|
6,687,390 | 6,687,496 | Is this code well defined? | I suspect the following chaining of functions would result in unspecified sequence according to the C++ standards (assume C++0x). Just want a confirmation and if anyone could provide an explanation, I'd appreciate it.
#include <iostream>
struct TFoo
{
TFoo(int)
{
std::cout<<"TFoo"<<std::endl;
};
... | The evaluation order is not specified. The relevant section of the draft C++0x spec is 1.9, paragraphs 14 and 15:
14 Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.
15 Except... |
6,687,630 | 6,770,305 | How to remove unused C/C++ symbols with GCC and ld? | I need to optimize the size of my executable severely (ARM development) and
I noticed that in my current build scheme (gcc + ld) unused symbols are not getting stripped.
The usage of the arm-strip --strip-unneeded for the resulting executables / libraries doesn't change the output size of the executable (I have no idea... | For GCC, this is accomplished in two stages:
First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:
-fdata-sections -ffunction-sections
Link the tra... |
6,687,635 | 6,687,679 | problem with array of std::pair in c++? | I was playing around with some code today, and I came across the idea of putting a bunch of pairs in an array, but I havn't been able to get it to work. Here are the code:
#include <utility>
#include <iostream>
std::pair<double,double> * pairArr;
int main(){
pairArr = new std::pair<double,double> [3]; //creating t... | The program as posted does not compile.
Changing the output to
std::cout << pairArr[0].first << pairArr[1].second << pairArr[2].first;
produces the expected result, 11.40.8, that is 1 1.4 0.8 without spaces: https://ideone.com/XAPHX
|
6,687,954 | 6,688,523 | using openFrameworks + CoreAudio | my C++ skills are pretty light but I manage to get stuff done - until I run into a wall. The current wall:
I am using CoreAudio to do some stuff with Midi playback. I've got lots of it working but am stuck on a simple thing. (I don't know the right C++ terminology so bear with me...).
I'm using a render callback functi... | You don't need to mess with static instances to do this. When you add the render callback, pass your C++ object as the refcon, and then cast the refcon to your object in the callback:
// The actual callback is defined as a static function
static OSStatus
myAURenderCallback(void *inRefCon,
AudioUnit... |
6,688,105 | 6,688,134 | pure virtual declarations in subclasses | i have a a couple c++ interfaces like this:
struct IThese {
virtual void doThesethings() = 0;
}
struct IThose : public IThese {
virtual void doThoseOtherThings() = 0;
}
Notice that IThose implement their own method, but also implements those from the other interface, so the idea is that implementors of IThose will ne... | Presently class IThose is abstract class** and you don't have to redeclare doTheseThings() inside it. You can choose to implement doTheseThings() inside class IThose.
If doThesethings() is implemented in class IThose, then it's child class (which derive IThose) may or may not implement it. But they must implement doTho... |
6,688,112 | 6,690,301 | Is this equivalent to a std::string? | Trying to track down a LNK2019 Unresolved External Symbol error on a function that has a number of std::string const & arguments.
Step one of this answer says to check decorated / undecorated names, and this is what I'm seeing in the linker error text in the argument list:
class std::basic_string<char,struct std::char_... | Yes.
As part of the C++ standardization, the std::string class was made more STL-compatible. Like the STL containers, the element type can be chosen. Common choices are char and wchar_t, but Visual C++ users can also use TCHAR. Like STL containers, memory allocation is handled by an allocator.
However, strings are un... |
6,688,118 | 6,688,626 | What is the initialization order for static data members of template class in a file? | In a given file if I have,
struct A { static int a; };
struct B { static int b; };
int A::a;
int B::b;
Then, I can always expect that A::a gets initialized before B::b. Now for the same file, take the template case,
template<typename T>
struct X { static T t; };
template<typename T>
T X<T>::t;
Suppose, X is instantia... | As long as the templates only have one definition (e.g. you only have one translation unit), it's well-defined. The static members are initialized in the order that the template specializations are instantiated in contexts that require the definition of the static data member. From §14.7.1/1 [temp.inst] of the C++03 ... |
6,688,415 | 6,688,512 | C++: Replacement for Singleton | I use singletons a lot because I hate to pass an object of the main class to member classes in order to allow them to access the main class.
Class Foo
{
A* a;
B* b;
C* c;
};
For example in the above example if A,B and C would like to access Foo- I would have to pass the object of Foo each one of them, and ... | This kind of pattern is creating a bunch of circular references, which in general is a code smell. You may want to take a solid look at your design, because the usual way to solve these sort of relationship problems is to create a third class that interacts with both existing classes. Alternately, what wrong with passi... |
6,688,516 | 6,688,556 | How to find places where a non-static method is called? | In the case of the following example,
I can not easily find the places where get() of Book class is called by searching files with get.
Because there are a lot of get which do not belong to Book class.
class Book {
function get() {
}
}
class Pen {
function get() {
}
}
$obj = new Pen;
$obj->get();
$obj = new... | When I use non-static methods, how can I easily find the places where they are called?
A class member function can be called in a number of ways,
Through instance of class
Through polymorphic behavior(dynamic dispatch)
For first case, any reasonably good code analysis tool or IDE will be able to tell you the class from... |
6,688,603 | 6,688,683 | Passing/Moving parameters of a constructor in C++0x | If I have a constructor with n parameters such that any argument to that can be an rvalue and lvalue. Is it possible to do support this with move semantics for the rvalues without writing 2^n constructors for each possible rvalue/lvalue combination?
| You take each one by value, like this:
struct foo
{
foo(std::string s, bar b, qux q) :
mS(std::move(s)),
mB(std::move(b)),
mQ(std::move(q))
{}
std::string mS;
bar mB;
qux mQ;
};
The initialization of the function parameters by the argument will either be a copy-constructor or move-cons... |
6,688,642 | 6,688,654 | getline() omitting the first letter of my output string | Hi i am a newbie in c++ and was doing some basic exercise. my code takes user input and feeds them in an array. Now i am using getline() to get the input string. my code is as follows:
cin.getline(cb[0].name, 200).get(); // Cadburry
cin.getline(cb[1].name, 200).get(); // Snickers
cin.getline(cb[2].name, 2... | The get() calls are consuming the S and the M, remove those and it will work. getline() already consumes the \n
|
6,689,015 | 6,689,609 | How can I play a `mpeg` file in `MFC` | How can I play a mpeg file in MFC.
Can you tell me any function which can play this type of files.
| You can embed windows media player in your application, either by using an ActiveX control and the IWMPPlayer interface. Or by using borland's TMediaPlayer. An example can be found here. I would recommend to stick to the first variant (an ActiveX control) if you want to work in MFC as MFC and Borland C++ builder are no... |
6,689,030 | 6,689,041 | return reference to local variable |
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?!
Here is a code:
#include <iostream>
using namespace std;
double &GetSomeData()
{
double h = 46.50;
double &hRef = h;
return hRef;
}
int main()
{
double nonRef = GetSomeData();
double &ref = GetSomeData();
cout << "nonRef: " << no... | Yes you got lucky.
Returning reference to local variable is Undefined Behavior.
Undefined Behavior means anything can happen and a behavior cannot be defined.
Regarding Undefined Behavior,
C++ Standard section 1.3.24 states:
Permissible undefined behavior ranges from ignoring the situation completely with unpredictabl... |
6,689,132 | 6,689,182 | DLL dependencies for portable C/C++ application for Windows | I want to create a light-weight portable application in C/C++ for Windows. I don't want to statically link everything because I want to keep the size of exe as small as possible. I also use Dependency Walker to track the DLL dependencies of my exe file.
My question is that what are the list of DLL dependencies that an ... | Create a basic Win32 application in something like Visual Studio and check the dependencies with Dependency Walker. Those are your base dependencies. All of the standard Win32 DLL files will be required, including user32.dll, kernel32.dll, and so on. (Although some of this varies, depending on what you want the applica... |
6,689,584 | 6,968,171 | how to convert the Certificate String into X509 structure.? | can any one tell me how to convert the string content into X509 structure . i am using openssl to read the X509 Structure.
example : certificate string
-----BEGIN CERTIFICATE-----
MIIExDCCA6ygAwIBAgIJAK0JmDc/YXWsMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD
VQQGEwJJTjELMAkGA1UECBMCQVAxDDAKBgNVBAcTA0hZRDEZMBcGA1UEChMQUm9j
a3dlbGwgY2... | You can use this OpenSSL code snippet to load the certificate when provided as a string input:
#include <openssl/bio.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
const unsigned char *data =
"-----BEGIN CERTIFICATE-----\n"
"MIIExDCCA6ygAwIBAgIJAK0JmDc/YXWsMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD\n"
/*...*... |
6,689,640 | 6,689,669 | C++ boost::ptr_vector<S>::iterator problem | I have this class:
template <class S, class P, class A>
class Task
{
private:
timeval start;
boost::ptr_vector<S> states;
boost::ptr_vector<P> policies;
public:
P findPolicy(S *state);
S findState(S *state);
};
When I try to define findPolicy or findState using an iterator:
template <class ... | boost::ptr_vector<S>::iterator it;
This needs to use the C++ keyword typename:
typename boost::ptr_vector<S>::iterator it;
Otherwise, C++ doesn't know what ptr_vector<S>::iterator is supposed to be. This is because the definition of ptr_vector<S> depends on the template parameter S, and the value of S is not known ... |
6,689,909 | 6,689,959 | How to easily figure out where and why a program crashed? | I'm currently working on a program (in C++, using Code::Blocks) that uses a lot of random numbers and takes a while to get going; most of the time, it works fine, but every now and then it performs an illegal operation and must shut down. Given the random numbers all over the place, and the fact that it currently take... | That is what debuggers are for. Build the system with full debugging symbols, configure the system so that you get a full crash report (in linux a core file), and then launch the debugger with the core file (alternatively run the whole program inside the debugger, but that might take a while, running inside a debugger ... |
6,689,952 | 6,690,004 | How do you implement Signals and Events in C++? | I am making a Gui Library on top of SDL using C++. (Don't ask me why, I am just doing it to gain some knowledge out of practice in order to understand how Gui libraries are made.) And I want to make a signal connection system like gtk+ or wxWidgets...
g_signal_connect(mybutton,"clicked",gtk_main_quit); //Gtk+
EVT_ME... | The simplest way is borrowing it from a library, for example boost::signal or boost::signal2. The next best thing is implementing your own but borrowing most of the features from libraries like boost::bind (to enable the connections) or using C++0x features that will simplify the generic connection of clients (std::fun... |
6,689,960 | 6,693,372 | How to form Concave shapes from convex pieces Confusion | Hey so i was told in a previous answer that to make concave shapes out of multiple convex ones i do the following:
If you don't have a convex hull, perform a package wrapping algorithm
to get a convex border that encompasses all your points (again quite
fast). en.wikipedia.org/wiki/Gift_wrapping_algorithm
Choose a poi... | Assuming you really want to take a convex polygon (as you've illustrated) and decompose it into convex parts without introducing new vertices, the usual approach is called "ear clipping" and is described in this Wikipedia article, Polygon triangulation. In this approach the convex pieces are triangles, which are neces... |
6,689,996 | 6,690,061 | why do i get the error and ...? | In my program i declared a function prototype like :
void callToPrint(LPTSTR , LPVOID , DWORD , string )
But i get the following error due to this statement : error C2061: syntax error : identifier 'string'
There are other errors also in the code which tell that the function does not take 4 arguments.
(error C2660: 'c... | Your file needs to contain the following line:
#include <string>
The header file string contains the definition for the string class. Because that class is within the std namespace the function prototype needs to be:
void callToPrint(LPTSTR , LPVOID , DWORD , std::string );
Since you're using LPTSTR in the prototype ... |
6,690,089 | 6,690,144 | Why does ostringstream strip NULL? | I have a string whose last part(suffix) needs to be changed several times and I need to generate new strings. I am trying to use ostringstream to do this as I think, using streams will be faster than string concatenations. But when the previous suffix is greater than the later one, it gets messed up. The stream strips ... | It doesn't strip anything. All string literals in C++ are terminated by NUL, so by inserting one manually you just finish the string, as far as anyone processing it is concerned. Use ostream::write or ostream::put, if you need to do that — anything that expects char* (with no additional argument for size) will most lik... |
6,690,177 | 6,691,151 | Problem with QSignalMapper and QAction never triger the Slot | Hi i try to bind slot with argument to QAction triggered SIGNAL
i have this code ,the context menu working great . BUT the OpenPublishWin never triggered .
void MyApp::ShowContextMenu(const QPoint& pos) // this is a slot
{
QString groupID;
QPoint globalPos = ui.treeView_mainwindow->mapToGlobal(pos);
QModel... | A quick look at the Qt docs for QSignalMapper (assuming that is what you're using based on the question title) states that the parameter for the mapped signal is const QString&. I can't recall if the parameter needs to be exact in this case for the connection but it may be a factor.
Additionally, double check that your... |
6,690,215 | 6,690,290 | Which stream functions in C++ control the formatting of input and output values of a class? | Which stream functions in C++ control the formatting of input and output values of a class
| There are manipulator functions.
Also, you can overload the << and >> operators.
|
6,690,256 | 6,690,297 | Why can this code elide a copy? |
Possible Duplicates:
constructor invocation mechanism
Why is it an error to use an empty set of brackets to call a constructor with no arguments?
Why can this code elide all copies of A?
#include <iostream>
class A
{
public:
A() {}
A(const A&) { std::cout << "Copy" << std::endl; }
};
class B
{
public:
B(cons... | The problem is not copy elision, but the meaning of the declaration:
B b(A());
// To get it working the way you expect [1]
B b = B(A());
// Or the slightly more obtuse.
B b((A()));
To the compiler is a function declaration. Google / search SO for the most-vexing-parse. More in the C++ FAQ lite including workarounds.
... |
6,690,341 | 6,732,011 | QSqlQuery Memory issues. QSqlQuery::exec() and QSqlDatabase::open()/close(); | I'm checking the memory usage of an application I've made. It makes numerous calls to read and write values to and from a database (SQLite 3). I've observed the following:
QSqlQuery::exec() uses some KB of RAM to execute a given query, but does not release the memory after it goes out of scope.
QSqlDatabase:: open() &... | It seems that in order to release this memory you must create the QSqlQuery variable as a pointer, and delete this pointer before you close the database:
QStringList values;
db.open();
QString strQuery = "SELECT DISTINCT " + field + " FROM " + table + str;
QSqlQuery *query = new QSqlQuery(db);
query->prepare(strQuery)... |
6,690,360 | 6,690,479 | In MFC CArray, what are reasons to use different default template type? | The MFC CArray class has two template parameters (from MSDN):
template < class TYPE, class ARG_TYPE = const TYPE& >
class CArray
...
The default parameter for ARG_TYPE is const TYPE&, and some questions on SO ask when to use a type different from the default (e.g. Should the ARG_TYPE for a CArray be const & or not, o... | My guess is that, it should be related to inheritance hierarchy.
struct B {};
struct D : B {};
CArray<D, const B&> myArray;
You may want to have the base class as the receiving argument, which can receive a const reference from the derived class.
|
6,690,721 | 6,691,003 | Does the boost.signals2 library need to be built? | My system is having trouble building the boost libraries. I understand that most boost libraries are (fortunately) just headers that do not need to be build (with some exceptions). Does the boost :: signals2 library need to be built? Also is the boost.signals2 library dependant on the boost.signals library?
| Signals is not header-only, signals2 is. But however, signals2 is explicitly developed for thread-safety and if you use boost.thread, this has to be compiled. As far as I know signals2 is not dependent on signals headers.
|
6,691,292 | 6,759,701 | Create CImage from Byte array | I need to create a CImage from a byte array (actually, its an array of unsigned char, but I can cast to whatever form is necessary). The byte array is in the form "RGBRGBRGB...". The new image needs to contain a copy of the image bytes, rather than using the memory of the byte array itself.
I have tried many different ... | Thanks everyone, I managed to solve it in the end with your help. It mainly involved @tinman and @Roel's suggestion to use SetDIBitsToDevice(), but it involved a bit of extra bit-twiddling and memory management, so I thought I'd share my end-point here.
In the code below, I assume that width, height and Bpp (Bytes per ... |
6,691,324 | 6,693,608 | Client connect() failed, server accept() succeeded. Why? | I have a client-server system where simply client should connect to server. Here is what happens when i click Connect on client:
BOOL connectionStatus = m_sockClient.Connect(sIpAddr, 27386);
this call fails (connectionStatus being 0) and GetLastError returns 10035 (try again)
On the other hand, server accepts the conn... | This is expected behavior. The error is WSAEWOULDBLOCK which means you need to wait for the OnConnect event to know when the connection is completely established. I'm not sure if there is a way to make it blocking, the whole point of the async wrapper is to make everything non-blocking. If you want blocking semantic... |
6,691,399 | 6,691,584 | Writing thread safe containers | Could someone recommend good book on how to write thread safe containers?
thanks
| STL port is one STL implementation which offers thread safety, you might want to check it out.
|
6,691,456 | 6,703,277 | Oracle OCCI stmt.setTimestamp insert TIMESTAMP(6): microseconds always 0 | UPDATE: The "fraction of a second" parameter to Timestamp's constructor actually takes nanoseconds... I guessed it was hundredths of a second and my low values were rounded away. Question left for reference....
I'm struggling with Oracle's C++ library - OCCI. Summarily:
creating Timestamp objects and verifying they'... | Turns out the "fractional seconds" field is nominally in nanoseconds rather than hundredths. I wish Oracle would say that in their documents! I say nominally because if it really preserved the least-significant digits then the hundredths values I had would have appeared as a number of nanoseconds and I might have imm... |
6,691,555 | 6,691,829 | converting narrow string to wide string | How can i convert a narrow string to a wide string ?
I have tried this method :
string myName;
getline( cin , myName );
wstring printerName( L(myName) ); // error C3861: 'L': identifier not found
wchar_t* WprinterName = printerName.c_str(); // error C2440: 'initializing' : cannot convert from 'const wchar_t *' to 'wch... | You should do this :
inline std::wstring convert( const std::string& as )
{
// deal with trivial case of empty string
if( as.empty() ) return std::wstring();
// determine required length of new string
size_t reqLength = ::MultiByteToWideChar( CP_UTF8, 0, as.c_str(), (int)as.length(),... |
6,691,560 | 6,691,606 | Understanding on User Defined function | Create a UserArray of bit fields which can be declared as follows: The size occupied by our Array will be less then a normal array. Suppose we want an ARRAY of 20 FLAGs (TRUE/FALSE). A bool FLAG[20] will take 20 bytes of memory, while UserArray<bool,bool,0,20> will take 4 bytes of memory.
Use class Template to create... | W, L and H are non-type template parameters. You can instantiate a template (at compile-time) with constant values, e.g.:
template <int N>
class MyArray
{
public:
float data[N];
void print() { std::cout << "MyArray of size " << N << std::endl; }
};
MyArray<7> foo;
MyArray<8> bar;
foo.print(); // "MyArray o... |
6,691,646 | 6,691,805 | C++ template class Type being forwarded as parameter to object's template function | Ok, I don't know if the title made much sense, so I will just show the code:
template <class S,class P,class A> class Task
{
protected:
timeval start;
boost::ptr_vector<S> states;
boost::ptr_vector<P> policies;
Agent &robot;
const ACTION_MODE &a_mode;
A algo;
public:
Task(Agent &a, AC... | Task<S,P,A>::algo.optimize<P>(policy);
At that point it can't know whether optimize is a value or not. You'll understand if you just look at
Task<S,P,A>::algo.optimize < P
This not only looks like a comparison to you, but also to the compiler. Even if it then proceeds with parsing, it can't know whether your intentio... |
6,691,651 | 6,691,849 | Is it possible to use functions from c++ namespaces with luajit ffi? | I've got a lot of c++ code which contains a lot of functions and classes in namespaces (boost, for example).
Now I'm trying to embed LuaJiT2 as script engine, but I cannot find anything about calling functions and using other stuff from namespaces.
So, Is it possible to pass the functions from c++ namespaces to LuaJIT ... | You may use the standard Lua API to expose namespace-scope functions, as well as class static functions, to Lua. This is done exactly as you would with the regular Lua interpreter, since LuaJIT is drop-in compatible with it.
But you can't use FFI, because FFI is based on a C-based parsing of the header files. And you'r... |
6,691,882 | 6,782,874 | How to run a loop using gui object names in qt? | I have a gui form, where multiple text boxes are present. I want to put their values inside an array. One way of doing it is by writing something like this
{array element } = ui->text_1->text();
and repeat it for text_2,text_3 upto n.
What I want is to run a loop and replace number portion of text box name in each ... | Another option to those listed would be to create an array using an initializer list. Depending on how big the array is (and how often it changes), this might be workable.
QLineEdit* entries[] = { ui->text_0, ui->text_1, ui=>text_2 };
QStringList answers;
for ( int i = 0; i < 3; ++i )
{
answers += entries[i]->text... |
6,692,037 | 6,692,073 | Why myClassObj++++ doesn't incur a compile error : '++' needs l-value just as buildin type do? | Why myint++++ compiles fine with VS2008 compiler and gcc 3.42 compiler ?? I was expecting compiler say need lvalue, example see below.
struct MyInt
{
MyInt(int i):m_i(i){}
MyInt& operator++() //return reference, return a lvalue
{
m_i += 1;
return *this;
}
//operator++ need it's op... | No, overloaded operators are not operators - they're functions. So GCC is correct to accept
that.
myobj++++; is equivalent to myobj.operator++(0).operator++(0);
Caling a member function (including overloaded operator) on a temprorary object of class type is allowed.
|
6,692,232 | 6,692,335 | Error on building OpenCV (C++) | Building my code (below) returns error 'imread' is not a member of 'cv'.
I am using:
Ubuntu 11.04.
libcv is at 2.1.0-3ubuntu1
CMake as a build system (with only project(foo) and add_executable(foo main.cpp) in it.)
main.cpp:
#include <opencv/cv.h>
int main(int argc, char **argv) {
cv::Mat src = cv::imread("frame... | You should include opencv/highgui.h.
|
6,692,238 | 6,692,273 | Better logging library for C++ | In our project now we using log4cxx, but those library don't develope some years, also we have some problems with it.
Could you advise some library for logging in C++.
Library must support multithreade logging, system-log.
Also it'll be good if it support logging via << operator.
Also lib license must be very democrac... | boost::log is probably the most versatile and well-written logging library I've seen. It's pretty complicated but really genius at the same time. And it does everything you can think of and then some more.
|
6,692,249 | 6,692,293 | error C2664: 'callToPrint' : cannot convert parameter 1 from 'std::wstring' to 'LPTSTR' | I converted a narrow string to the wide string as follows :
string nameOfPrinter;
getline( cin , nameOfPrinter );
wstring WprinterName;
int number = MultiByteToWideChar( CP_UTF8 , 0 , nameOfPrinter.c_str() , nameOfPrinter.size() , &WprinterName , 0 );
// then i make a call to the function whose prototype is callToPrin... | You also need to use .c_str() here.
Also, I'd read the printer name directly into WprinterName, using
getline(wcin, Wprintername);
|
6,692,280 | 6,692,325 | member object constructor and enum | Why does this not compile?
File.hpp
class CTest
{
public:
enum enumTest { EN_TEST };
//constructor:
CTest(enumTest f_en);
};
AnotherFile.hpp
#include "File.hpp"
class CAnotherTest
{
public:
CTest obj_Test(CTest::EN_TEST);
};
Visual Studio says: error C2061: syntax error : identifier 'EN_TEST'
... | Because,
CTest obj_Test(CTest::EN_TEST);
is evaluated as a function named obj_Test. Now it should have argument as a type, however, CTest::EN_TEST is a value, not a type.
If it's intended that obj_Test an object then you have pass CTest::EN_TEST to it in the constructor:
class CAnotherTest
{
public:
CAnotherTest () ... |
6,692,406 | 6,697,083 | Build fails when including C++ files | I have an XCode project (Objective-C) to which I'm trying to add a C++ library I've coded earlier. As soon as I add a single .cpp or .mm file, the build process will trip up on random things, usually when building the prefix header. The same thing happens when I include .c files. Basically, I can only use .m files in m... | I'm an idiot. For some reason the return type was missing from the function.
CG_EXTERN void CGFontGetGlyphsForUnichars(CGFontRef font, void* chars, CGGlyph* glyphs, int len)
CG_AVAILABLE_STARTING(__MAC_10_2, __IPHONE_2_0);
|
6,692,660 | 6,692,744 | c++ increase buffer size | im implementing a tcp/ip service in c++. what happen is that the server will receive data and each data may contain 1 or more messages. the server is only allow to receive a max of e.g 100 bytes of data per round. so in scenario 1, if a message is of 120 bytes, it will be split into 2 data. so i create a global static ... | Use a std::vector instead. Will save you soooo much hassle.
|
6,692,880 | 6,693,088 | How to deal with last comma, when making comma separated string? |
Possible Duplicates:
Don't print space after last number
Printing lists with commas C++
#include <vector>
#include <iostream>
#include <sstream>
#include <boost/foreach.hpp>
using namespace std;
int main()
{
vector<int> VecInts;
VecInts.push_back(1);
VecInts.push_back(2);
VecInts.push_back(3);
VecIn... | How about this:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <sstream>
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
std::ostringstream ss;
if(!v.empty()) {
st... |
6,692,982 | 6,693,047 | How to assign value to left side using Overload operator[]? | I have made the following code:-
class A{
bool bFlag[2];
public:
A(){
for(int i = 0; i < 2; i++)
bFlag[i] = false;
}
bool operator[](int r){ //i know how to assign value to R.H.S using operator[]
if( r >= 0 || r < 2 ){
bFlag[r] = true;
return bFlag[r];
}
retu... | Als is right, but here is an example:
class A{
private:
int val[10];
public:
A(){}
int& operator[](int i) {
return val[i];
}
};
this makes in posible to do things like
A a;
a[2] = 2;
you should of course add the old method as well. to optimize for l-value to making it.
class A{
private:
i... |
6,693,010 | 6,693,107 | How do I use MultiByteToWideChar? | I want to convert a normal string to a wstring. For this, I am trying to use the Windows API function MultiByteToWideChar.
But it does not work for me.
Here is what I have done:
string x = "This is c++ not java";
wstring Wstring;
MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , x.size() , &Wstring , 0 );
The last line ... | You must call MultiByteToWideChar twice:
The first call to MultiByteToWideChar is used to find the buffer size you need for the wide string. Look at Microsoft's documentation; it states:
If the function succeeds and cchWideChar is 0, the return value is the required size, in characters, for the buffer indicated by lp... |
6,693,015 | 6,693,136 | A good C++ native multimedia library? | Can anyone recommend a portable, c++ native multimedia library? I've tried SDL, but it doesn't interface well with classes, as it is a c library.
| There’s SFML – the “Simple and Fast Multimedia Library” – which is essentially a object-oriented, platform-independent, OpenGL-based alternative to SDL and which looks really quite promising.
It allows to write very clear code with no special attention to resource cleanup:
#include <SFML/Graphics.hpp>
int main() {
... |
6,693,051 | 6,693,145 | CMAKE: performing a file copy AFTER a custom command has run | I have a build script fragment that looks as follows:
foreach(...)
...
add_custom_command( OUTPUT ${fn_c} ${fn_s} ${fn_p_c} {fn_p_h}
COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} --proto_path=${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${proto_var} --cpp_out=. --plugin=protoc-gen-RBLRPC=${C... | Don't use file(COPY...) function, but add the following command to your add_custom_command:
COMMAND ${CMAKE_COMMAND} copy ${CMAKE_CURRENT_BINARY_DIR}/${fn_c}
${CMAKE_SOURCE_DIR}/include/rpc/marshall
But for what you're going to do, I would suggest you keep your source tree clean, add directly use the generated... |
6,693,073 | 6,797,136 | In C++ how to convert a string to class object? | For example i have a class named "WaterScene", in the .xml i have saved as string "WaterScene" when i read the .xml i have to convert that string to class. One approach is just string comparison
if( string == "WaterScene")
return new WaterScene;
Is there any generic way to do this to avoid string comparison? Like in ... | I have used Generic Class factory to solve the issue... First i am registering class and storing it in a map before main().
|
6,693,218 | 6,693,303 | on-line recording with ffmpeg | Is this possible? Someone tried to do on-line recording of audio and video(of the screen) with ffmpeg? I read everything google can find about ffmpeg in the net. The variant of recording I deed load CPU to 100%, but it still can't convert frames with appr. speed relevant to how fast frames are recording, audio go good,... | Recording audio/video of the screen is possible with ffmpeg. People do this for the purposes of screen casting. Performance of this depends on the hardware in use, the codecs used and various other factors.
See this post (or this one) for some further advice and command line use.
|
6,693,413 | 6,693,480 | Function returning reference, what to return on failure? | As a consequence of the design of a framework I'm targeting with a plugin, I've implemented a part of my code as a singleton. This class is responsible for handling connections to an external program with which I'm communicating from within the framework.
Enabling the external communication is a runtime setting, howe... | Add a public function
static bool IsServiceEnabled();
and throw an exception in getInstance, when it's called while ServiceEnabled == false;
|
6,693,493 | 6,693,574 | Why does sscanf not work properly with a bool type | The output of this code:
const char *buff = "*_2D 1";
char field[10];
int flag;
sscanf(buff, "%s %d", field, &flag);
printf("field:%s flag:%i\n", field, flag);
is field:*_2D flag:1
However by changing the int to bool results in strange behaviour:
const char *buff = "*_2D 1";
char field[10];
bool flag;
sscanf(buff, "%... | Imagine if bool is only one byte, rather than the four (or even eight) that an int uses. Then telling sscanf that &flag is a pointer to an int will end up overwriting either three or seven bytes elsewhere on the stack -- which could be right on top of your field variable. That space would be filled with 0 bytes, effect... |
6,693,706 | 6,694,352 | Interface pattern with shared_ptr | I want to have the following class structure:
#include <tr1/memory>
class Interface;
class Impl;
class Impl
{
public:
Impl( std::tr1::weak_ptr< Interface > interface );
private:
std::tr1::weak_ptr< Interface > interface_;
};
class Interface
{
public:
Interface() { impl_ = new Impl( this ); }
private:
... | I solved it by removing the need to use shared_ptr< Interface > from the Impl.
The underlying problem was that the Interface is a Node in a directed acyclic graph. Each node knows its parents and children, so implementing a Node::addChild( shared_ptr< Node > child ) is impossible, since the node cannot be added as a we... |
6,693,739 | 6,694,841 | How to create custom file templates i VC++ 2010? | I want to make a custom file template for .cpp and .h files in VC++ 2010 but can't figure out how to do this.
All I want to include in the files that I create is:
/*
* File: main.cpp
* Author: NoobiCake
*
* Created on 14. juli 2011, 14:57
*/
int main( int argc, char* args[] ) {
return 0;
}
It's just like in Ne... | A simple way to do it, is to create a macro to insert the desired text, and bind it to a key.
|
6,694,469 | 6,694,630 | Programming style: object with passages by references or value? (c++) | This is a general question on programming style. Let's say I have an object Line which has some methods and private variables Point point_a_ and Point point_b_. Let's say that at some point I need to change the position of the two points. What programming style would you prefer between the following cases? They all do ... | In this simple scenario I might just use public member variables.
Otherwise I would provide getters that return a const reference and matching setters.
class Line {
public:
Line(const Point& p1, const Point&p2) : m_p1(p1), m_p2(p2) {}
const Point& p1() const
{ return m_p1; }
const Point& p2() const
... |
6,694,544 | 6,694,575 | What debugger can check c++ code for memory leaks? |
Possible Duplicate:
how to find memory leak in c++ code/project
I would like to ask what debugger should I install in order to check for memory leaks? I have an .a that contains a .cpp and an .h . I used a lot of pointers and references. Now I would like to test for memory leaks.
I heard about lint. Does this exist... | You need memory debugging, memory leak detection, and profiling tool like Valgrind.
Debuggers don't usually do that.
|
6,694,702 | 6,695,539 | std::getline alternative when input line endings are mixed | I'm trying to read in lines from a std::istream but the input may contain '\r' and/or '\n', so std::getline is no use.
Sorry to shout but this seems to need emphasis...
The input may contain either newline type or both.
Is there a standard way to do this? At the moment I'm trying
char c;
while (in >> c && '\n' != c && ... | OK, here's one way to do it. Basically I've made an implementation of std::getline which accepts a predicate instead of a character. This gets you 2/3's of the way there:
template <class Ch, class Tr, class A, class Pred>
std::basic_istream<Ch, Tr> &getline(std::basic_istream<Ch, Tr> &is, std::basic_string<Ch, Tr, A>& ... |
6,694,745 | 6,694,802 | How to delete multiple dynamically allocated arrays in a single delete statement? | If I have 3 pointers to double :
rdf1 = new double [n];
rdf2 = new double [n];
rdf3 = new double [n];
I want to delete them with a single delete statement. something like :
delete [] rdf1,rdf2,rdf3;
What's the right way to do it ?
| Unfortunately, this is syntactically correct:
delete [] rdf1,rdf2,rdf3;
More unfortunately, it doesn't do what you think it does. It treats , as a comma operator, thus eventually deleting only rdf1 (since operator delete has precedence over operator ,).
You have to write separate delete [] expressions to get the expec... |
6,694,945 | 6,695,003 | How to create C++ class in android project via Eclipse? | In order for reuse ability on iOS, I would like to write the logic for my Android game in C++ rather than java. How can I create a C++ class in eclipse and integrate it into my application?
I have read "native C++ code can be used on Android as well using the Native Development Kit (NDK)". What is the latest and greate... | Investigate using the JNI and NDK here:
http://developer.android.com/sdk/ndk/index.html
|
6,695,218 | 6,704,554 | Invisible runtime errors in threads | I am writing a C++ application for an embedded Linux. I have a problem where runtime errors, like unhandled exceptions and segmentation faults, that occur in threads other than the main thread are not displayed in the console. In such cases my application will be terminated abruptly without any error message. Is there ... | I found out that these runtime-errors are displayed in the syslog files, that completely fulfills my requirements.
|
6,695,261 | 6,695,453 | Template within template: why "`>>' should be `> >' within a nested template argument list" | I know that when we are using template inside another template, we should write it like this:
vector<pair<int,int> > s;
and if we write it without the whitespace:
vector<pair<int,int>> s;
we will get an error:
`>>' should be `> >' within a nested template argument list
I see this is understandable, but I just can't h... | Sometimes you want it to be >>. Consider
boost::array<int, 1024>>2> x;
In C++03 this successfully parses and creates an array of size 256.
|
6,695,273 | 6,695,373 | Return struct as void | I'm having a function that returns a a void data. And i need to receive it as a structure.
eg. say a structure widget_data. a function GetObjectData() that returns a void data.
widget_data *wd=GetObjectData();
and GetObjectData() returns sd->data.
where sd is structure, data is of void type.
when i compile it i get er... | Let's clarify things a little first. void means nothing, so you cannot have a data of void type. Thus, if function returns void then is cannot possibly return any data. Now, the void * is a void pointer. You can treat it as a memory address pointing somewhere. It could be pointing to any kind of data, or even nowhere. ... |
6,695,309 | 6,695,577 | How to change the C++ boost posix_time::ptime's resolution to millisecond? | I'm trying to print a boost::posix_time::ptime in the format of "YYYY-MM-DD hh:mm:ss.fff" where the MM is a 2-digit month and fff a 3-digit millisecond. An example is: 2011-07-14 22:38:40.123.
I'm using Boost 1.33.1.
I tried to call the API "ptime::to_simple_string()" but it doesn't meet my need: this method prints th... | The simple, pragmatic solution would be to use %f and always strip the last 3 characters from the result.
|
6,695,410 | 6,695,535 | gdb front end to use with vim? | What gdb frontends can I use with vim for debugging C and C++ code? Currently I use cgdb and am satisfied with it. Was just wondering what else is out there?
| Google is your friend.
http://clewn.sourceforge.net/
Honestly, I think that you're better off sticking with cgdb.
|
6,695,538 | 6,997,516 | Adding scroll bar to widget containing a layout in QT C++ | I am new to QT and I am creating a widget that has a gridlayout. The gridlayout contains a matrix of QLineEdit widgets. The window resizes to fit the layout but when layout is large it goes off screen. When I maximize the screen, the QLineEdit widgets are resized to fit the screen and for large layouts they become extr... | I fixed my problem by creating a QMainWindow with the menu bar. Then created a widget which includes the layout, set the Scroll Area to the widget. Finally set the central widget of the main widow to the scroll area.
|
6,695,731 | 6,695,735 | Is it possible for the main function to be a friend of a class? | I know that this is detrimental to data hiding but theoretically is this allowed ?
| Of course.
main is an almost completely ordinary function.
|
6,696,033 | 6,696,201 | Specialize C++ member function based on class template argument | I have a class with a template parameter which should decide which of two styles of data it contains. Based on that parameter I want to implement a member function one of two different ways. I tried using Boost Enable-If, but without success. Here's the version of the code that I'm most surprised doesn't work:
#incl... | Since you are going to be making two different versions of getRange() anyways, you can always overload your struct String member functions depending on the type of PadSide. I know it's not as "pretty", but in the end, it's still a similar amount of code, and you won't have to make multiple class types.
template<PadSid... |
6,696,324 | 6,714,080 | Code-completion / Project type in Eclipse | I have a project which is under SVN source control. I can easily set up Subversive for Eclipse, connect to the repository and check out the code. Once I've done this (from the SVN perspective) it appears just fine as a project in the C++/C perspective.
The problem is, eclipse doesn't seem to recognise it as a C++ proje... | Provided the answer in the comment. For the bonus question, I'd check out the subfolders into separate projects, sort of how I would do when developing Eclipse plugins.
|
6,696,342 | 6,696,415 | C++: Weird shared library error - eclipse | I'm trying to compile some code. Here is the error I'm getting:
error while loading shared libraries: libcudart.so.4: cannot open shared object file
Now I've included /usr/local/cuda/include and linked to /usr/local/cuda/lib and passed the -lcudart flag on the compile prompt.
Yet I still get this run-time error!
I've j... | This usually happens with old code when they change the folder structure. Locate where the file is expected in the old code, then make a sym link to where it actually is.
Also try launching eclipse as root. Or running:
ldconfig /usr/local/cuda/lib
|
6,696,664 | 6,696,919 | Why is this QT app exiting with a SIGABRT signal? | I'm new to Qt. So I started to reimplement one of the get started examples: link.
However I get a SIGABRT signal when closing the windows. The reason for this is obvoisly due to some memory managment error.
Below you find the callstack and the relevant code. The line editWindow.setLayout(&layout); causes the error. Is... | Many different Qt functions will take ownership of the object being passed in which means it assumes control over all memory management and will free it upon delete. From the setLayout docs:
The QWidget will take ownership of layout.
After you have called setLayout it has a parent and its parent deletes it in additi... |
6,696,706 | 9,177,949 | node.js native addon - destructor of wrapped class doesn't run | I'm writing a node.js addon in C++. I wrap some class instances using node::ObjectWrap, to associate the native instance with a javascript object. My problem is, the wrapped instance's destructor never runs.
Here is an example:
point.cc
#include <node.h>
#include <v8.h>
#include <iostream>
using namespace v8;
using n... | Garbage collection is not guaranteed in V8 - it's only executed when the engine is running out of memory. Unfortunately that means you'll probably have to call a release function manually if you need to release resources - which would not be too great for the users of a JS API. (You can attach it to process.on('exit') ... |
6,696,780 | 6,696,847 | Template class for non-inline member functions | I am trying to follow an example here:
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
But I dont want to inline my function definitions with my class definition.
Will I have to put
template<typename Data>
concurrent_queue<Data>::
in front of all my fun... | Yes, you will, and the definitions will still need to be in the header file. This is why everyone uses inline definitions- because they basically have to be inline anyway.
|
6,696,808 | 6,697,120 | get # of rows and # of columns of a square matrix from vector c++ | I have a vector of size lets say 4:
vector <double> example;
example.push_back(3.0);
example.push_back(10.1);
example.push_back(33.1);
example.push_back(23.3);
so I have [3 10.1 33.1 23.3];
If I know I have a square matrix (i.e. sizes can only be 4, 9, 16, 25, 36, 49...)
How do I know the # of rows which is the same ... | A two-dimensional array allocated as contiguous locations will be faster than a vector of vectors or an array of vectors. A vector has a slight disadvantage in that functions must be called to access the vector (although the compiler may optimize these out).
For example:
enum {MATRIX_SIZE = 4};
// Define a square mat... |
6,696,939 | 6,697,197 | Problem with C++ Partial Template Specialization | I have a situation similar to this:
template<class A, class B>
class MyClass<A, B>
{
...
static A RARELY_USED_A;
}
// Seems to work but does not cover all possible cases, since
// there may be instances of A that have no numeric limits.
template<class A, class B>
A MyClass<A, B>::RARELY_USED_A= std::numeric_limit... | Use inheritance to reuse and specialize without duplicating all the common code:
template<typename A>
struct RarelyUsedShared
{
static A RARELY_USED_A;
};
template<typename A>
A RarelyUsedShared<A>::RARELY_USED_A = std::numeric_limits<A>::max();
template<>
string RarelyUsedShared<string>::RARELY_USED_A = "";
tem... |
6,697,286 | 6,697,689 | catching exception from boost::filesystem::is_directory | I am currently catching errors from boost::filesystem::is_directory and showing the error to the user by calling "what()" on the exception. This gives the reason for failure but the error is strange to the user. For example:
boost::filesystem::is_directory: Access is denied
How can I catch the boost error and figur... | By "nicer error message" would you mean something like
#include <iostream>
#include <boost/filesystem.hpp>
int main()
{
boost::filesystem::path p("/proc/1/fd/1");
try {
boost::filesystem::is_directory(p);
} catch(const boost::filesystem::filesystem_error& e)
{
if(e.code() == boost::system:... |
6,697,292 | 6,697,334 | Pinging from a C/C++ program | I want to write a C or C++ program, that given an IP address, Pings it and then performs further action based on whether the Ping was successful or not.
How to do this?
| Have a blast at The Ping Page, which has a link to full source on the original Unix ping(8).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.