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 |
|---|---|---|---|---|
2,859,801 | 2,859,894 | How do I connect two apps | I am considering building an app in C++ that will be parsing text from the web and create some statistical results. These results I want to be fed in an external app in real time. The external app (to whose code I have no access, but can ask for a - paid - custom made addition) will then need some code to read and use ... | There are a number of IPC mechanisms to choose from from (sockets, shared memory, pipes, ...). I guess the "best choice" will depend to a large extend on how the other application is structured aka. how much your custom extension will cost you.
I don't know much of your environment but it might be worthwhile to have a ... |
2,859,950 | 2,859,995 | Register management tips | Implementing a custom VM and I've come to use registers (these will store pointers and will be NULL when empty). But, I've come to realize that I actually have no idea how to manage register-based memory. Like, what do I do if all my registers are used up and some code wants another? Preferably, without just creating a... | I don't think this is a problem of the machine, instead it is a problem of the programmer of the machine. What you can do(IMO) is just to provide the means to move the values of the registers into memory back and forth. Problem solved :)
|
2,859,980 | 2,859,997 | Conversion between classes | Let's say we have a class called A and another one called B.
and we want to have a conversion method that converts A to B.
In the software architecture point of view, which one is preferred?
write A.export()
write B.import()
write a converter class, i.e. convert(A, B) or Convert(A) or ...
if the language matters, I'm... | It entirely depends on how you intend to use it, but in many cases, the cleanest way to do this is to implement a converting constructor:
class B { };
class A
{
A(const B& b) { }
};
B b;
A a = b; //< calls converting constructor
(of course, you could implement a converting constructor for converting from A to B, ... |
2,860,006 | 2,879,303 | Good code visualization / refactoring tools for C++? | I've found myself coming across a lot of reasonably large, complicated codebases at work recently which I've been asked to either review or refactor or both. This can be extremely time consuming when the code is highly concurrent, makes heavy use of templates (particularly static polymorphism) and has logic that depen... | There is a KDevelop plugin for code visualization:
http://liveblue.wordpress.com/2009/08/21/gsoc-wrap-up-static-code-visualization-in-kdevelop/
|
2,860,068 | 2,860,086 | Linkage of namespace functions | I have a couple of methods declared at the namespace level within a header for a class:
// MyClass.h
namespace network {
int Method1(double d);
int Method2(double d);
class MyClass
{
//...
}
}
then defined in
//MyClass.cpp
int
Method1(double d)
{ ... }
int
Method2(double d)
{ ... }
This project compiles clea... | It looks like you've put the function declarations inside a namespace block, but forgotten to put the function implementations inside a namespace block as well. Try:
namespace network {
int
Method1(double d)
{ ... }
int
Method2(double d)
{ ... }
}
|
2,860,252 | 2,860,273 | g++ doesn't think I'm passing a reference | When I call a method that takes a reference, g++ complains that I'm not passing a reference. I thought that the caller didn't have to do anything different for PBR. Here's the offending code:
//method definition
void addVertexInfo(VertexInfo &vi){vertexInstances.push_back(vi);}
//method call:
sharedVertices[index]-... | VertexInfo(n1index, n2index) creates a temporary VertexInfo object. A temporary cannot be bound to a non-const reference.
Modifying your addVertexInfo() function to take a const reference would fix this problem:
void addVertexInfo(const VertexInfo& vi) { /* ... */ }
In general, if a function does not modify an argu... |
2,860,390 | 2,860,421 | Cannot refer to a template name nested in a template parameter | I have the following code:
template <typename Provider>
inline void use()
{
typedef Provider::Data<int> D;
}
Where I'm basically trying to use a template class member 'Data' of some 'Provider' class, applied to 'int', but I get the following errors:
util.cpp:5: error: expected init-declarator before '<' token
uti... | typedef typename Provider::template Data<int> D;
The problem is that, when the compilers parses use() for the first time, it doesn't know Provider, so it doesn't know what Provider::Data refers to. It could be a static data member, the name of a member function or something else. That's why you have to put the typenam... |
2,860,475 | 2,860,672 | How to access CWebBrowser class instance (defined in a protected class) in a different class? C++ | I have been playing with this webbrowser control example
I got it working and added some timers using ON_WM_TIMER.
Now I would like to access the m_Browser (CWebBrowser class instance) defined inside the protected CMyBrowserView class into a different class. (for example CMyBrowserApp in the code sample) and use .Navi... | Create a subclass of CMyBrowserView and add a method for each of the things you want the
browser to do. The method should call the appropriate method on m_Browser.
E.g.
class CBrowserViewEx : public CMyBrowserView
{
...
void Navigate(LPCTSTR URL, VARIANT* Flags,
VARIANT* TargetFrameName, VAR... |
2,860,524 | 2,860,611 | qapps runs well but breakpoint sometimes generates segmentation fault | I have a qApp that generates a segmentation fault only when a breakpoint is inserted in the code (I can put it at different places) and only after 4-5 breakpoint stops. Do I have a problem with my code or is this a DBG bug. the method is part of a QThread Class.
Basically what I did is i took the mandlebrot example,... | It looks like the problem is that you have unsynchronized access to some object in your code and breakpoints are happily allows you to see the problem.
|
2,860,593 | 2,860,632 | What is the difference between Visual C++ and C++? | Well here's a rather stupid question. Is Visual C++ JUST an IDE?? Or is it a language on its own for win32? What exactly would be the difference between the two? This I ask because I was trying out some of my old C++ code on VC++ 2008 and it wouldn't compile.
| Visual C++ can be many things, including:
Microsoft's C++ compiler (cl.exe, link.exe etc)
The IDE (Visual Studio in C++ mode)
The C runtime (MSVCRT)
Other libraries (less so): MFC, ATL
As for compiling old C++ code: Visual Studio is now a fairly compliant C++ compiler. This was not always the case, such as with Visua... |
2,860,634 | 2,860,690 | Checking for duplicates in a vector |
Possible Duplicate:
Determining if an unordered vector<T> has all unique elements
I have to check a vector for duplicates. What is the best way to approach this:
I take the first element, compare it against all other elements in the vector. Then take the next element and do the same and so on.
Is this the best way t... | Use a hash table in which you insert each element. Before you insert an element, check if it's already there. If it is, you have yourself a duplicate. This is O(n) on average, but the worst case is just as bad as your current method.
Alternatively, you can use a set to do the same thing in O(n log n) worst case. This i... |
2,860,673 | 2,860,739 | Initializing a C++ vector to random values... fast | Hey, id like to make this as fast as possible because it gets called A LOT in a program i'm writing, so is there any faster way to initialize a C++ vector to random values than:
double range;//set to the range of a particular function i want to evaluate.
std::vector<double> x(30, 0.0);
for (int i=0;i<x.size();i++) {
... | Right now, this should be really fast since the loop won't execute.
Personally, I'd probably use something like this:
struct gen_rand {
double range;
public:
gen_rand(double r=1.0) : range(r) {}
double operator()() {
return (rand()/(double)RAND_MAX) * range;
}
};
std::vector<double> x(num_ite... |
2,860,691 | 2,861,709 | IE Address bar search. I need to add a list of other results at the end of current result list | Currently, if you type in the address bar in IE, you see a dropdown list of url search results depending on what you type.
I'd like any hint, anything, about how to access the address bar object throught a BHO in C++, so that
i can append url results from my bho at the end the current list.
Thank you.
If anyone need pr... | There is no direct way to do this. You can add your urls to History using IUrlHistoryStg, and then they will show up if they match what the user types.
|
2,860,722 | 2,860,869 | linker error when using tr1::regex | I've got a program that uses tr1::regex, and while it compiles, it gives me very verbose linker errors.
Here's my header file MapObject.hpp:
#include <iostream>
#include <string>
#include <tr1/regex>
#include "phBaseObject.hpp"
using std::string;
namespace phObject
{
class MapObject: public phBaseObject
{
... | Regex support for C++0x is incomplete and wasn't there for TR1, see the implementation status page for C++0x/TR1.
Boost offers an alternative TR1 implementation as well as the original library it is based on.
|
2,860,846 | 2,860,857 | IE status bar. I need to add a clickable icon to the status bar | My bho (Browser Helper Object) is a sidebar (right-sided iframe) that needs to be opened/closed by clicking the status bar icon in IE (IE8). I didn't find any informations for clickable icons. Anyone knows wich interface to use to do that. Thank you. (I'm using ATL: Active Template Library).
If anyone need precisions, ... | Modification of IE's Status Bar by add-ons is not supported and is likely to cause reliability and performance problems across IE versions. You should consider using a Menu item instead, as Menu items ARE supported extensibility points.
|
2,860,968 | 2,861,420 | Qtimer not timing out QT, C++ | I am learning C++ and using QT.
I have a small program in which I am trying to update the text of the PushButton every second. The label being current time. I have a timer that should time out every second, but seems like it never does. here's the code.
Header File
#ifndef _HELLOFORM_H
#define _HELLOFORM_H
#include "u... | You don't include the Q_OBJECT macro at the beginning of your class. You need it if your class declares any signals or slots (at least, if you want them to work). In fact, it's generally a good practice to include it in any class that is derived from QObject.
Modify your class declaration to look like this:
class Hel... |
2,860,997 | 2,861,066 | Accessing initialized variable on different class C++ | I'm having some difficulties with this problem.
The main idea is, I initialized a variable of class type B in class A, class A.h has the variable Z declared as public, like B *Z;
In class A.cpp, I initialized it as Z = new B();
Now, I want to access that variable from class C and I'm unable to do so. C.h includes A.h a... |
I initialized a variable of class type
B in class A
#pragma once
#include "B.h"
class A
{
public:
B* Z;
A()
{
Z = new B();
}
}
B.h
#pragma once
class B
{
}
C.h
#pragma once
#include "A.h"
class C
{
A a; //here you construct A
C()
{
a.Z = new B(); //you can read/writ... |
2,861,101 | 2,861,356 | Static initialization of a struct with class members | I have a struct that's defined with a large number of vanilla char* pointers, but also an object member. When I try to statically initialize such a struct, I get a compiler error.
typedef struct
{
const char* pszA;
// ... snip ...
const char* pszZ;
SomeObject obj;
} example_struct;
// I only want to ... | Your initialization of ex performs copy-initialization. It takes the value on the right and uses it to initialize the variable on the left. For class-type members, the appropriate constructor is used. In your case, that means invoking the copy constructor for SomeObject, but you've made that constructor private, so the... |
2,861,216 | 2,861,698 | Browser tabs create multiple instances of my sidebar for each tab; I only want one sidebar | I have a sidebar (iframe). The problem is, if you open a second tab (in the same browser) it creates a new instance of the same sidebar. That means i have now 2 sidebars. In exemple, if i close the sidebar in the first tab, i would like to have it closed in the second tab as well.
Is it possible to have only one instan... | You can't change how IE works, so if you really want to do this, you have hoops you need to jump through, or you can fake it.
You can fake it by just living with multiple instances and synchronizing their state yourself.
If you really want to have just one, you can have your sidebar be simple a host for a child windo... |
2,861,270 | 2,861,312 | returning an abstract class from a function | Is it possible to return an abstract class(class itself or a reference, doesn't matter) from a function?
| You can return an abstract class pointer - assuming B is a concrete class derived from abstract class A:
A * f() {
return new B;
}
or a reference:
A & f() {
static B b;
return b;
}
or a smart pointer:
std::unique_ptr<A> f() {
return std::make_unique<B>(...);
}
|
2,861,366 | 2,861,391 | Demystifying gcc under lpthreads | in these days i'm playing with thread library and trying to implement some functions.
One of the tutorial says that to run the program use :
gcc -lpthread -lrt -lc -lm project1.c scheduler.c -o out
first of all i need deep understanding of what is gcc doing in each line,
lpthread is used for what? what are the contri... | -l parameter means - link to a specific library. See GCC manual for more information
Thus -lpthread means link to libpthread.so (or pthread.a)
Likewise for -lm -lrt, -lc
[lib]pthread[.so] - POSIX threads
[lib]m[.so] - math standard library (sin, cos, e.t.c.)
[lib]rt[.so] - POSIX realtime extensions
[lib]c[.so] - libc ... |
2,861,478 | 2,894,927 | 2d HUD not drawing properly over QGLWidget (using QPainter) | I am trying to display HUD over my 3D game. For starters, I am just trying to display "Hello World", but I haven't had any success yet! The scene freezes / flickers once I am done.
I am using Qt/C++ and QGLWdiget / QPainter to get this done. I have used overpainting example as my reference to get started. Here is what ... | For anyone who is still struggling with this and came across this post: here is how I solved it::
Please follow the overpainting example as is. If you look over at the code in the example, you would notice in the constructor, a timer timeout() SIGNAL is connected to animate() SLOT. If you look closely at the animate() ... |
2,861,497 | 2,880,658 | C++ boost function overloaded template | I cannot figure out why this segment gives unresolved overloaded function error (gcc version 4.3.4 (Debian 4.3.4-6)):
#include <algorithm>
#include <boost/function.hpp>
// this does not work
int main1()
{
typedef boost::function<const int&(const int&, const int&)> max;
max m(&std::max<int>);
}
// this does no... | Update: this is a gcc bug that has been fixed in gcc >=4.4. bugzilla. Also, revised my answer with a reduced test case.
There are two components to this problem: the way boost::function adopts a function pointer and the gcc bug.
boost::function - There is something strange about the error message you listed in the que... |
2,861,523 | 2,865,124 | boost.asio's socket's receive/send functions are bad? |
Data may be read from or written to a
connected TCP socket using the
receive(), async_receive(), send() or
async_send() member functions.
However, as these could result in
short writes or reads, an application
will typically use the following
operations instead: read(),
async_read(), write() and
as... | The read, async_read, write, and async_write are composed functions that call the class functions multiple times until the requested number of bytes is transmitted. They are included by the library as a convenience. Otherwise, every developer would need to implement the same logic.
The class functions wrap the underlyi... |
2,861,532 | 2,861,557 | Infrequent segmentation fault in accessing boost::unordered_multimap or struct | I'm having trouble debugging a segmentation fault. I'd appreciate tips on how to go about narrowing in on the problem.
The error appears when an iterator tries to access an element of a struct Infection, defined as:
struct Infection {
public:
explicit Infection( double it, double rt ) : infT( it ), recT( rt ) {}
d... | Correct me if I'm wrong but I would bet that erasing an item in an unordered multimap invalidates all iterators pointing into it. Try "it = carriage.erase(it)". You'll have to do something about ret as well.
Update in reply to your latest update:
The reason breaking out of the loop after calling "carriage.erase(it)" ... |
2,861,761 | 2,862,023 | Is it good practice to separate code into blocks? | If I have a method that does multiple, related things, is it good practice to stick each "thing" that the method does into a seperate block?
Ex.
{
int var
//Code
}
{
int var
//More Code
}
It would help reduce the number of local variables, and make the code more readable, but I'm not sure if it's a good idea.
| Well, it's certainly good practice to restrict the scope of variables as much as possible. They're less likely to be re-used unnecessarily, and you're more likely to define them when you declare them, which avoids bugs due to undefined variables and such. There are also plenty of cases where you have an object which do... |
2,861,839 | 2,861,859 | Can the template parameters of a constructor be explicitly specified? | A constructor of a class can be a template function. At the point where such a constructor is called, the compiler usually looks at the arguments given to the constructor and determines the used template parameters from them. Is there also some syntax to specify the template parameters explicitly?
A contrived example:
... | No. The C++03 standard says:
[Note: because the explicit template argument list follows the function template name, and
because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for t... |
2,862,105 | 2,862,113 | A question on vectors, pointers and iterators | Guys, I have a midterm examination tomorrow, and I was looking over the sample paper, and I'm not sure about this question. Any help would be appreciated.
Let v be a vector<Thingie*>, so that each element v[i] contains a pointer to a Thingie. If p is a vector<Thingie*>::iterator, answer the following questions:
what t... |
what type is p?
p is of type vector<Thingie*>::iterator, whatever type that happens to be.
what type is *p?
*p is a Thingie*&; that is, it is a reference to the element in the vector at which the iterator points.
what code provides the address of the actual Thingie?
*p, since the elements of the vector are poin... |
2,862,195 | 2,862,290 | Idiomatic use of auto_ptr to transfer ownership to a container | I'm refreshing my C++ knowledge after not having used it in anger for a number of years. In writing some code to implement some data structure for practice, I wanted to make sure that my code was exception safe. So I've tried to use std::auto_ptrs in what I think is an appropriate way. Simplifying somewhat, this is ... | It is not idiomatic to write your own container: it is rather exceptional, and for the most part useful only for learning how to write containers. At any rate, it is most certainly not idiomatic to use std::autp_ptr with standard containers. In fact, it's wrong, because copies of std::auto_ptr aren't equivalent: only o... |
2,862,236 | 2,862,436 | STL member variable initalization issue with windows API | I am creating a windows app that uses a vector of stings as a member variable. For some reason, I can compile but when it tries to get at any of the vectors members is crashes. the error is 0xC0000005: Access violation reading location 0xcdcdcdd9. in the member function of the vector class.
this is the size() functi... | I've come across this kind of thing before. Most likely cause is a corrupt heap.
|
2,862,242 | 2,862,250 | Casting problem cant convert from void to float C++ | as i said i get this horrible error i dont really know what to do anymore
float n= xAxis[i].Normalize();
thats where i get the error and i get it cuz normalize is a void function this is it
void CVector::normalize()
{
float len=Magnitude();
this->x /= len;
this->y /= len;
}
i need normalize to stay as void th... | A void function doesn't return anything, so there's nothing to assign to n.
You should return some value from normalize to assign it to n.
float CVector::normalize()
{
float len=Magnitude();
this->x /= len;
this->y /= len;
return 10.0;
}
|
2,862,284 | 2,862,316 | Returning a C++ reference in a const member functions | A have a class hierarchy that looks somethign like this:
class AbstractDataType {
public:
virtual int getInfo() = 0;
};
class DataType: public AbstractDataType {
public:
virtual int getInfo() { };
};
class Accessor {
DataType data;
public:
const AbstractDataType& getData() const {
retu... | No you do not need to use a pointer. You can use a reference or a pointer equally in this case.
The code you pasted should work and does work in g++ 4.4 and Visual Studio 2010.... other than the missing semicolons after the class declarations.
I'm guessing maybe your code here doesn't match exactly the code you are com... |
2,862,346 | 2,862,369 | Storing header and data sections in a CSV file | This should be relatively easy to do, but after several hours straight programming my mind seems a bit frazzled and could do with some help.
I have a C++ class which I am currently using to store read/write data to file. I was initially using binary data, but have decided to store the data as CSV in order to let progra... | The most sensible way is don't do it. Let an existing library do it for you. You'll never be able to put the requisite amount of work into this class that you'll need to maintain backwards compatibility and changing requirements.
Use an existing solution, like Google's protocol buffers. They're stored in binary - so... |
2,862,398 | 2,869,379 | SWIG-Lua question on class returning another class | I am concreting a question I had earlier.
I have two classes in C++ and I use SWIG to wrap them. A method in one class can return a pointer to the other class. How can I get Lua to see it as more than just a userdata?
More concretely:
I have
class fruit
{
int numberofseeds;
//some other stuff about fruit constru... | If your SWIG .i file is set up correctly, you can use the ":" operator:
local y = x:getfruit()
local z = y:getseedcount()
See the "Classes" section (23.2.7) of the SWIG Lua documentation.
If that doesn't work you need to tell SWIG how to convert a fruit* out parameter to a Lua representation using a typemap in your .i... |
2,862,454 | 2,862,476 | what is the reason of Invalid Address specified to RtlFreeHeap | the develop environment is vs2008, the language is c++, when I release the problem,at beginning it run with out problem but after several minutes it stop and show error like that : HEAP[guessModel.exe]: Invalid Address specified to RtlFreeHeap( 003E0000, 7D7C737B ).
who can tell me the reason of the error. thank you ve... | My guess is that you are trying to use the wild pointer. Either the pointer to the memory which got freed has been de-referenced or some invalid pointer has been passed to free function.
It is very hard to tell the reason without seeing the actual code. You can attach some debugging tools like WinDbg and get the cause ... |
2,862,462 | 2,866,548 | I have a BrowserHelperObject(BHO) in c++ and i need to block some keyboard controls (Ctrl-o) in a i-frame | I need to know of a way to prevent the user to 'open a new url' (with Ctrl + O) as soon as he has the focus on my sidebar (right-sided iframe).
In fact, my sidebar offers some controls and the user should not be able to 'navigate' to other website through the sidebar.
I'm using a bho in C++ using ATL(active template li... | Implement IInputObject and pay special attention to HasFocusIO.
|
2,862,562 | 2,862,588 | Path String Concatenation Question | Please see my code below.
ifstream myLibFile ("libs//%s" , line); // Compile failed here ???
I want to combine the path string and open the related file again.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("libs//Config.txt");
// Ther... | The ifstream constructor does not work that way. Its first parameter is a C string to the file you want to open. Its second parameter is an optional set of mode flags.
If you want to concatenate the two strings, just concatenate the two strings:
std::string myLibFileName = "libs/" + line;
ifstream myLibFile(myLibFile... |
2,862,636 | 2,869,136 | C++: FFMPEG and SDL resources | I'm looking for resources (preferably books, but websites are fine too) for using FFmpeg and/or SDL with C++.
Stuff I'd like to be able to do (eventually):
Decode and play videos in realtime to a QT widget (the QT part isn't a problem)
Overlay text and images on the video (in realtime)
Loop video
Cross-fade from one v... | If all you need is to decode and play videos and require overlays I would consider using the Phonon framework, and use QT Graphics View by using a Phonon::VideoWidget inside a QGraphicsProxyWidget. That way you can easily get overlays, cross-fading, animations etc. Phonon in Windows uses DirectShow as a back-end. You... |
2,862,852 | 2,862,879 | Returning reference to object is not changing the address in c++ | I am trying to understand functions returning a reference. For that I have written a simple program:
#include<iostream>
using namespace std;
class test
{
int i;
friend test& func();
public:
test(int j){i=j;}
void show(){cout<<i<<endl;}
};
test& func()
{
test temp(10);
return temp; //// Address of t... | There are several problems in your code:
(1) That is not how you want to return a reference. temp(10) is an automatic (i.e. resides in stack) variable and will be destroyed once your program goes out of scope of the test function. A better way to show this would be to return a reference to a variable passed (e.g. for c... |
2,862,875 | 2,862,944 | C++ overloading virtual = operator | here is the code for my question:
class ICommon
{
public:
virtual ICommon& operator=(const ICommon & p)const=0;
};
class CSpecial : public ICommon
{
public:
CSpecial& operator=(const CSpecial & cs)const
{
//custom operations
return *this;
}
};
CSpecial obj;
Basically: I want the interface ICommon to force ... | To echo what Naveen said, the operator=() defined in CSpecial isn't compatible with the one defined in ICommon, and results in an overload rather than an override. While you can have covariant return types (as you've done), the arguments themselves can't be covariant.
Furthermore, you've defined the ICommon::operator=... |
2,862,915 | 2,863,634 | C++ CRTP(template pattern) question | following piece of code does not compile, the problem is in T::rank not be inaccessible (I think) or uninitialized in parent template.
Can you tell me exactly what the problem is?
is passing rank explicitly the only way? or is there a way to query tensor class directly?
Thank you
#include <boost/utility/enable_if.hp... | In CRTP the base class template take advantage of the fact that member function bodies (definitions) are not instantiated until long after their declarations. In your code the base class depends on incomplete type.
|
2,862,993 | 2,863,313 | iPhone/iPad C++ Example | Does anyone know where or how to obtain a C++ example to create iPhone apps? What I am looking for is just using C++ (no objective-C or just the bare essential objective-C) and no interface builder, source only.
Can ayone help me locate such a beast?
| You can download Carmack's source for Wolfenstein3D for the iphone to see what a program that only uses the minimum of Objective-C necessary to run looks like.
He uses C mixed with Objective-C in this case ,but as everyone has mentioned, there's no way to avoid using some Objective-C if you plan on linking against the ... |
2,863,347 | 2,863,360 | Declaring the array size with a non-constant variable | I always thought that when declaring an array in C++, the size has to be a constant integer value.
For instance:
int MyArray[5]; // correct
or
const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct
but
int ArraySize = 5;
int MyArray[ArraySize]; // incorrect
Here is also what is explained in The C++ Programmin... | This is a GCC extension to the standard:
You can use the -pedantic option to cause GCC to issue a warning, or -std=c++98 to make in an error, when you use one of these extensions (in case portability is a concern).
|
2,863,420 | 2,863,440 | Error in VC++ for code that looks perfectly good C++? | Hey guys. Check out this piece of sample code.
#include "stdafx.h"
#include<conio.h>
#include<string.h>
class person{
private char name[20];
private int age;
public void setValues(char n[],int a)
{
strcpy(this->name,n);
this->age=a;
}
public void display()
{
printf("\nName = %s",name);
printf("\nAge ... | The syntax of declaring public and private is wrong. Unlike other languages, in C++ it should be
class person{
private:
char name[20];
int age;
public:
void display();
....
|
2,863,450 | 2,863,841 | C++ console output in Netbeans | When I run a C++ program in Netbeans on a Mac that has cout or printf statements the output is displayed in a terminal opened using X11. Is there a console built into Netbeans? If yes, how do I change the output to it?
Thanks,
Spencer
| Under Project Properties -> Run -> Console Type you can choose "Output Window" instead of External Terminal.
|
2,863,519 | 2,863,546 | Arena in Malloc Function | I am using malloc_stats() to print malloc related statistics in which I am finding "Arena 0" for some programs and "Arena 0 and Arena 1" for some other programs.
What do these arenas represent?
| See link text. It looks like heap is a collection of arenas ("sub-heaps") to handle memory allocation between several threads, thus reducing contention.
|
2,863,836 | 2,863,921 | Do Java programs ever crash? | I am a c++ programmer , I know little bit about java. I know that java programmers do not have to work with memory directly like C++. I also know that most crashes in C++ appliations are due to memory corruptions.
So can an application written in Java crash due to a memory related issue?
Thanks
| Contrary to some other answers I’ll claim that Java programs will crash as often, or possibly even more often than C++ programs.
By “crash” most people understand that a program encounters an error that isn’t properly handled, causing the application to terminate. Well, this of course happens and has got nothing to do ... |
2,864,004 | 2,864,020 | C++ Basic Class Layout | Learning C++ and see the class laid out like this:
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
I know Java and methods(functions) in Java are written within the class. The class looks like... | There's a difference. When you write the definition of the function within the class definition (case 2), then the function is considered to have been declared inline. This is standard C++.
Usage, is to declare the member functions (Java methods) within the class definition, in a header file (.h), and to define these m... |
2,864,058 | 2,864,123 | Custom iterator which converts values before saving it | A typical forward iterator is expected to implement following methods:
value_type& operator*();
value_type* operator->();
I'm writing a custom iterator for a custom container where user expects to see a value_type different from representation of the value inside a container. So when returning a value_type value to us... | You might want to take a look into the implementation of the std::vector<bool> specialization iterators, as they tackle the same problem. Note that with time, the specialization has been frown upon mainly because it does not comply with the container requirements (the iterators don't provide references to the actual co... |
2,864,066 | 2,864,462 | Determine if the current thread has low I/O priority | if (reader.is_lazy()) goto tldr;
I have a background thread that does some I/O-intensive background type work. To please the other threads and processes running, I set the thread priority to "background mode" using SetThreadPriority, like this:
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
Howe... | Well it fails if you've already set it to background mode. Could you, dependent on whether you would like it to be background processing, not just Set the priority to background begin and see if it fails?
If you'd expect/want it not to be then you could test by calling background end.
If thats not good to you you'd pr... |
2,864,306 | 2,864,809 | How to reverse PNG for drawing | I make game Mario and I want when I use left key < , the character will turn his head to left :-?
How can I implement that ? Thanks for reading this :)
| BitMap::RotateFlip(RotateNoneFlipY)
|
2,864,307 | 2,864,326 | Can't I send NULL as a parameter with a constructor? | Lets say i have a Shape object that has a constructor like this:
Shape( width, height, radius, depth )
Now, I just have a silly rect so i dont need redius and depth... is it okey to do
Shape myRect(50, 50, NULL, NULL) ?
I know its not the best idea and I should use inheritance and stuff but this is the mess im in so... | Depends on what types radius and depth are. If they are integers, you have to use an out-of-bound value like -1 to indicate "not set" (out-of-bound could also be 0 if you declare it that way). If they are pointers, NULL could be used.
Actually what you describe is a common example of bad inheritance, and it's used in O... |
2,864,337 | 2,864,745 | What's the purpose of `qt_noop` | I just found the existence of qt_noop() define in the qglobal.h as:
inline void qt_noop() {}
What's the point of it?
| I know it's used internally in some macros that should do something only for debug builds, for example:
# ifndef QT_NO_DEBUG
# define Q_ASSERT(cond) ((!(cond)) ? qt_assert(#cond,__FILE__,__LINE__) : qt_noop())
# else
# define Q_ASSERT(cond) qt_noop()
# endif
#endif
|
2,864,450 | 2,866,707 | UTC timestamp in millisecond using C++ under Windows | How do I get the UTC time in milliseconds under the Windows platform?
I am using the standard library which give me UTC time in seconds. I want to get the time in milliseconds. Is there a reference of another library which give me the accurate UTC time in milliseconds?
| GetSystemTime() produces a UTC time stamp with millisecond resolution. Accuracy however is far worse, the clock usually updates at 15.625 millisecond intervals on most Windows machines. There isn't much point in chasing improved accuracy, any clock that provides an absolute time stamp is subject to drift. You'd need... |
2,864,574 | 2,864,648 | Problem building stripped down version of Qt 4.6.2 | I'm trying to build a smaller version of Qt, I used the following configuration options:
./configure -qt-sql-mysql -no-qt3support -no-audio-backend -no-phonon -no-phonon-backend -no-opengl -no-script -no-scripttools -no-javascript-jit -no-webkit -no-svg -no-multimedia -fast
After executing make, I eventually run into ... | It is trying to build the Assistant (that is the tool you us to view Qt documentation) tool, the Assistant needs webkit. If you don't need Assistant in your application when you are distributing it, just exclude it from the build
|
2,864,804 | 2,864,824 | Template specialization within template definition: is this supported for all compilers or standard usage? | This compiled on VS 2008, but it seems like non-standard usage of templates.
template <class T>
class Foo
{
public:
void bar(Foo<int> arg)
{
// do some stuff here
}
// more code ...
};
Is there an issue since the template specialization Foo<int> is contained within the definition of its own template class... | It's not really specialisation - you are just saying that function takes a parameter of type Foo <int> - the fact that the function is itself a member of the Foo class isn't really important. And yes, it's legal.
|
2,865,036 | 2,865,437 | Why can't we overload "=" using friend function? | Why it is not allowed to overload "=" using friend function?
I have written a small program but it is giving error.
class comp
{
int real;
int imaginary;
public:
comp(){real=0; imaginary=0;}
void show(){cout << "Real="<<real<<" Imaginary="<<imaginary<<endl;}
void set(int i,int j){real=i;imaginary=j;}
friend comp operat... | The assignment operator is explicitly required to be a class member operator. That is a sufficient reason for the compiler to fail to compile your code. Assignment is one of the special member functions defined in the standard (like the copy constructor) that will be generated by the compiler if you do not provide your... |
2,865,396 | 2,865,777 | Bit manipulation, permutate bits | I am trying to make a loop that loops through all different integers where exactly 10 of the last 40 bits are set high, the rest set low. The reason is that I have a map with 40 different values, and I want to sum all different ways ten of these values can be multiplied. (This is just out of curiosity, so it's really t... | A bit more complicated, but done purely by bit manipulation. Your example:
#define WIDTH 4
#define BITS 2
void printbits(long pattern) {
long bit;
for (bit = 1L << WIDTH - 1; bit; bit >>= 1)
putchar(pattern & bit ? 49 : 48);
putchar('\n');
}
void movebits(pattern, bit) {
long mask = 3L << bit;
while (((... |
2,865,451 | 2,865,554 | Marshalling an array of shorts: "Mismatch has occurred" | I have the following C++ struct:
typedef struct FormulaSyntax{
WORD StructSize;
short formulaSyntax [2];
} FormulaSyntax;
I have a DLL method which takes an instance of this struct. Here's what I've tried on the C# side:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
p... | Found the answer here: Here is what my C# struct needed to look like - it needed the MarshalAs line. It works now.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FormulaSyntax {
public short StructSize;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = Unmanaged... |
2,866,048 | 2,866,156 | Who deletes the copied instance in + operator ? (c++) | I searched how to implement + operator properly all over the internet and all the results i found do the following steps :
const MyClass MyClass::operator+(const MyClass &other) const
{
MyClass result = *this; // Make a copy of myself. Same as MyClass result(*this);
result += other; // Use += to add o... | Under the circumstances, I'd probably consider something like:
MyClass MyClass::operator+(MyClass other) {
other += *this;
return other;
}
Dave Abrahams wrote an article a while back explaining how this works and why this kind of code is usually quite efficient even though it initially seems like it shouldn... |
2,866,194 | 2,866,542 | DeferWindowPos and SWP_SHOWWINDOW/SWP_HIDEWINDOW | I am writing a virtual desktop application which utilises the DeferWindowPos API functions. The current method I am using is moving the windows off the screen if they're not on the current virtual desktop. However I know wish to also hide the windows that are off-screen so they do not appear on the task bar. I have att... | In addition to the rtfm, DeferWindowPos is eventually going to call SetWindowPos. SetWindowPos always validates its parameters by passing them to the WindowProc via WM_WINDOWPOSCHANGING so, unless you are also hooking every windows WindowProc as part of your virtual desktop manager, moving them off screen is going to f... |
2,866,307 | 2,866,407 | BYTE typedef in VC++ and windows.h | I am using Visual C++, and I am trying to include a file that uses BYTE (as well as DOUBLE, LPCONTEXT...) , which by default is not a defined type.
If I include windows.h, it works fine, but windows.h also defines GetClassName wich I don't need. I am looking for an alternative to windows.h include, that would work with... | You need to include windows.h to get those types. If you want to reduce the number of defines that windows.h brings in, you can #define WIN32_LEAN_AND_MEAN before including windows.h, which will exclude a lot of stuff (but not everything). See http://support.microsoft.com/kb/166474.
|
2,866,399 | 2,866,415 | Should I 'delete' this CDC? | Folks,
I'm trying to track down an intermittant bug that's showing up on site.
I've a feeling it's in some GDI code I'd to cobble together to get a tally printer working.
I'm connfused over how to delete this CDC, my code looks OK to me, but is this correct.
// Create a device context for printing
CDC* dc = new CD... | Since you allocated dc on the heap, yes you do need to delete dc. Not only that but if you keep the code as you have it you should also have a delete dc before your throw. The DeleteDC function is not related to the allocated memory of dc.
You could simplify to this though:
// Create a device context for printing
CDC... |
2,866,539 | 2,866,631 | C++ Header Guard issues | I am making a small C++ framework, which contains many .h and .cpp.
I have created a general include which include all my .h file such as:
framework.h
#include "A.h"
#include "B.h"
#include "C.h"
each .h header are protected with include guard such as
#ifndef A_HEADER
#define A_HEADER
...
#endif
The issues is, I wo... | Basically what your doing is #include "A.h" in framework.h and #include "framework.h" in A.h. This causes cyclic dependency of the header files and you will get errors such as undefined class A. To solve this, use forward declarations in header file and #include only in corresponding cpp file. If that is not possible t... |
2,866,878 | 2,867,583 | C++ hash table w/o using STL | I need to create a hash table that has a key as a string, and value as an int. I cannot use STL containers on my target. Is there a suitable hash table class for this purpose?
| Here's a quick a dirty C hash I just wrote. Compiles, but untested locally. Still, the idea is there for you to run with it as needed. The performance of this is completely dependant upon the keyToHash function. My version will not be high performance, but again demonstrates how to do it.
static const int kMaxKeyL... |
2,866,897 | 2,866,929 | what happens when you copy vector<boost::share_ptr> to another vector | Do we get multiple copies of the pointers yet the data members are still being shared?
boost::shared_ptr<string> a1(new string("Hello"));
vector<boost::shared_ptr<string> > a;
a.push_back(a1);
vector<boost::shared_ptr<string> > b;
b = a;
cout<<a[0]->c_str()<<b[0]->c_str()<<endl;
a1->append(" ... | Yes. But don't take my word for it, try it and see.
|
2,867,340 | 2,867,483 | How to create a string array in MATLAB? | I would like to pass a vector of strings from C++ to MATLAB. I have tried using the functions available such as mxCreateCharMatrixFromStrings, but it doesn't give me the correct behavior.
So, I have something like this:
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
vector<s... | Storing a vector of strings as a char matrix requires that all of your strings are the same length and that they're stored contiguously in memory.
The best way to store an array of strings in MATLAB is with a cell array, try using mxCreateCellArray, mxSetCell, and mxGetCell. Under the hood, cell arrays are basically a... |
2,867,451 | 2,868,355 | Is is possible to make a shaped, alpha-blended dialog? | I'm making a non-rectangular dialog, modelled over an image from Photoshop (the image is the background of the dialog, and the user will see trough the transparent part of the image). I'ts like a dashboard-style window for a media-app with a few custom-drawn controls. Most of the background-image is either opaque or 10... | Perhaps you could use layered windows? I haven't tested these with WTL but you should be able to get the effect you want. To the best of my knowledge I don't think you can add controls to a layered window so you'll need to attach it to another (non-layered) window to use controls.
|
2,867,511 | 2,867,535 | Const Functions and Interfaces in C++ | I'll use the following (trivial) interface as an example:
struct IObject
{
virtual ~IObject() {}
virtual std::string GetName() const = 0;
virtual void ChangeState() = 0;
};
Logic dictates that GetName should be a const member function while ChangeState shouldn't.
All code that I've seen so far doesn't follow th... | I think it's laziness/carelessness. GetName() should have no effect on the object's state, and the contract of IObject should state that fact explicitly.
If the inheriting class was somehow forced to make GetName() have (hidden!) side effects, they could always declare the corresponding fields as mutable.
|
2,867,666 | 2,867,693 | C++: Filling vector from the pipe | I would like to fill my vector<float> from command line:
more my.txt | myexe.x > result.txt
What is the best way to open the pipe in C++?
Thanks
Arman.
| Your shell will connect the standard output of more to the standard input of myexe.x. So you can just read from std::cin, and need not worry whether the input comes from the keyboard or from some other program.
For example:
vector<float> myVec;
copy(istream_iterator<float>(cin), istream_iterator<float>(),
back_ins... |
2,867,755 | 2,868,732 | What does IUrlHistoryStg::BindToObject Method do? | I'm looking for a way to access the address bar search so that i can append some personnal url at the end of the current list, and i found 'IUrlHistoryStg::BindToObject' but there is no documention linked to it. Anyone knows what this method does ?
On msdn: http://msdn.microsoft.com/en-us/library/aa767718%28VS.85%29.as... | It's not implemented, so it doesn't do anything. It was a bad idea that didn't get removed in time to not have it be in the SDK.
Use IShellFolder::BindToObject() instead.
|
2,867,758 | 2,867,832 | How to generate a LONG guid? | I would like to generate a long UUID - something like the session key used by gmail. It should be at least 256 chars and no more than 512. It can contain all alpha-numeric chars and a few special chars (the ones below the function keys on the keyboard). Has this been done already or is there a sample out there?
C++ or... | As per your update2 you are correct on Guids are predicable even the msdn references that. here is a method that uses a crptographicly strong random number generator to create the ID.
static long counter; //store and load the counter from persistent storage every time the program loads or closes.
public static string ... |
2,867,821 | 2,910,806 | C++ boost::lambda::ret equivalent in phoenix | Boost lambda allows to overwrite deduced return type using ret<T> template.
I have tried searching for equivalent in phoenix but could not find one.
Is there an equivalent in phoenix? I know how to make my own Replacement but I would rather not. thank you
| Rewrite: I missed the point on my first answer (it was late), let me try again.
Let me give some exposition for people like me who might miss your point the first time. In boost::lambda, when using user defined types in operator expressions, one has to use the ret<> function to override return type deduction. This is... |
2,868,121 | 2,868,141 | What is the problem with this code? | #include<stdio.h>
class A { public: int a;};
class B: public A {
public:
static int b;
B(){
b++;
printf("B:%d\n",b);
}
};
int main() {
A* a1 = new B[100];
A* a2 = new B();
return 0;
}
Error:
In function `main':
undefined reference to `B::b'
undefined reference to `B::b'
u... | Static variables need to be allocated outside the class. Add this line outside the class B:
int B::b;
Think of static variables as being declared with the extern keyword. They still need to be allocated somewhere. This means the allocation should never be in the header file!
|
2,868,301 | 2,868,319 | Why does C++ behave this way? | #include<stdio.h>
class A { public: int a;};
class B: public A {
int c;
int d;
};
int main() {
A* pA = new B[10];
B* pB = new B[10];
printf("\n%d", pA->a);
pA++;
printf("\n%d", pA->a); // prints junk value
printf("\n\n%d", pB->a);
pB++;
printf("\n%d", pB->a);
return 0... | It can only know that at runtime. Imagine it slightly changed
A* a;
if(runtimevalue)
a = new A[10];
else
a = new B[10];
But that's not going to happen. C++ puts emphasize in speed, but this would basically make it into a language that ensures safety of operations. There is Java, C# and others that already solve th... |
2,868,351 | 2,868,887 | Windows Threading: beginthread or QueueUserWorkItem (C++) | I am wondering whether to use beginthread or QueueUserWorkItem for threaded methods in C++. What are the differences between the two APIs and in what context are they better suited?
Thanks,
BTW, I have read this question Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
| QUWI uses a thread from the thread pool to execute the callback function. Such threads are very light weight but not suitable for all types of threaded tasks. Basic requirements are that they need to be relatively short-lived, don't block very often and are not time critical.
It is all rather well explained in the SD... |
2,868,373 | 2,868,572 | C++ Beginner - Simple block of code crashing, reason unknown | Here's a block of code I'm having trouble with.
string Game::tradeRandomPieces(Player & player)
{
string hand = player.getHand();
string piecesRemoved;
size_t index;
//Program crashes while calculating numberOfPiecesToTrade...
size_t numberOfPiecesToTrade = rand() % hand.size() + 1
for (; numberOfPiecesToTr... | stick a breakpoint into your for loop to give you a better idea of what's going on. I would bet that the for loop is going infinite and causing the program to hang.
On hitting the breakpoint, check your iterator variables and see if you can see anything out of the ordinary
|
2,868,439 | 2,868,506 | Is there a way to limit an integer value to a certain range without branching? | Just out of curiosity. If I have something like:
if(x < 0)
x = 0;
if(x > some_maximum)
x = some_maximum;
return x;
Is there a way to not branch? This is c++.
Addendum: I mean no branch instructions in the assembly. It's a MIPS architecture.
| There are bit-tricks to find the minimum or maximum of two numbers, so you could use those to find min(max(x, 0), some_maximum). From here:
y ^ ((x ^ y) & -(x < y)); // min(x, y)
x ^ ((x ^ y) & -(x < y)); // max(x, y)
As the source states though, it's probably faster to do it the normal way, despite the branch
|
2,868,485 | 2,868,527 | Cast vector<T> to vector<const T> | I have a member variable of type vector<T> (where is T is a custom class, but it could be int as well.)
I have a function from which I want to return a pointer to this vector, but I don't want the caller to be able to change the vector or it's items. So I want the return type to be const vector<const T>*
None of the ca... | If you have a const vector<int> you cannot modify the container, nor can you modify any of the elements in the container. You don't need a const vector<const int> to achieve those semantics.
|
2,868,493 | 2,869,398 | How to return array of C++ objects from a PHP extension | I need to have my PHP extension return an array of objects, but I can't seem to figure out how to do this.
I have a Graph object written in C++. Graph.getNodes() returns a std::map<int, Node*>. Here's the code I have currently:
struct node_object {
zend_object std;
Node *node;
};
zend_class_entry *nod... | I simply needed to MAKE_STD_ZVAL(node_zval). A secondary issue with this code was that I was reusing this zval pointer, thus overwriting every previous zval and ending up with an array full of the same object. To remedy this, I initialize node_zval for each loop. Here's the final code:
PHP_METHOD(Graph, getNodes)
{
... |
2,868,662 | 2,879,690 | SWT-like GUI toolkit for C or C++ | Do you know any cross-platform GUI toolkit like swt for C (using default widgets in each operating system = right pics on eclipse.org/swt) ? There is an implementation of swt for D language called DWT but I need it for C or C++. Thanks.
|
Qt (community)
wxWidgets
FLTK
GTK+
FOX
Notus
VCF - EDIT2 seems to be inactive for a few years
You can read some details in that wiki.
First 4 are pretty popular, the rest I dont know.
EDIT:
8. There is C++ port but it seem Windows only for now
9. SWT/Fox - C++ port on top of FOX toolkit - seems to be dead for more th... |
2,868,673 | 2,868,992 | How to support comparisons for QVariant objects containing a custom type? | According to the Qt documentation, QVariant::operator== does not work as one might expect if the variant contains a custom type:
bool QVariant::operator== ( const QVariant & v ) const
Compares this QVariant with v and
returns true if they are equal;
otherwise returns false.
In the case of custom types, their
eq... | The obvious answer is to cast the data out of with var1.value<MyEnum>() == var2.value<MyEnum>() to compare them, but that requires you to know the type when comparing. It seems like in your case this might be possible.
If you are just using enums, you could also convert it to an int for storage in the QVariant.
Edit: ... |
2,868,680 | 2,868,729 | What is a cross-platform way to get the current directory? | I need a cross-platform way to get the current working directory (yes, getcwd does what I want). I thought this might do the trick:
#ifdef _WIN32
#include <direct.h>
#define getcwd _getcwd // stupid MSFT "deprecation" warning
#elif
#include <unistd.h>
#endif
#include <string>
#include <iostream>
using names... | If it is no problem for you to include, use boost filesystem for convenient cross-platform filesystem operations.
boost::filesystem::path full_path( boost::filesystem::current_path() );
Here is an example.
EDIT: as pointed out by Roi Danton in the comments, filesystem became part of the ISO C++ in C++17, so boost is n... |
2,868,955 | 2,868,971 | shielding #include within namespace { } block? | Edit: I know that method 1 is essentially invalid and will probably use method 2, but I'm looking for the best hack or a better solution to mitigate rampant, mutable namespace proliferation.
I have multiple class or method definitions in one namespace that have different dependencies, and would like to use the fewest n... | Just think of #including as copying and pasting the contents of the included file to the position of the #include directive.
That means, yes, everything in the included file will be inside the namespace.
|
2,868,956 | 2,869,003 | lambda+for_each+delete on STL containers | I'm trying to get a simple delete every pointer in my vector/list/... function written with an ultra cool lambda function.
template <typename T>
void delete_clear(T const& cont)
{
for_each(T.begin(), T.end(), [](???){ ???->delete() } );
}
I have no clue what to fill in for the ???'s. Any help is greatly appreciat... | Two issues here: the lambda syntax itself, and how to get the value type of a container:
To call the mydelete() function on each pointer (assuming you've defined a mydelete() member function):
for_each(c.begin(), c.end(), [](typename T::value_type x){ x->mydelete(); } );
To delete them using the delete operator:
for_e... |
2,869,183 | 2,869,584 | Segmentation fault in std function std::_Rb_tree_rebalance_for_erase () | (Note to any future readers: The error, unsurprisingly, is in my code and not std::_Rb_tree_rebalance_for_erase () )
I'm somewhat new to programming and am unsure how to deal with a segmentation fault that appears to be coming from a std function. I hope I'm doing something stupid (i.e., misusing a container), because ... | Possibly you're holding onto an iterator into ce across the call to recover. If recover happens to remove that item the iterator will be invalidated and any future use (say an attempt to erase it) could result in a seg fault.
It would help if we could see more context of how ce is used before and after the call to reco... |
2,869,515 | 2,871,936 | What should be done in place of ddeexec for MDI apps? | We have been using ddeexec registry entries to handle opening a design from Explorer.
MSDN (about 2/3 way into article) indicates that ddeexec is deprecated, and applications should use IDropTarget instead.
What is unclear to me is how that this actually is supposed to work..
e.g. If I have Foo.exe, which is intended t... | When you use IDropTarget, it simulates a drag&drop (XP and later, you must use DDE or whatever on older systems)
As luck would have it, Raymond Chen recently did a blog post about IDropTarget with sample code.
|
2,869,552 | 2,869,688 | Simple average calculation | I'm trying to write program calculating average of given numbers stored in an array. Amount of numbers should be not more than 100, and user should input them until a !int variable is given :
#include <iostream>
#include <conio.h>
using namespace std;
double average(int tab[], int i){
int sum=0;
for(int j=0;... | isdigit tests whether the character is a digit. The test is only reached following assigning 0 to number, and 0 is a control code, not a digit, so isdigit(0) is always false, and so your while condition is always true.
...
number=0;
...
} while( !isdigit(number) );
Instead, test the input stream to dete... |
2,869,594 | 2,869,667 | How return a std::string from C's "getcwd" function | Sorry to keep hammering on this, but I'm trying to learn :). Is this any good? And yes, I care about memory leaks. I can't find a decent way of preallocating the char*, because there simply seems to be no cross-platform way.
const string getcwd()
{
char* a_cwd = getcwd(NULL,0);
string s_cwd(a_cwd);
free(a_c... | If you want to remain standard, getcwd isn't required to do anything if you pass to it a NULL; you should instead allocate on the stack a buffer that is "large enough" for most occasions (say, 255 characters), but be prepared for the occasion in which getcwd may fail with errno==ERANGE; in that case you should allocate... |
2,869,785 | 2,870,146 | Point to point linear gradient? | I want to make an application that can generate point to point gradient (like Photoshop does). I'm familiar with how to generate an up to down gradient but not point to point. How is this conceptually done.
Thanks
| I can't say if this is exactly how Photoshop does it, or that it's the most optimal way of doing it, but this should be the basic principle.
Think of the two points as defining a vector. You can find a normal vector for this, which will be perpendicular to the original vector (since that's the definition of a normal ve... |
2,870,005 | 2,877,608 | Boost Binary Endian parser not working? | I am studying how to use boost spirit Qi binary endian parser. I write a small test parser program according to here and basics examples, but it doesn't work proper. It gave me the msg:"Error:no match".
Here is my code.
#include "boost/spirit/include/qi.hpp"
#include "boost/spirit/include/phoenix_core.hpp"
... | The big_word parser matches a big-endian word (16 bits), while big_dword will match what you want (big-endian dword, 32 bits). But I don't think it to be a good idea to use a float as the attribute to the binary parser, you might not get what you expect.
|
2,870,214 | 2,870,296 | How do I add controls other than buttons/actions to toolbars in Qt, such as text boxes and combo boxes? | From the screenshot featured on this page http://www.kde.gr.jp/~ichi/qt/designer-manual-3.html it seems like this functionality was available in Qt3. Was it removed in Qt4?
| I don't believe you can do so from within Designer. You can add other widgets programmatically using QToolBar::addWidget().
|
2,870,301 | 2,870,320 | C++ pass enum as parameter | If I have a simple class like this one for a card:
class Card {
public:
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
Card(Suit suit);
};
and I then want to create an instance of a card in another file how do I pass the enum?
#include "Card.h"
using namespace std;
int main () {
... | Use Card::Suit to reference the type when not inside of Card's scope. ...actually, you should be referencing the suits like that too; I'm a bit surprised that Card.CLUBS compiles and I always thought you had to do Card::CLUBS.
|
2,870,377 | 2,870,413 | Is it possible to call an object method this way in C++? | Here's my class definition:
class A {
public:
void do_lengthy_work() {
cout << "working." << endl;
}
};
I have an object of type A, and I want to call do_lengthy_work() on it:
A a;
a.do_lengthy_work();
Is it also possible to call the same method using some variant of the following?
A::do_l... | You can wrap the function with mem_fun_ref:
mem_fun_ref(&A::do_lengthy_work)(a);
This can be very useful for STL algorithms like for_each:
std::vector<A> vec;
std::for_each(vec.begin(), vec.end(), mem_fun_ref(&A::do_lengthy_work));
If you have an A *, you would use mem_fun:
std::vector<A *> vecp;
std:for_each(vecp.be... |
2,870,493 | 2,870,651 | How does Photoshop (Or drawing programs) blit? | I'm getting ready to make a drawing application in Windows. I'm just wondering, do drawing programs have a memory bitmap which they lock, then set each pixel, then blit?
I don't understand how Photoshop can move entire layers without lag or flicker without using hardware acceleration. Also in a program like Expression... | Look at this question:
Reduce flicker with GDI+ and C++
All you can do about DC drawing without GPU is to reduce flickering. Anything else depends on the speed of filling your memory bitmap. And here you can use efficient algorithms, multithreading and whatever you need.
|
2,870,529 | 2,889,601 | g++ How to get warning on ignoring function return value | lint produces some warning like:
foo.c XXX Warning 534: Ignoring return value of function bar()
From the lint manual
534 Ignoring return value of function
'Symbol' (compare with Location) A
function that returns a value is
called just for side effects as, for
example, in a statement by itself or
the left-... | Thanks to WhirlWind and paxdiablo for the answer and comment. Here is my attempt to put the pieces together into a complete (?) answer.
-Wunused-result is the relevant gcc option. And it is turned on by default. Quoting from gcc warning options page:
-Wno-unused-result
Do not warn if a caller of a function marked with... |
2,871,055 | 2,871,067 | User Defined Class as a Template Parameter | I' m re-implementing std::map. I need to make sure that any data type (basic or user defined) key will work with it. I declared the Map class as a template which has two parameters for the key and the value. My question is if I need to use a string as the key type, how can I overload the < and > operators for string ty... | You should factor out the comparison as a type, like the normal std::map does. That is, have a utility class less_compare:
template <typename T>
struct less_compare
{
bool operator()(const T& pLhs, const T& pRhs) const
{
return pLhs < pRhs;
}
};
And then:
template <typename Key, typename Value, typ... |
2,871,353 | 2,875,946 | how can udp data can passed through RS232 in ansi c? | i want to transmit and receive data on RS232 using udp and i want to know about techniques which allow me to transmit and receive data on a faster rate and also no lose of data is there?
thanx in advance. i have tried but need improvements if possible
#include <stdio.h>
#include <dos.h>
#include<string.h>
#include<... | Be aware the many operating systems block direct access to ports. You would have to write a specialized driver to access them.
If you can control the RS232 port pins directly, you may be able to adjust the speed programmatically. In most cases, RS232 is controlled by a UART (or USART). This device also controls th... |
2,871,364 | 2,871,779 | Image rotate OpenCV error | When I use this code to rotate the image, the destination image size remains same and hence the image gets clipped. Please provide me a way/code snippet to resize accordingly (like Matlab does in imrotate) so that image does not get clipped and outlier pixels gets filled with all white instead of black. I don't want im... | Instead of cloning the source image as the dest you are going to have to create an image big enough to take the final rotated image, which will be a square with sides 1.5 times the biggest of the source width or height.
Edit:
The amount you need to enlarge the destination by is 1 + sin(angle of rotation), which has a m... |
2,871,584 | 2,872,044 | Specialization of template method - what's wrong with my code? | What's wrong with this code?
class School {
public:
template<typename T> size_t count() const;
private:
vector<Boy*> boys;
vector<Girl*> girls;
};
template<> size_t School::count<Boy>() const {
return boys.size();
}
My compile says
error: specialization of ‘size_t School::count() [with T = Boy]’
after... | Have you accidentally called count<Boy> in School before it is declared? One way to reproduce your error is
class Boy;
class Girl;
class School {
public:
template<typename T> size_t count() const;
size_t count_boys() const { return count<Boy>(); }
// ^--- instantiation
private:
std::vector<Boy*> boys;... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.