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,831,551 | 6,831,643 | Shared Object (DLL) question | I have a question regarding Shared Objects (or DLLs). I am working on a plugin loader for my game engine. I need one question answered before starting to do that, though.
If I load the data using an external function can I unload my shared object?
Here is a little code snippet:
//The Plugin:
class PythonScriptingPlugin... | No, allocated memory remains, but you will not be able to call any function from that plugin/dll. That makes your object useless.
|
6,831,554 | 6,835,885 | C++0x Variadic Parameter Pack: Syntax | the following code snippet won't compile under gcc4.6.1:
template <typename... TS>
void do_stuff(TS... ts)
{
auto f = [](TS... things) { };
}
It throws an error stating that the pack things was not expanded. The following code does compile however:
template <typename... TS>
void do_stuff(TS... ts)
{
auto f = [](TS... | Two things:
Yes, GCC is wrong to reject [](TS... things) { }. It's possible that it hasn't been implemented yet.
What you declared by [](TS ... things...) { } is equivalent to [](TS... things, ...). In C++ (not in C), you can leave off the comma before the C-style variadic ellipsis. So instead of doing void printf(ch... |
6,831,647 | 6,831,689 | Automatically deallocate array? | I'm looking for a way to automatically deallocate an array of wchar_ts – kind of like an autopointer (I'm not really aquainted with std::auto_ptr, but I think it cannot be used for arrays).
The code I have right now is this:
/* volume is of type wstring,
* hr is of type HRESULT,
* VSS_PWSZ equals wchar_t*
*/
VSS_... | Use std::vector<wchar_t> it is your basic C++ array (or std::wstring if you want to manipulate it like a string).
std::vector<wchar_t> pwszVolume(volume.begin(), volume.end());
pwszVolume.push_back(0);
hr = pDiffMgmt->QueryDiffAreasOnVolume(&pwszVolume[0], &pEnumMgmt);
The question may be. What does QueryDiffAreasOnV... |
6,831,756 | 6,832,158 | Can I run an application compiled in Visual Studio 2005 on Windows 98? | I have built a program in Microsoft Visual Studio 2005 and it works fine.
The problem I am having is the the machine it needs to be used on is running windows 98. As far as I can tell I need to install the re-distributable for vc++. Can I install the re-distributable on windows 98 or is there a way to make it work on ... | Yes, apps compiled with VS 2005 work perfectly fine on Windows 98 and Me. I've run several of them myself, and keep VS 2005 around and installed for precisely this purpose. Version 2005 of the CRT redistributable is supported as far back as Windows 98.
The trick is that you must compile the application for the multi-b... |
6,831,913 | 6,831,953 | Accessing a BST in a singly linked list | Having a singly linked list with its nodes being BST's, what is the code in c++ which needs to be used in order for me to be able to access the elements of the BST?
ifstream isd;
isd.open ( "book1.txt" );
while( !isd.eof ( ) ) {
book b1;
isd >> b1;
b[i] = b1;
i++;
}
isd.close ( );
int j = 0;
for( ... | Why not roll your own algorithm? How are the BSTs ordered in the list? It should be a fairly simple exercise to do this. I'm not sure there is built-in (e.g. STL) support for lists of BSTs. If you clarify your problem, lots of people here would help you write an algorithm to do anything you want.
EDIT:
Here's some pseu... |
6,831,968 | 6,832,122 | What is the difference and benefits of these two lines of code? | I have two lines of code I want explained a bit please. As much as you can tell me. Mainly the benefits of each and what is happening behind the scenes with memory and such.
Here are two structs as an example:
struct Employee
{
std::string firstname, lastname;
char middleInitial;
Date hiringDate; // anoth... | First of all, std::list is a doubly-linked list. So both those statements are creating a linked list of employees.
list<Employee*> group;
This creates a list of pointers to Employee objects. In this case there needs to be some other code to allocate each employee before you can add it to the list. Similarly, each emp... |
6,832,073 | 6,832,236 | What is current best practice around use of strings in cross-platform C and C++ APIs? | I looks like I may need to embark on some cross-platform project and part of it will have to be done in C or C++ (not decided yet hence the question is about them both). I will be dealing mostly with the text-based stuff and strings in general.
That C/C++ will have an API callable from the higher-level platform-depende... | Rules
Use UTF formats to store strings, not "code pages" or whatnot (UTF-16 is probably easier edit: I totally forgot about byte order issues; UTF-8 is probably the way to go).
Use null-terminated strings instead of counted strings, as these are the easiest to access from most languages. But be careful about buffer o... |
6,832,123 | 6,832,524 | Basic string-diff for C++ test case | I have a C++ function which returns a multi-line std::string. In the test-case for this, I compare each line against the known-value - something like:
std::string known = "good\netc";
std::string output = "bad\netc";
std::vector<std::string> knownvec;
pystring::splitlines(known, knownvec); // splits on \n
std::vecto... | The easiest thing to do would be to break out of your loop when strings no longer match:
for(unsigned int i = 0; i < std::min(outvec.size(), knownvec.size()); ++i)
{
bool areEqual = pystring::strip(outvec[i]) == pystring::strip(knownvec[i]);
CHECK_EQUAL(pystring::strip(outvec[i]), pystring::strip(knownvec[i]));... |
6,832,499 | 6,833,364 | QSplitter show a divider or a margin between the two widgets | I have a QSplitter and two widgets on either side, but I want to be able to have a margin, so that there is a clear transition between the two widgets. I looked in QSplitter and QSplitterHandle but dont see any explicit way of doing this.
How do I add a divider between the two widgets?
| Style sheets are a powerful mechanism for changing the appearance of any widget in Qt.
See here for a quick tutorial, and here for a reference guide. Style sheets can be assigned using an editor in the Designer, or passed as a string using setStylesheet(QString). It is certainly easier using the Designer because th... |
6,832,666 | 6,847,817 | LNK2019 when including asio headers, solution generated with cmake | I am trying to port a big project from gcc (Linux) to msvc (windows), using cmake and boost libraries.
The project compile and runs fine for gcc but on msvc it returns the following error:
Dyna.obj : error LNK2019: unresolved external symbol "void __cdecl boost::throw_exception(class std::exception const &)" (?throw_ex... | Try to add the flag "/EHsc" into your TPN_WIN32 variable in cmake.
It seems that MSVC is not throwing exceptions and you need to enable it in your vcproj.
|
6,832,916 | 6,833,027 | What does SAFE[] means here? | So I look at UrlEncode function from here:
std::string UriEncode(const std::string & sSrc)
{
const char DEC2HEX[16 + 1] = "0123456789ABCDEF";
const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
const int SRC_LEN = sSrc.length();
unsigned char * const pStart = new unsigned char[SRC_LEN * 3];
... | SAFE simply appears to be an array marking which characters are valid in a URI. It even has row and column comments to make it easier to see which entry's which.
You'll see that the first valid character is 0x30, or 0. 0x41-0x5A are the capital letters, etc.
This way, SAFE[*pSrc] is simply non-zero ("true") when a cha... |
6,833,143 | 6,833,174 | How to check memory allocation failures with new operator? | Just recently I switched the language of my project to use C++ from C.
With C, I used malloc and after that I check if malloc was successful but with C++, I use 'new' to allocate memory and I would like to know how you would normally check the memory allocation failure.
From my google search, I saw nothrow like the fol... | Well, you call new that throws bad_alloc, so you must catch it:
try
{
scoped_array<char> buf(new char[MAX_BUF]);
...
}
catch(std::bad_alloc&)
{
...
}
or
scoped_array<char> buf(new(nothrow) char[MAX_BUF]);
if(!buf)
{
//allocation failed
}
What I mean by my answer is that smart pointers propagate excep... |
6,833,184 | 6,833,325 | Composition and inheritance design problem | I got these virtual classes from a library that implement an algorithm in the form of abstract classes
class A{
public :
virtual void foo() = 0 ;
};
class B{
public:
void setA(A * a) { m_a = a ;}
virtual void f() = 0;
void g() {m_a->foo();}
protected:
A * m_a ;
};
T... | You've a third solution. Add a function setA() in the dB. Of course, this function will hide B::setA() which is good for you if dB::setA() is implemeted as:
class dB : public B
{
dA *m_dA ; //add this member also!
public :
void f()
{
m_dA->bar(); //fast forward : no cast here... |
6,833,320 | 6,834,346 | Dealing with the huge number of Boost header files | Is there a way to drastically reduce the number of header files needed for Boost?
Ideally, I'm asking the Boost folks to find a way to make their product smaller. But in the meantime, is there a way to include Boost, but not have several thousand header files to deal with?
Is there a C++ mechanism to "bundle" thousand... | Boost offers a tool called BCP. BCP allows you to extract subsets of Boost.
It can also analyze your source tree and extract only the Boost components that your source tree is using.
|
6,833,343 | 6,833,374 | How to handle multiple members of a C++ class simultaneously? | I'm used to Python, and struggling to learn some C++. In Python, when I have a class with a "move" function, I can simply add its members to a list and iterate over the list like this:
for i in list:
i.move(n)
Now, how is the corresponding thing done conveniently in C++?
| You can do the same in C++ by using pointers or reference to your objects.
If your class is MyClass, you could declare:
std::vector<MyClass*> list;
then add your objects to the list:
list.push_back(&objectOfMyClass); //-- for all of your objects
and finally:
std::vector<MyClass*>::iterator itr;
for (itr = list.begin(... |
6,833,392 | 6,834,210 | change function pointer from library A in library B | My situation is the following:
I am writing a toolbox that generates two libraries. The first (A) has all the functions and data-types and can be used in a pure C++ application; the second (B) is an interface to MATLAB.
A pure C++ program would be compiled with
g++ $(FLAGS) C.cpp $(MOREFLAGS) -lA
while a MATLAB progra... | In library B, add a static constructor to set myexit:
// Consider putting this into a namespace
extern void (*myexit)(int);
// anonymous namespace to avoid name collisions
namespace {
class StaticInit {
StaticInit() {
myexit = mex_exit;
}
} static_init_obj;
}
Then link library B to depend on library A:
gcc -o... |
6,833,769 | 7,075,707 | How to extract channel type from Boost::GIL view type? | I cant find the correct way to extract the pixel or channel type from an image view. I'm looking to define pod_t below to be 'unsigned char' in the case of gray8_view_t. There is no simple ViewType::pixel_t. What is the proper definition of this type in function PixelFoo?
template<class ViewType>
void PixelFoo... | ViewType::value_type should be similar to what you expected to be ViewType::pixel_t.
Then, for homogeneous pixel types, the channel_type<T>::type from HomogeneousPixelBasedConcept should lead to the type you are looking for:
template<class ViewType>
void PixelFoo(ViewType v)
{
typedef typename boost::gil::channel_... |
6,834,079 | 6,834,265 | Question on using class member function as template parameter | I'm reading the book by Daoqi Yang "C++ and Object Oriented Numeric Computing for Scientists and Engineers". He has a similar example to what I am showing below, but the exceptions are the class "P" I define and the second to last line (which doesn't work). My question is: why does my compiler generate and error when I... | Template arguments must be compile-time constant expressions or types, and member functions require special handling anyway. Instead of doing this, use boost::function<> as an argument, and boost::bind to create the functor, e.g.
double trapezoidal(double, double, boost::function<double(double)>);
// ...
P f;
trapezo... |
6,834,119 | 6,834,384 | Ways for custom logging in C++ | I am in progress of refactoring a C++ application of mine. Before I used a macro like
LOG("something interesting") // 1
LOG("something ended") // 2
LOG("foo: " << bar) // 3
My idea now was to write a Log class like so:
Log(std::string _init_message):
init_message(_init_message)
{ PrintLogLine(init... | As I've mentioned in the comments, you could use Boost.Format. It also helps with the problem of int-to-string conversions, etc. It might get a bit verbose, though — to avoid calling .str() to call std::string constructor, you could make one that accepts boost::format directly.
Log log(boost::format("foo %1% bar") % 42... |
6,834,156 | 28,114,018 | Descriptive monitor name from D3D display adapter ID | As the question suggests, I'm trying to pull a descriptive monitor name to match with a display adapter name. The code below gives me a device ID like \.\DISPLAY1 which is understandable but not what I'm looking for.
// Get name.
D3DADAPTER_IDENTIFIER9 d3dID;
d3d9.Get().GetAdapterIdentifier(iAdapter, 0, &d3... | UINT iOutput = 0;
IDXGIOutput *pOutput = nullptr;
while (DXGI_ERROR_NOT_FOUND != pAdapter->EnumOutputs(iOutput++, &pOutput))
{
DXGI_OUTPUT_DESC desc;
VERIFY(S_OK == pOutput->GetDesc(&desc));
MONITORINFOEXW monInfoEx;
monInfoEx.cbSize = sizeof(MONITORINFOEXW);
GetMonitorInfoW(desc.Monitor, &monI... |
6,834,343 | 6,834,745 | Ultra Quick Way To Concatenate Byte Values | Given 3 different bytes such as say x = 64, y = 90, z = 240 I am looking to concatenate them into say a string like 6490240. It would be lovely if this worked but it doesn't:
string xx = (string)x + (string)y + (string)z;
I am working in C++, and would settle for a concatenation of the bytes as a 24 bit string using ... | Did you consider instead just packing the color elements into three bytes of an integer?
uint32_t full_color = (x << 16) | (y << 8) | z;
|
6,834,541 | 6,837,683 | Problems with CMenu::ModifyMenu | I'm using CMenu::ModifyMenu in the OnCreate method of my CFrameWnd derived class to change the captions on my menu to match the user language.
I'm using VC++ designer and the menu is declared in a .rc file.
For the MENUITEM elements I use it as follow:
m_wndMenu->ModifyMenu(ID_APP_EXIT, MF_BYCOMMAND, NULL, CString((LPW... | You may have to explicitly disable the menu item and set tool tip text after a call to ModifyMenu. Using ModifyMenu will effectively destroy the previous menu item and create a new one. You are losing any settings and initialization from the resource file or otherwise that you had on the previous item or menu.
See rema... |
6,834,581 | 6,834,608 | C++: Is it better to pass an enum as a value or as a const reference? | There are sort of two related questions here:
A) How is enum implemented? For example, if I have the code:
enum myType
{
TYPE_1,
TYPE_2
};
What is actually happening? I know that you can treat TYPE_1 and TYPE_2 as ints, but are they actually just ints?
B) Based on that information, assuming that the enum pass... | Speed wise it almost certainly doesn't matter - any decent C++ compiler is just going to pass a single int.
The important point is readability - which will make your code more obvious to the reader?
If it's obvious that these enums are really just ints then I would pass them by value, as if they were ints. Using the ... |
6,834,730 | 6,834,778 | about return type from a function | Here I have written some code to get the square of a number from a function, but the return statement is not working as desired by me, it is giving me the same number which I have entered, I want to know the reason behind this, please if any one can explain this to me...
#include<iostream>
#include<conio.h>
using name... | You do not obtain the result.
Your line should be:
a = square(a);
to fetch the result from the function.
The other possibility would be to write in the function
int square(int &i)
{
i = i * i;
return i;
}
The latter will alter the variable you passed to the function which justifies passing a reference.
To mak... |
6,834,741 | 6,834,896 | about win32 standalone:tracking a browser? | I am trying to make a standalone using c++.In my standalone I want it to track user's clicks,I mean which link does he/she clicks.I am trying to count how much time he/she uses a perticular site,like pageaddict(a firefox extension).
So any support..?
| If you want to make a Firefox extension, you should be using JavaScript. In C++, you might make a sniffer, which could tell you from what site the packets you receive are from. But that would require quite a lot of knowledge and of time.
|
6,835,287 | 6,835,526 | Generate random numbers in increments | I need to generate n random numbers between a and b, but any two numbers cannot have a difference of less than c. All variables except n are floats (n is an int).
Solutions are preferred in java, but C/C++ is okay too.
Here is what code I have so far.:
static float getRandomNumberInRange(float min, float max) {
ret... | I think a reasonable approach can be the following:
Total "space" is (b - a)
Remove the minimum required space (n-1)*c to obtain the remaining space
Shot (n-1) random numbers between 0 and 1 and scale them so that the sum is this just computed "optional space". Each of them will be a "slice" of space to be used.
Firs... |
6,835,367 | 6,836,564 | How to invoke a gwt rpc servlet from c or c++ client using libcurl? | I have a google app engine application with a GWT client. Most server functionality is accessible through normal GWT RPC calls as usual. I am writing a data mining application in C++ which needs to communicate with the appengine application. Problem is, there are just too many gwt servlets implemented so a rewrite of s... | If you were using java on the client you could use GWT SyncProxy. Although main usecase of this library was to test remote gwt rpc service, but it can be effectively used for any purpose. As you are developing your client in C++ this might not be an option for you.
If you control the GWT application (that is you can re... |
6,835,614 | 6,836,289 | serializing data to a std::streambuf | I have a Visual Studio 2008 C++ project where I'm trying to serialize data from several classes to a custom std::streambuf implementation.
The data classes with their serialization:
struct Header { /*...*/ };
inline std::ostream& operator<<( std::ostream& os, const Header& h )
{
/* serialize the members of Heade... | You need to call flush() on the iostream (or call pubsync() on your streambuf).
Traditionally you'd do this in the destructor of your streambuf (in the same way that filebuf's destructor calls close()), in which case you just need to destroy it.
Also it's conventional to provide a class inheriting from iostream that ow... |
6,835,679 | 6,837,344 | C++ compilation error: "cast from 'WCHAR*' to 'WORD' loses precision" | MyGUI library.
There's a line in its sources:
mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
mHandle is size_t
LoadCursor returns HCURSOR.
Error:
D:\Dev\MyGUI_3.2.0_RC1\Common\Input\Win32\ResourceW32Pointer.cpp:48: error: cast
from 'WCHAR*' to 'WORD' loses precision
Here's the full source:
www.past... | The problem is actually at MAKEINTRESOURCE(IDC_ARROW) and isn't related to the type of mHandle. [Aside: I agree that mHandle should not be size_t but I think that is not your current problem.]
Since IDC_ARROW is defined to be MAKEINTRESOURCE(32512), the code should in fact read
LoadCursor(NULL, IDC_ARROW)
rather than... |
6,835,711 | 6,835,896 | C++ templates that use external functions | does C++ allow using external functions in template specification implementations? What I wanna do is make a wrapper to BLAS/LAPACK (the CBLAS doesn't cut it for me, I need a couple of functions that are not in there and are in the external BLAS), somewhat like this
extern "C" {
void saxpy_(int* n, const float* con... | The problem I see is that you declare three things:
template<class T>
void ax_plus_y(const T a, const Matrix<T, Dynamic, Dynamic>& x,
Matrix<T, Dynamic, Dynamic>& y);
template<>
void ax_plus_y<float>(const float a, const Matrix<float, Dynamic, 1>& x,
Matrix<float, Dynamic, 1>& y);
template<>
void ax_plus_y<... |
6,835,960 | 6,836,025 | CUDA, using memset(or fill or ...) to set an array of float to max val possible | Edit: Thanks for the previous answers. but in fact I want to do it in CUDA, and apparently there is no function Fill for CUDA. I have to fill the matrix once for each thread so I want to make sure I'm using the fastest way possible. Is this for loop my best choice?
I want to set the matrix of float to the maximum valu... | Use std::numeric_limits<float>::max() and std::fill as:
#include <limits> //for std::numeric_limits<>
#include <algorithm> //for std::fill
std::fill(matrix, matrix + N*N, std::numeric_limits<float>::max());
Or, std::fill_n as (looks better):
std::fill_n(matrix, N*N, std::numeric_limits<float>::max());
See thes... |
6,836,077 | 6,836,379 | Actions order in Bison | I'm trying to use Bison to generate a parser, in C++. The grammar is fine, but I'm having some quick trouble with the actions. Here's a simple sample:
statements
: statement
| statements statement;
As far as I know, this is a pretty normal thing to do. The question I have is which is derived first. For example, if I h... | It associates to the left, i.e.
(((statement) statement) statement) statement
You can tell that this is the only possibility because this can be reduced to statements statement, which is one of your productions. The other option
statement (statement (statement (statement))))
would have to be reduced to statement sta... |
6,836,161 | 6,836,351 | making use of otherwise wasted padding space | The following struct X has 3 bytes of payload and 1 byte of padding:
struct X
{
short a;
char b;
};
memory layout: aab.
The following struct Y has 4 bytes of payload and 2 byte of padding:
struct Y
{
X x;
char c;
};
memory layout: aab.c.
Is there any way to keep X nested inside of Y and have sizeof(... | For hopefully obvious reasons the size of both X and Y can't be four (if it were possible, X would have multiple definitions, the normal padded one and one where the padding is used by the char of Y). So the only way Y could be 4 is if X were changed to eliminate its padding. This can be done by compiler specific pragm... |
6,836,401 | 6,836,459 | Can a compiler inline a virtual function if I use a pointer in a clear situation? | I've already read Are inline virtual functions really a non-sense?. But I still have some doubts and found no answer there.
They say that if situation isn't ambiguous, compiler should inline the virtual function.
However:
This can happen only when the compiler has an actual object rather than a pointer or reference to... | It doesn't matter whether B has any derived classes. In that situation b points to a B object so the compiler can inline the call.
And surely any decent modern compiler can and will do that in your situation. If you don't use pointers it becomes a whole lot easier. It's not really an "optimization" then. The fact that... |
6,836,437 | 6,857,980 | How can I make boost::function not be so lenient? | typedef boost::function<void (int,bool)> MyCallback;
void RegisterCallback(MyCallback callback);
class A {
public:
void GoodCallback(int intArg,bool boolArg) {
printf("calling GoodCallback (%d,%s)\n",intArg,boolArg?"true":"false");
}
void BadCallback(int intArg) {
printf("calling BadCallba... | I'm a bit late with this answer but since the problem is the binding you could do this step later with the help of a templated version for your callback registration function and another one for regular function pointers:
template<typename C>
void RegisterCallback(void (C::* func)(int, bool), C* inst)
{
MyCallback ca... |
6,836,476 | 6,836,550 | QDomDocument won't insert QDomElement | I'm doing something with XML and now I'm confused.
This code works perfectly:
QDomElement new_item = doc.createElement(name);
new_item.setAttribute("type", value.typeName());
new_item.setAttribute("value", value.toString());
doc.elementsByTagName(section).at(0).appendChild(new_item);
But if I would c... | Basically DomElement creation needs information that QDomDocument has. From Qt 4.7 documentation
Since elements, text nodes, comments, processing instructions, etc., cannot exist outside the context of a document, the document class also contains the factory functions needed to create these objects. The node objects c... |
6,836,525 | 6,836,555 | How should I interpret this struct in c++? | class new_hashtable {
public:
/* This is the datatype stored in the hashtable slots. */
struct KEY_VALUE {
KEY k;
VALUE v;
KEY_VALUE(const KEY &k_,const VALUE &v_) :k(k_), v(v_) {}
KEY_VALUE() {}
};
}
In above codes, is KEY_VALUE(const....) :k(k_), v(v_){} a copy constructor... | The difference between class and struct in C++ is that the default for struct is public. Other than that they're exactly the same.
So you have an inner class KEY_VALUE with all the members and methods public, with 2 constructors: the default, and one that receives 2 parameters. It is not a copy constructor. k(k_), v(v_... |
6,836,617 | 6,837,600 | What is the proper lifetime management for a CCmdTarget used as an event sink? | I'm following the Microsoft sample code given for "How to create a sink interface in a MFC-based COM client" in order to create an event sink in C++ (VC6). The event source is a .NET assembly that exposes it's functionality via COM interop.
The thing that is giving me fits is the very last note of the sample:
Because... | The default implementation of OnFinalRelease is to delete the object. It would probably be best to subclass CCmdTarget to gain the message map and event hooks and make your own class which can stay in scope for all processing needed then only delete once at the end. You could add a callback or notification message to s... |
6,836,704 | 6,837,429 | How to send a double array from C# to C++ | In my C# code, I have the following array:
var prices = new[] {1.1, 1.2, 1.3, 4, 5,};
I need to pass it as a parameter to my managed C++ module.
var discountedPrices = MyManagedCpp.GetDiscountedPrices(prices) ;
How should the signature of GetDiscountedPrices look like? In the most trivial case, when discounted prices... | Your managed function declaration would look something like this in the header file:
namespace SomeNamespace {
public ref class ManagedClass {
public:
array<double>^ GetDiscountedPrices(array<double>^ prices);
};
}
Here's an example implementation of the above function that simply subtracts a h... |
6,836,729 | 6,836,839 | building static library (.lib) VS 2010 Pro | I have a newbie question about building a static library in VS 2010 Pro.
When you choose to build a static library (.lib) instead of an application, the Linker option in project properties disappears. Normally I go to Linker->Input->Additional Dependencies to add the needed .lib files for a project.
I've built the libr... | A Static library is linked with your executable. Any dependencies that your static library has (external libraries it requires) must also be specified in your executable.
So, if libA requires libB, then an application that links with libA will also have to link with libB.
|
6,836,899 | 6,884,454 | Gstreamer - Convert command line gst-launch to C code | I have been making a few experiments with GStreamer by using the gst-launch utility. However, ultimately, the aim is to implement this same functionality on my own application using GStreamer libraries.
The problem is that it's ultimately difficult (at least for someone that is not used to the GStreamer API) to "port" ... | I found the solution. There's a function built in on GStreamer that parses gst-launch arguments and returns a pipeline. The function is called gst_parse_launch and is documented here: http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/gstreamer-GstParse.html
I haven't tested it but it's possible th... |
6,836,984 | 6,836,997 | Redefinition of constructor with inheritance | Why in the underlying example keeps the compiler complaining about a redefinition for the B constructor. If i remove the {} it complains they need to be there. How is this done correctly?
I want to implement the constructor of B in the CPP file and not inline.
#include <vector>
#include <sstream>
#include <iostream>
u... | You have already defined B constructor in the class definition:
class B : public A
{
public:
B() : A() {};
~B();
};
So, when you define it again outside of the class definition:
B::B()
{
cout << "B construct!";
you get the error; if the correct constructor is the last one, replace your class definition ... |
6,837,020 | 6,837,041 | Replacing std::list object given an iterator | Given an iterator into a std::list, how do you replace the object at the position that the iterator references? Currently all I can think of is calling insert with the new object and iterator (to insert the new object before the element referenced by the iterator), and then calling erase to remove the object to be repl... | What's wrong with:
(*it) = obj;
where obj is the replacement value?
|
6,837,036 | 6,837,085 | Why do some header files require libraries to be linked, in Visual Studio? | I'm building a socket program in Visual Studio 2003 .NET
I #include <winsock2.h> header file but also noticed that I had to link in the WS2_32.lib to fix the unresolved winsock function errors.
In other homework projects, I just added a header file and used it's functions - without adding the corresponding library.
Ho... | The socket functions are actually implemented in ws2_32.dll. In order for the linker to be able to find them, you need to add the ws2_32.lib import library to your project. Note that the import library does not contain the actual code for the functions, but only information about where to find the actual functions (in ... |
6,837,288 | 6,837,343 | QNetworkAccessManager problem | I'm trying to open a web page using QNetworkAccessManager - and for some pages it works fine - while for others it does not. I tried setting a real browser user-agent, however it still doesn't work for example, http://www.erepublik.com. Here's the code:
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
... | It looks like you're getting the data correctly, it's just that that particular URL just forwards you to a different one. Try http://www.erepublik.com/en (with the /en) instead.
|
6,837,444 | 6,837,455 | Decltype for return of a function | I am making a templated class that is a wrapper around any iterator. I am making the operator* this way:
template <typename T>
class MyIterator {
public:
//...
decltype(*T()) operator*() {
//...
}
}
I give decltype a invocation to operator* of class T, and it even works, but if T doesnt have default co... | This is what std::declval is for:
decltype(*std::declval<T>()) operator*() { /* ... */ }
If your implementation does not provide std::declval (Visual C++ 2010 does not include it), you can easily write it yourself:
template <typename T>
typename std::add_rvalue_reference<T>::type declval(); // no definition required
... |
6,837,506 | 6,839,202 | Ubuntu: gethostbyaddr Returns NULL with HOST_NOT_FOUND Error | My machine is Ubuntu Server 10.10.
I have the following code snippet:
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
struct in_addr addr;
struct hostent *he;
/* printf ("sizeof struct in_addr... | For reverse DNS lookups, the behavior is controlled by /etc/host.conf. You need to specify hosts in there. You need to add this line in your /etc/host.conf:
order hosts,bind
See http://tldp.org/LDP/nag/node82.html.
|
6,837,699 | 6,838,005 | Are mutex lock functions sufficient without volatile? | A coworker and I write software for a variety of platforms running on x86, x64, Itanium, PowerPC, and other 10 year old server CPUs.
We just had a discussion about whether mutex functions such as pthread_mutex_lock() ... pthread_mutex_unlock() are sufficient by themselves, or whether the protected variable needs to be ... |
If the above code is correct, how is it invulnerable to caching
issues?
Until C++0x, it is not. And it is not specified in C. So, it really depends on the compiler. In general, if the compiler does not guarantee that it will respect ordering constraints on memory accesses for functions or operations that involve mu... |
6,837,990 | 6,838,067 | Algorithm to loop over an array from the middle outwards? | I'm working on a divide-and-conquer algorithm (in fact, one that does curve fitting to a number of input points). For the 'divide' part, I need to calculate an error term for each point, and if the error exceeds a given threshold, I wish to split the curve at that point and process the left and right sections of the in... | This would be more readable imho
for (int q=0; q < steps; q++) {
int index = i + ( q% 2 == 0 ? q/2 : -(q/2+1)); //index lookup here
}
|
6,837,996 | 6,838,133 | Position of reused variable for loop | What are the pros/cons of using Method 1 vs Method 2?
Method 1:
for ( std::vector<MyObject*>::iterator it = my_objects.begin(); it != my_objects.end(); ++it )
{
Vector2 temp_position = (*it)->GetPosition();
// do something...
}
Method 2:
Vector2 temp_position; // I do NOT need scope for this object outside of ... | If we ignore any optimizations the compiler performs, there is a concrete difference between the functions called by each version.
In Method 1, since you're creating the vector inside the loop, its constructor will be invoked once (specifically, its copy constructor), and its destructor will be invoked once, for each i... |
6,838,068 | 6,838,219 | Defining a top-level no-op in C++? | Is the following legal according to the C++ standard? (If the answer differs from standard to standard, I would like to know that, too.)
#define VERY_OLD_COMPILER 1
#ifdef VERY_OLD_COMPILER
#define USING_NAMESPACE_STD enum { }
#else
#define USING_NAMESPACE_STD using namespace std
#endif
USING_NAMESPACE_STD;
int mai... | Looking at the latest public C++0x draft, it seems semicolons at top-level are allowed and ignored.
The grammar treats a translation-unit as a sequence of declarations, and amongst the various kinds of declarations there is an empty-declaration that is just a simple semicolon.
Pragmatic solution: considering that your... |
6,838,119 | 7,194,710 | Hadoop pipes (wordcount) example failing (with hadoop 0.21.0) | I was trying out the simplistic word count example for hadoop pipes. Unfortunately it is erroring out with java.lang.NullPointerException and /usr/lib64/libstdc++.so.6: no version information available errors when I try to run it as:
$ bin/hadoop pipes -Dhadoop.pipes.java.recordreader=true \
-Dhadoo... | So I gave it another shot and started from scratch. This time round I had better success. Here is the code and the config files I used.
Also, here's the command I used to run the job:
hadoop pipes -conf path/to/dp_hpt_conf.xml
-input /path/to/input
-output /path/to/output
The input files in... |
6,838,207 | 6,838,474 | How to pass void arguments in a class/function templates | Hey i'm trying to make a Button template class, which is constructed with the the button would recieve when pressed (such as mouse position), and a pointer to the function that should be called.
However buttons often return void and take no arguments (Buttons that you press and something happens: they don't take any ... | You can specify a template specification of type void, for example, you could use the following variations of the templated class, button:
template <typename rtnVal, typename Val1, typename Val2>
class Button {
private:
rtnVal(*Function)( Val1 val1, Val2 val2 );
public:
Button() : Function( nullptr ) {}
v... |
6,838,292 | 6,839,067 | how to get rid of "In class initializer for static data member ... is a C++0x extension" warning in Xcode 4 | I can get rid of the warnings in the build log by adding -std=c++0x to "other c++ flags", but they still show up in the side pane. I'm guessing that the other flags are not being passed to clang or whatever is responsible for parsing code for the gui...
Any ideas?
Update:
The warnings have mostly disappeared, but I'm ... | Use a pragma instead of a command line switch, as described in the answer to "Is there a way to suppress warnings in Xcode?"
|
6,838,363 | 6,838,386 | Win32 equivalent of .net SendKeys | I am designing a system that reads a gesture from Kinect and make some actions. I am trying to include the system to be able to send HotKey to an application. My system is writing in c++ but the UI is in C++.net. I have been able to use SendKeys from the UI part and it does work.
Is there a Win32 equivalent so I can u... | In WIN32, SendKeys is called SendInput:
http://msdn.microsoft.com/en-us/library/ms646310(v=vs.85).aspx
It can also simulate mouse movements, etc.
|
6,838,535 | 6,838,707 | Once an array-of-T has decayed into a pointer-to-T, can it ever be made into an array-of-T again? | So let us say I have an array:
int a[3] = { 1, 2, 3 };
Now if I were to check the type of 'a', on my machine I get:
cout<<typeid(a).name(); // prints 'A3_i'
Now if I take the address of 'a', then dereference that address, the type does not change (which I really like, because in my mind 'taking the address' and 'dere... | I'm not sure if this is quite what you're looking for, but you can use typecasting to get back an object with the same type as the original array. The idea is to use the little-known types pointer-to-array and reference-to-array to recover the information. For example:
char arr[137];
cout << sizeof(arr) << endl; // P... |
6,838,567 | 6,839,280 | How to create a new JS object using NPAPI? | I'm writing an NPAPI plugin. In C++ code, I can't create a JS object using NPAPI. I tried this method:
Foo.js
function Foo(p)
{
this.a=p;
}
Foo.prototype.get=function()
{
return this.a;
}
C++ code (I want to create the Foo object. Just link what we can do in JS . var s=new Foo(2);)
int newJSObject(const NP... | NPN_Construct doesn't seem to work on browser objects, so there is no direct way to do what you want. What you could do, however, is make a javascript function to create the object for you and return it; you could even use NPN_Evaluate to inject it automatically into the page.
something like this:
function __create_ob... |
6,838,590 | 6,853,010 | QT QStackedLayout problem | I would like to ask about QStackedLayout.
Now, I have a several widgets added to the QStackedLayout
And I want to do sth like that:
When user switch to Page X, refresh Page X.
How can I do that?
I have a custom code that I want to run when it refreshes
Thank You very much
| Based on your comment to mine, it seems like you are looking for a signal that is generated when the current page changes so that you can update the underlying data for the screen. In that case, you would want to hook a slot up to void QStackedWidget::currentChanged(int index)
|
6,839,180 | 6,839,214 | Linking error in simple C program using a C++ header | I am following an intro tutorial http://www.linuxinsight.com/files/alp/alp-ch01-getting-started.pdf.
I have created the source files main.c, reciprocal.cpp and reciprocal.hpp. I have been able to successfully compile these files. The problem comes when I go to link them and I receive the following error message:
main.o... | When you mix C and C++ code together, you can run into trouble because the two languages have different linkages. That is, if you were to crack open the object files for a compiled C and C++ file, you would find that the names inside of those object files were different.
In particular, C++ compilers tend to use a tech... |
6,839,425 | 6,839,544 | What will be the critical section code for a shared queue accessed by two threads? | Suppose we have a shared queue (implemented using an array), which two threads can access, one for reading data from it, and other for writing data to it. Now, I have a problem of synchronization. I'm implementing this using Win32 API's (EnterCriticalSection etc.).
But my curiosity is what will be the critical section ... | For a single producer/consumer circular queue implementation, locks are actually not required. Simply set a condition where the producer cannot write into the queue if the queue is full and the consumer cannot read from the queue if it is empty. Also the producer will always write to a tail pointer that is pointing t... |
6,839,486 | 6,839,527 | How do I create a class that can initialize C++ data types? | The title basically says it all. I mainly want to do this so that I can create an object (say, a custom string object) that can initialize the parameters of other functions in other APIs. Here's an example of me trying to get a custom integer class to work:
#include <iostream>
using namespace std;
class test
{
public:... | What you are trying to do needs an conversion operator
operator int()
{
return this->member;
}
For the class you are trying to write(containing only integer members), You do not need to overload the = operator.
= operator is one of the member functions that is generated by the compiler by default for every cla... |
6,839,508 | 6,839,581 | Test if stdin has input for C++ (windows and/or linux) | I basically want to test if stdin has input (like if you echo and pipe it). I have found solutions that work, but they are ugly, and I like my solutions to be clean.
On linux I use this:
bool StdinOpen() {
FILE* handle = popen("test -p /dev/stdin", "r");
return pclose(handle) == 0;
}
I know that I should add more ... | Here's a solution for POSIX (Linux): I'm not sure what's the equivalent of poll() on Windows. On Unix, The file descriptor with number 0 is the standard input.
#include <stdio.h>
#include <sys/poll.h>
int main(void)
{
struct pollfd fds;
int ret;
fds.fd = 0; /* this is STDIN */
fds.event... |
6,839,562 | 6,839,903 | LinkedList/Stack/Queue - Help with Dequeuing | I had to write a linked list, then turn it into a dynamic Stack, then turn that into a dynamic Queue. Well everything seems to work except the "dequeuing", right as the programs about to finish, it gives me an error: "An unhandled win32 exception occured in LinkedList_Stack_BNS11.exe [4972].".
I'm only assuming it's t... | Last nodes's next element should be set to NULL in a linked list. So,
void NumberList::enqueue(int num)
{
// ...
if(isEmpty())
{
head = newNode;
head->next = NULL;
rear = head;
}
else
{
rear->next = newNode;
rear = rear->next;
rear->next = NULL; ... |
6,839,828 | 6,839,872 | was not declared in this scope | I am new in C++ and working on a project with QT. I created a header file called imageconvert.h which is as follow:
class ImageConvert
{
private:
IplImage *imgHeader;
uchar* newdata;
public:
ImageConvert();
~ImageConvert();
IplImage* QImage2IplImage(QImage *qimg);
QImage* IplImage2QImage(IplImage *iplImg);
};
also ... | The functions you've defined are member functions of the ImageConvert class. You need an instance of that class to be able to call them.
Something like:
ImageConvert ic;
ic.QImage2IplImage(your_QImage_object);
If you don't need state to do the conversion, you should make those helper functions static. Then you can cal... |
6,839,849 | 6,839,895 | Replacing multiple chars at the same time | So in my code I have a series of chars which I want to replace with random data. Since rand can replace ints, I figured I could save some time by replacing four chars at once instead of one at a time. So basically instead of this:
unsigned char TXT[] = { data1,data2,data3,data4,data4,data5....
for (i = 34; i < flen... | That won't work. The compiler will take the result from rand() % big_number and chop off the extra data to fit it in an unsigned char.
Speed-wise, your initial approach was fine. The optimization you contemplated is valid, but most likely unneeded. It probably wouldn't make a noticeable difference.
What you wanted to d... |
6,840,380 | 6,852,162 | Boost.Python: Calling virtual functions from C++ | I'm not looking for help on exposing virtual functions to Python, I would like to know how I can call the said virtual functions from the C++ side. Consider this...
// ====================
// C++ code
// --------------------
struct Base
{
virtual void func() {
cout << "Hello from C++!";
}
};
BOOST_PYT... | Your approach will not work in such a simple way; you have to add wrapper to your python class, from which python class will be subsequently derived. here, under 1. I explained briefly how it works. So, to call python-override of a c++ virtual method, use get_override and call the returned object with ().
For some code... |
6,840,576 | 6,840,659 | How to export a C++ class from a dll? | I have a class which has two overloaded functions. How do I export it from a dll and also how to use it by other C++ classes? My class looks like this:
#define DECLDIREXP __declspec(dllexport)
#define DECLDIRIMP __declspec(dllimport)
class DECLDIREXP xyz
{
public:
void printing();
void prin... | A common approach is to have a single macro (let's call it EXPORT) which either expands to dllimport or dllexport depending on whether some sort of "building the DLL right now" define is set, like this:
#ifdef MAKEDLL
# define EXPORT __declspec(dllexport)
#else
# define EXPORT __declspec(dllimport)
#endif
class EXPO... |
6,840,759 | 6,841,001 | C++ stream second insertion operator | Is it possible to define a second insertion operator to have two modes of outputting a class? Say e.g. one that outputs all members and one that just outputs some basic unique identifier that is grep-able in a log? If so, is there an operator that is usually chosen? I would guess as analogy to << one might use <<< if t... | If you want to output only the id, then the best idea is probably to provide a method to get the id in a type that's streamable (e.g. std::string id() const;). That's much more intuitive to other people working on the code than some strange operator use.
Your suggestion of <<< (it's not possible to create new operator... |
6,841,039 | 6,841,055 | error when declaring an enum to a variable | I have the following syntax:
enum home
{
no,
yes,
}homew;
home homes;
std::string s;
s="no";
homes=s; //is not working. Why?
Were am I wrong?
| You are confusing strings with enumerated values.
An enum variable is simply an integer that you can use a literal for at compile time, nothing more than that.
It makes the code more understandable and self-documenting rather than merely using a number literal.
|
6,841,070 | 6,842,320 | Are there any problems using SysAllocString with literals? | I have the following code
void Test()
{
BSTR aBstr = ::SysAllocString(L"blah");
PrintBSTR(aBstr);
::SysFreeString(aBstr);
}
void PrintBSTR(BSTR _aBstr)
{
PrintWstring(_aBstr);
}
void PrintWstring(std::wstring _aWstring)
{
std::wcout << _aWstring << std::endl
}
It works well for ... | There is nothing wrong with passing a literal to SysAllocString.
|
6,841,130 | 6,970,046 | Ordering of using namespace std; and includes? | I recently saw this code being used in a source file in a C++ project:
using namespace std;
#include <iostream>
Ignoring all issues of whether it's a good idea to have using namespace std at all, is the above code even legal? There is no code in the file before these two lines.
I would have thought that this wouldn't... | A perhaps interesting data point. When I compile the following:
using namespace std;
using namespace no_such_namespace;
with g++ 4.5.2, I get:
c.cpp:2:17: error: ‘no_such_namespace’ is not a namespace-name
c.cpp:2:34: error: expected namespace-name before ‘;’ token
To be clear, those two lines are the entire source ... |
6,841,156 | 6,841,173 | Project contains more lib than dll files | I try to understand a visual studio project, which I had downloaded. There are two folders a bin and a lib folder. The number of lib files in the lib folder is greater than the number of dlls in the bin folder.
I thought every dll file could have a lib file (object file library). So the number of lib files in a project... | Of course there are lib's that don't have a corresponding dll. If you set your project type to "static library" your output will be a lib file which can link only statically to another lib, dll, or exe.
When you create a dll, a lib file is automatically created which takes responsibility of conveniently wrapping LoadLi... |
6,841,223 | 6,841,613 | What is a cold/dead field and what is a peeling optimization? | In the paper Loop Recognition in C++/Java/Go/Scala (pdf) we find the following quote in the section C++ Tunings:
Structure Peeling. The structure UnionFindNode has 3 cold fields:
type_, loop_, and header_. Since nodes are allocated in an
array, this is a good candidate for peeling optimization. The three
fields ... | Structure peeling is an optimization where you divide a structure into several ones to improve data locality (in order to reduce cache misses). You separate "hot" data (frequently accessed) from "cold" data (seldomly accessed) into two structures to improve the efficiency of the cache, by maximizing the probability of ... |
6,841,263 | 6,842,041 | How to bring window on top of the process created through CreateProcess | I am launching a process from my application using CreateProcess API and I want to bring the window of the new process to top. Is there a way to do it? Do we have any flag or something like that with CreateProcess?
| You can try to use the STARTUPINFO structure which is passed in with CreateProcess and set SW_SHOW. I'm not sure this will help bring the focus to the top though. If that doesn't work then try the following.
First off, do not use FindWindow(), it is unnecessarily unreliable since it only works via the window name and c... |
6,841,297 | 6,841,392 | Which TLS library should I use, portability is an issue | We are looking to add TLS (transport layer security) support to our software, and are looking for the best choice of a library.
The software is written in c++, and is ported to Linux and Solaris (and Windows, but who gives a crap?).
Being able to adapt the code to both Linux and Solaris is a major concern, and thus a l... | We've used OpenSSL on Windows, AIX, Solaris, HPUX and Linux for quite a long time and never found any incompatibilities. As far as I remember, no platform specific code was needed to make it work everywhere.
|
6,841,376 | 6,841,402 | C++ help with headers | I've got a C++ project and I'm really confused with the header organization in that project. I have header files for gui declaration and source files. The organization is:
//file1.h
#pragma once
//file1.cpp
#include "file1.h"
//file2.h
#pragma once
//file2.cpp
#include "file2.h"
And when I'm trying to inlcude file1... | error C1083: Cannot open include file
Means most probably either your file is not present at the path or you have not added the path of the file to your include path.
Have a look at Fatal Error C1083.
|
6,841,405 | 6,841,429 | What the pointer size in 64 bits computer in C++? | My computer is change from 32 bits to 64 bits, and my operating system is 64 bits Windows 7. I think the pointer in 64 bits operating system should be 64 bits -- 8 bytes. However, when I use sizeof(void*) in C++ to get the size of a point, the result is 4.
Why 4??
| Your executable is still being compiled as a 32-bit binary. Try compiling it as a 64-bit project.
The operating system makes no difference to the internal size of a pointer if the processor is emulating the program within a 32-bit environment...
In VS2010, head over to the configuration manager, make a new entry under ... |
6,841,410 | 6,844,454 | How can I make vim align the ternary ?: operator nicely? | I like to write code using the ternary ?: operator like this:
std::string result = input.empty() ? createNewItem()
: processInput( input );
How can I configure vim so that when pressing Return after having typed createNewItem() indents the next line so that the cursor is in the same ... | Inspired by a roughly similiar question I exercised my vimscript-fu and created a little script to do this job:
if (!exists("*CppIndentDepth"))
function CppIndentDepth()
let lineno = v:lnum
let lastQuestionMark = match(getline(lineno-1), "?[^?]*")
if lastQuestionMark != -1
return... |
6,841,474 | 6,841,860 | Size of different program elements in C++ | When does memory get allocated to a data type, class and function? At the time of declaration or at the time of definition?
Also is there a way to know the sizeof function?
|
Size of different program elements in C++
When does memory get allocated to a data type, class and function? At the time of declaration or at the time of definition?
A data type is just an abstract notion understood by the compiler. When a variable of that type is needed, memory must be allocated. The:
amount of mem... |
6,841,632 | 6,841,675 | static member definition with template base class | There is a base class:
template<class T_CLASS>
class TBase
{
protected:
static CSomeClass m_objSomeClass;
public:
inline void Set(CSomeClass f_objSomeClass) { m_objSomeClass = f_objSomeClass; }
};
And there are some sub classes which all shall have their own static member m_objSomeClass. I try to do this ... | template<>
CSomeClass TBase<CSub1>::m_objSomeClass;
template<>
CSomeClass TBase<CSub2>::m_objSomeClass;
is the one of the correct ways, if you want to explicitly have static member defined for a solid class like CSub1, CSub2. Demo.
Edit: The conventional way is to define as:
template<class T_CLASS>
CSomeClass TBase<T_... |
6,841,680 | 6,842,369 | boost::lambda expression fails to compile because of instantiation of abstract template arg. Any explanation and/or work arounds? | I'm in the process of learning boost::lambda and I've managed to create a situation that I can't resolve with what I know so far.
Apparently in the bowels of boost::lambda, the following example causes the attempted instantiation of abstract class AbstractFoo, and prevents the lambda expression from compiling. The prob... | Riffing off of JVo's answer, the following works around the issue:
func3 = (bll::protect(bll::bind( &Foo::it,
bll::bind( &Foo::Ptr::get,
bll::_1 ))) (bll::_1) == 2);
where
bll::bind( &Foo::Ptr::get, bll::_1)
Pulls out the pointer s... |
6,841,696 | 6,841,742 | C++ (Hashmap style) Data Structure Ideal For This Scenario? | People have asked similar questions about the efficiency of various data structures but none I have read are totally applicable to my scenario so I wondered if people had suggestions for one that was tailored to satisfy the following criteria efficiently:
Each element will have a unique key. There will be no possibili... | What you need definitely sounds like a hash set, C++ has this as either std::tr1::unordered_set or in Boost.Unordered.
P.S. Note, however, that TR1 is not yet standard, and you'll probably need to get Boost for the implementation.
|
6,842,080 | 6,842,291 | C++ Novice regarding Bitset operations with strings | I'm currently learning about bitset, and in one paragraph it says this about their interactions with strings:
"The numbering conventions of strings and bitsets are inversely related: the rightmost character in the string--the one with the highest subscript--is used to initialize the low order bit in the bitset--the bit... | They are both right.
Traditionally the bits in a machine word are numbered from right to left, so the lowest bit (bit 0) is to the right, just like it is in the string.
The bitset looks like this
...1100 value
...3210 bit numbers
and the string that looks the same
"1100"
will have string[0] == '1' and string[3] =... |
6,842,173 | 6,842,232 | Private vs. Static functions in C++ | Is there any advantage to using private (probably also static) functions in a class for utility functions used in my class that do not need access to an instance's data over using global static functions in my .cpp file that implements the class?
The first sounds cleaner to me, but the second really makes more sense as... | I would not put private static functions to the header file if they are not needed. They would just pollute the header file and add more work.
But private static functions may be needed when you have a template method/function in a class and want to use that helper function in it.
Another reason for using private stat... |
6,842,176 | 6,842,231 | What is the easiest way to copy a nested vector | In my code I have a struct named bead. and I have a vector which is defined as
vector< vector< vector <vector <bead*> > > > boxes
Sometimes, I need to make some changes to the boxes and I might need to revert those changes.
What happen if I do the following:
vector< vector <vector <vector <bead*> > > > nBoxes;
nBoxes ... | I think that you meant
boxes = nBoxes;
in the end.
operator = of vector copies the contents of the vector. That is, in your case it copies the pointers to bead. The bead objects themselves aren't deep-copied.
|
6,842,197 | 6,853,835 | Compiling a basic OpenCV + Cuda program on linux | I've worked with opencv on linux in the past, but not with cuda. I've struggled with the following compilation error for months. And after trying many solutions i gave up and worked with windows. However, i really want to work on linux. This is the command i'm using to compile the threshold example given on the opencv... | In order to help you I had to download and install CUDA 4.0 (with driver 4.0.21) and then download and compiled OpenCV 2.3 for my Macbook Pro, on Mac OS X 10.6.8.
The sample code from OpenCV_GPU was successfully compiled on my machine through:
g++ threshold.cpp -o threshold `pkg-config --cflags --libs opencv` -lopencv_... |
6,842,566 | 8,167,587 | How to build a grid from scattered points in OpenCV? | What I need is to construct a intensity grid(image) in OpenCV from which I can extract some contours. I have already resolved this issue with a complete data grid, but my problem is that I will only have some scattered points available on the map and I will have to build this grid myself.
From what I've read from diffe... | So, you could use the delaunay triangulation to give you the interpolating points to fill in the empty image points in between. This is basically what happens when you use delaunay to render a sparse height field. It may help to read up on barycentric coordinates (as those are the coordinates you would use to perform... |
6,842,609 | 7,047,821 | How to display a bitmap in android through OpenGLES in C++? | I have a class in my Java layer which implement Renderer. Inside this class I have a bitmap which I want to pass to JNI layer. JNI layer would be responsible for displaying bitmap by using OpenGL. Can anyone tell me how this can be done?
Update:
I know there is an open gl method glTexImage2D which can be used to displa... | You cannot pass a java Bitmap class pointer directly and expect it to work with glTexImage2D.
glTexImage2D expects raw pixel data to be passed in the pointer. ( in fact your JNI native C function declaration looks wrong, last parameter should be of type jobject, not void * . use "javah" to generate correct JNI functio... |
6,842,638 | 6,842,676 | Why typecasting operator doesn't work with inherited class? | I have two classes:
struct B {};
struct D {
operator B& ();
};
When I do;
b = d; // B b; ... D d;
Result is as per expectation where D::operator B&() is invoked (Demo).
If the D is changed to,
struct D : B {
operator B& ();
};
then D::operator B&() is not invoked (Demo). Is B::B(const B&) is finding a better can... | If D derives from B, there is an implicit automatic conversion from D to B. This has higher precedence than a user-defined conversion operator.
|
6,842,690 | 6,842,709 | Will _forceinline virtual function from base class be __forceinlined in derived class without explicitly stating it? | Suppose we have:
class Base
{
__forceinline virtual int A() {return 1;}
}
class Derived: public Base
{
int A()
{
return 2;
}
}
Function A in derived class is virtual without explicitly stating it. Will function A in derived class be also __forceinlined without explicitly stating it?
| First, functions called virtually can't be inlined - the compiler needs to get to vtable pointer first to know which function to call. Not all functions marked virtual are called virtually - those can be inlined.
Then, __forceinline won't propagate to the derived class implementation - it's a non-standard compiler-spec... |
6,842,799 | 6,842,821 | Enum variable default value? | The question is simple:
#include <iostream>
enum SomeEnum {
EValue1 = 1,
EValue2 = 4
};
int main() {
SomeEnum enummy;
std::cout << (int)enummy;
}
What will be the output?
Note: This is not an interview, this is code inherited by me from previous developers. Streaming operator here is just for ex... | The program has Undefined Behavior. The value of enummy is indeterminate. Conceptually there is no difference between your code and the following code:
int main() {
int i; //indeterminate value
std::cout << i; //undefined behavior
};
If you had defined your variable at namespace scope, it would be value... |
6,842,880 | 6,853,130 | Why reimplement strlen as loop+subtraction? | Inspired by this question about the following code from SQLite3:
static int strlen30(const char *z){
const char *z2 = z;
while( *z2 ){ z2++; }
return 0x3fffffff & (int)(z2 - z);
}
that is accompanied by a commit message saying this function helps with int overflows.
I'm particularly interested in this pa... |
Why reimplement strlen as loop+subtraction?
I suspect the real answer is that the programmer felt like it, but another potential justification/rationalisation is that the loop is inline (independent of whether strlen30 itself is), whereas on many systems strlen is an out-of-line function call (e.g. Linux/GCC). If th... |
6,843,130 | 6,848,748 | CUDA Thrust performance | I have a 640*480 vector which contains a set of numbers, I wish to find the min and max number of each row of the vector.
for(int i = 0; i < R; i++)
{
Begin = m_valBuffer.begin() + (i*C);
End = Begin+C;
rMinmax= minmax_element(Begin, End);
}
However this is extremely slow, is there a... | This example shows how to compute the sum of each row using
the reduce_by_key algorithm. You can easily adapt that example to compute
the min or max of each row. To compute the min and max of each row
simultaneously you'll need to use this strategy. Specifically,
you'll need to use a transform_iterator on the in... |
6,843,167 | 6,843,267 | "glibc detected - free(): invalid pointer - Program received signal SIGABRT, Aborted" | Here's a minimal code that puzzles me :
#include <list>
class A;
class A {
private:
std::list<A*> a_list;
// int a_list;
public:
A() : a_list() {}
};
int main() {
A* a_tab = new A[1];
// A* a_tab = new A();
delete a_tab;
return 0;
}
At execution, I got :
*** glibc detected *** ./main: free()... | You use wrong deletion. You have allocated an array of one element using operator new[], but you delete as a single object using operator delete. Use delete[] a_tab; instead.
|
6,843,202 | 6,843,555 | What if redefine an inline function? | I've spent days in a weird problem and finally discover that there were two inline function of the same signature in the project and they caused the problem. To simplify the situation here is an example: two cpp file:
a.cpp
#include <iostream>
void b();
inline void echo()
{
std::cout << 0 << std::endl;
}
int mai... | The compiler is not required to diagnose this ODR violation, and it is not trivial. The inline keyword means that different translation units might have the same symbol, so it is marked weak by the compiler. The basic use case is a function defined inline in a header: all translation units that include the header will ... |
6,843,247 | 6,843,433 | Problems with QObject multiple inheritance and policy/traits design in C++ | I'm building a fairly large plugin-driven app in my spare time, and have come across a show stopping design flaw. My app uses policy/traits based design, but because I use Qt it is done just through MI (rather than templates and MI). Some of these classes are pure virtual and some perform rather critical functions un... | You can't inherit from multiples clasess that inherit QObject.
Try using composition instead of inheritance. See composition over inheritance.
You can also try using Q3Signal class. Although it belongs to old QT3 according to QT doc :
The Q3Signal class can be used to send signals for classes that don't
inherit QOb... |
6,843,466 | 6,843,643 | C# Correct managed code from C++ | I have to use this external functions "GetOpenedFiles" (more info to: http://www.codeproject.com/KB/shell/OpenedFileFinder.aspx) into my C# application.
I don't know as I can write a wrapper of this function:
void GetOpenedFiles(LPCWSTR lpPath, OF_TYPE Filter, OF_CALLBACK CallBackProc, UINT_PTR pUserContext);
ORIGINA... | public struct OF_INFO_t
{
Int32 dwPID;
String lpFile;
IntPtr hFile;
}
public delegate void CallbackFunctionDef(OF_INFO_t info, UIntPtr context);
[DllImport("OpenFileFinder.dll", EntryPoint = "GetOpenedFiles")]
static extern void GetOpenedFiles(string lpPath, OF_TYPE filter, CallbackFunctionDef CallBackProc, ... |
6,843,531 | 6,843,607 | Modify log class to accept variables in string - C++ | I am trying to modify my log class to accept variables in my string. For example, if I wanted to output that there are 7 players in an area.
Here is my write to log function:
void Log::writeSuccess(string text,...)
{
// Write the sucessfull operation to the logfile
logfile << "<---> " << text << endl;
}
And he... | In case you can't or won't use boost:
void Log::writeSuccess(const char* const fmt, ...) {
va_list ap;
va_start(ap, fmt);
char buff[1024];
vsnprintf(buff, sizeof(buff), fmt, ap);
logfile << buff;
}
Note: it assumes that the written length is limited.
Update: with gcc it's possible to do this in a t... |
6,843,572 | 6,843,631 | SDL/SDL_image.h: No such file or directory | I'm trying to follow Lazy Foo's tutorials. But when I try to run one of his examples I get this compiler error:
error: SDL/SDL_image.h: No such file or directory
The compiler/linker is set up correctly, I'm using Code::Blocks on Windows XP.
However, the problem is simply that there are no SDL_image.h. I've checked in... | You need to install SDL_image separately. It's not shipped with SDL.
|
6,843,602 | 6,843,907 | How do I extract any information from boost::errinfo_nested_exception? | I have recently started using boost::exception. Now I would like to use boost::errinfo_nested_exception to print information about the cause of the error. The problem is I can't figure out how to get information from the cause. I have tried the following with no success:
#include <iostream>
#include <boost/exception/al... | You need to rethrow the nested exception and examine that:
const boost::exception_ptr* c =
boost::get_error_info<boost::errinfo_nested_exception>(e);
if(c) try {
boost::rethrow_exception(*c);
} catch(boost::exception const& e) { // or a type derived from it
const std::string* file = boost::get_error_info<b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.