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,711,041 | 6,711,081 | C++: Passing pointer variable to function | I have a class Node:
class Node {
public:
int item;
Node * nextLink;
};
Outside a function I declare a Node pointer:
Node * newNode;
Then, I pass this pointer to a function foo:
void foo(Node * node) {
node = new Node();
node->item = 1;
Node * anotherNode = new Node();
anotherNode->item = 2;
no... | You need to pass a reference. You are modifying a copy of the pointer
try
void foo(Node*& node)
|
6,711,293 | 6,713,677 | C++ Is using auto_ptr references as out variables idiomatic? | Suppose I want to write factory method that is supposed to allocate heterogeneous objects on the heap and return them to the caller. I am thinking of designing the API like this:
bool MakeEm(auto_ptr<Foo>& outFoo, auto_ptr<Bar>& outBar) {
...
if (...) {
return false;
}
outFoo.reset(new Foo(...));
outBar.r... | You don't have to make up your own struct to return two values - you can use std::pair. In that case there isn't much syntactic overhead in returning the two values. This solution does have the problem that ".first" and ".second" aren't very descriptive names, but if the types involved and the name of the function make... |
6,711,422 | 6,711,713 | AngelScript, how to load a script file? | I know how I can bind C++ functions to AngelScript, but in my C++ code, how do I load an .as script file? How can I say in my C++ "Execute myscript.as now!" ?
In the AngelScript API I don't find any function like "LoadScript" or "ExecuteScript".
Or do I have to define a path somewhere from where AngelScript loads all s... | Just found it out (in a small side sentence in the docs):
AngelScript doesn't provide a build in file loading. That's why there is no API function. So the manual loading is indeed the only way.
|
6,711,514 | 6,711,667 | Trouble declaring object of included type | If I declare an object in my header file, I get a compilation error. I can, however, construct it in my application's setup() method, simply by calling Analyzer A(44100., "a", 200);.
If I construct it this way, how do I keep a pointer to it? Won't the object be inaccessible once the constructor call has gone out of sco... | you can initialize constructor type of A
in constructor of testApp as
testApp:testApp():A(44100., "a", 200){
//testApp constructor.
}
|
6,711,959 | 6,721,345 | Opengl Superbible Configuring an IDE | Someone knows how to configure Kdevelop and cmakelist.txt to work with GLTools/GLU/ and other opengl libraries?
Opengl superbible brings a tutorial to configure VS and a MAC IDE, but, i can't find any tutorial to configure Kdevelop to work fine with superbible's libs...
| As you noted, the configuration is in CMakeLists.txt moreso than KDevelop, which is told what to do by the CMake manager. That said, google turned up a few points of interest regarding opengl config with CMake. These look like they have the main points of interest:
http://www.cmake.org/pipermail/cmake/2009-February/027... |
6,712,453 | 6,712,501 | C++ compilation issue | I am seeing some C++ errors I don't understand (I am java centric coder):
WarningNotification_if.cpp: In function 'void fireStatusBarMessage(char*, int)':
WarningNotification_if.cpp:62:14: error: expected type-specifier
WarningNotification_if.cpp:62:14: error: cannot convert 'int*' to 'WarningEventData*' in initializa... |
WarningEventData *theEventData =
new WarningEventData::WarningEventData();
This is quite odd. A new expression is supposed to name a type, not a constructor. Is WarningEventData inside a like-named namespace? And if so, why isn't it WarningEventData::WarningEventData* theEventData ?
|
6,712,867 | 6,715,143 | Multiplying Transform and Matrix types in Eigen | To me this should just work, so the fact it does not, almost certainly means I am the one in the wrong. Even though in principle a Transform< double, 3, Affine > is the same as a Matrix< double, 4, 4 >, they cannot be used together sensibly:
Affine3d rotMat( AngleAxisd( 45.0, ( Vector3d() << 0.0, 1.0, 0.0 ).finished()... | Just write:
m = m * rotMat.matrix();
I don't know if it is an oversight that Eigen doesn't define this multiplication implicitly or if it might interfere with other use cases of the library.
|
6,713,193 | 6,713,366 | g++ complains that "virtual const ... cannot be overloaded" | I am attempting to use a third party SDK (Crystal Space) and am encountering some problems.
The code (not mine) looks like this:
#define CS_EVENTHANDLER_PHASE_LOGIC(x)
CS_EVENTHANDLER_NAMES(x)
CS_EVENTHANDLER_DEFAULT_INSTANCE_CONSTRAINTS
virtual const csHandlerI... | Why can't I overload virtual const functions?
Ofcourse you can, provided you overload them and not create two methods with the same prototype.
It is syntactically valid to overload virtual const functions.
All you methods, GenericPrec(), InstaceSucc() and InstancePrec() have the very same prototype. To overload a funct... |
6,713,420 | 62,596,471 | C++ convert integer to string at compile time | I want to do something like this:
template<int N>
char* foo() {
// return a compile-time string containing N, equivalent to doing
// ostringstream ostr;
// ostr << N;
// return ostr.str().c_str();
}
It seems like the boost MPL library might allow this but I couldn't really figure out how to use it to accompli... | This is now possible in C++17 and beyond without any external dependencies, with the conversion done entirely at compile-time. I've packaged the code in a short header file, check out constexpr-to-string on GitHub. The code supports different bases and character widths as well.
Examples of use:
const char *number = to_... |
6,713,483 | 6,713,657 | Is it possible to reference individual tabs of a QTabWidget by tab number? | Very quick question here. I was wondering if it is possible for me to reference individual tabs from a QTabWidget by number. This will save me a lot of time, as I am generating an unknown number of tabs during run-time. I could not find anything in the QT documentation, but I feel like this is a very basic feature that... | If you want the tab with a certain index, use widget():
QWidget* tab = tabWidget->widget( index );
|
6,713,484 | 6,713,515 | smart pointers and arrays | How do smart pointers handle arrays? For example,
void function(void)
{
std::unique_ptr<int> my_array(new int[5]);
}
When my_array goes out of scope and gets destructed, does the entire integer array get re-claimed? Is only the first element of the array reclaimed? Or is there something else going on (such as unde... | It will call delete[] and hence the entire array will be reclaimed but I believe you need to indicate that you are using an array form of unique_ptrby:
std::unique_ptr<int[]> my_array(new int[5]);
This is called as Partial Specialization of the unique_ptr.
|
6,713,637 | 6,713,698 | Heap vs Stack allocation | I am alittle bit confused on topic of allocating objects on heap vs allocating on stack, and when and how delete() should be called.
For example I have class Vector. I would like to make an array of these.
I could either do this
Vector** v = new Vector*[100]; //create an array of 100 pointers to 100 Vector objects
Thi... | I'll start from the beginning...
Vector** v = new Vector*[100];
Allocates an array of 100 pointers to objects of type Vector on the heap
It returns one pointer- v - the you can use to keep track of this array of pointers.
Delete this array of 100 points with:
delete[] v;
(Use the delete operator- delete for a single ... |
6,713,747 | 6,713,813 | Activate windows under mouse through mouse hook | Basically i make mousestruct in the hook
MOUSEHOOKSTRUCT* str;
Then make it from lparam,
LRESULT CALLBACK MouseProc( int nCode, WPARAM wParam, LPARAM lParam )
{
str = (MOUSEHOOKSTRUCT *) lParam;
...
Then I catch mousemovements
case WM_MOUSEMOVE:
wParm = AU3_WM_MOUSEMOVE;
fromp = WindowFromPoint(str->pt)... | You can use the blocking SendMessage instead depending on surrounding implementation. PostMessage will send to the window message queue but may not have the priority you expect as it returns without waiting for the processing of the message.
Also check out SetCapture and ReleaseCapture to change which window is capturi... |
6,713,842 | 6,715,180 | Virtual Function Compared to Pointer Casting | The current version of some code I'm using utilises a slightly odd way of acheiving something which I think could be acheived with polymorphism. More concretely we currently use something like
for(int i=0; i<CObjList.size(); ++i)
{
CObj* W = CObjList[i];
if( W->type == someTypeA )
{
// do some things wh... | I'm going to answer specifically on the performance angle, because I work in a perf-critical environment and a while ago I happened to run measurements on a similar case to work out the fastest solution.
If you are on an x86, PPC, or ARM processor, you want virtual functions in this situation. The performance cost of c... |
6,713,844 | 6,715,209 | If TECGetTextEncodingFromInternetName() requires a Pascal-style string, why is CopyCStringToPascal() discontinued in OSX 10.5? | It is my responsibility to build an old version of an open-source library for OSX 10.5. (The library is Xerces 2.8.)
The library fails to build out-of-the-box on OSX 10.5 due to (among other things) use of the discontinued OSX function CopyCStringToPascal(). The relevant code snippet is:
Str255 pasEncodingName;
...
C... | There are three upgrade paths, all through CFString.
The first, already suggested by Grady Player, is to use CFString to convert the encoding name to a Pascal string. You may be able to start with the encoding name in a CFString (using the CFSTR macro); if not, you can create a CFString from the C string, and a Pascal ... |
6,713,897 | 6,713,938 | How to reach the member data of a class from inside one of its member class/struct? | Hey I have an abstract class named Partition which is a functor, and its a member of my ConcavePolygon class. The Partition Functor depends on a lot of the ConcavePolygon's data such as TPPLPoints and SFMLPoints.
I've found that even though i've defined the class inside the one it
depends on, i can't easily reach Con... | In C++, nested classes are really just a way of scoping namespaces (and providing protection: public/protected/private) for class names. They do not create any special relationship between the two classes besides the name: OuterClass::NestedClass.
So you need to treat nested classes like they are separate classes. If y... |
6,713,956 | 6,714,503 | What can cause cout << variable << "\t"; to print blankspace instead of a value, when the output exceeds terminal width? | I have a series of three loops that each cout a row of \t delimited values
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
struct the_struct {
float a_float;
the_struct() :a_float(0){}
};
class the_class {public: the_struct a_struct;};
int main ()
{
vector <the_class> v_obj... | As discussed in comments under the question, this seems to be a bug/quirk in the Mac terminal (I'm thinking bug, but I don't know if the Posix spec says something weird about the allowable interaction between tabs and the right-hand-side of the terminal).
If the 11th value is single-digit (which 0 is), then at least on... |
6,714,046 | 7,053,461 | c++ linux double destruction of static variable. linking symbols overlap | Environment: linux x64, compiler gcc 4.x
Project has following structure:
static library "slib"
-- inside this library, there is static object "sobj"
dynamic library "dlib"
-- links statically "slib"
executable "exe":
-- links "slib" statically
-- links "dlib" dynamically
at end of the program, "sobj" is destructed ... | OK, I have found solution:
http://gcc.gnu.org/wiki/Visibility
For example if change
static CTest test;
to
__attribute__ ((visibility ("hidden"))) static CTest test;
problem will gone.
Linux:
CTest() this=-1646158468
CTest() this=6296196
use
use
~CTest() this=6296196, is Alive
~CTest() this=-1646158468, is Alive
nm o... |
6,714,281 | 6,714,315 | Call C++ from C# Array MarshalAs Problems? | So I have a function inside of a C++ library:
double MyFunc(double** data, int length)
{
//data elements are accessed like this
(*data)[i] = 5.0;
}
In C# I access this function in this way:
//import
[DllImport(@"MYDLL.dll")]
public static extern double MyFunc(ref double[] data, int length);
//usage
MyFunc(ref ... | You can simply pass a double[] directly.
|
6,714,307 | 6,720,162 | Gtkmm compiling error | OS: Windows 7
Compiler: MinGW
IDE: Code::Blocks
I just installed Gtkmm on my computer in the folder C:/gtkmm/ and set up an example program. When I compiled it, it gave the error "gtkmm.h: No such file or directory"
I tried setting the PATH variable to C:/gtkmm/include and C:/gtkmm/gtkmm-2.4, but neither worked. Then I... | pkg-config is a helper function for adding cflags and lib paths to the compiler line.
What you will need to do is add the libraries and cflags path to the compiler line. I am not 100% sure how to do that in code::blocks., though
In ubuntu 11.04, you need all these to compile even a simple gtkmm program:
Libs (pkg-confi... |
6,714,580 | 6,714,627 | How to determine whether connection to socket was closed | I am writting the socket with C++ under Linux. I have a question. How I can find out whether the client closed the connection.
Especially in the situation in which the server accepted the client and started to wait for some data from client. But the client does not send anything and just closes the connection to server... | If the client closed the connection, n = read(newsocketfd, buffer, 255) will return 0.
|
6,714,628 | 6,714,641 | Error: no match for 'operator&&' | I'm getting the following error
error: no match for 'operator&&' in 'board[0][0] && board[0][1]'
My code is the following:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
string board[3][3];
board[0][0] = "[ ]";
board[0][1] ... | You need to change something like:
board[0][0] && board[0][1] && board[0][2] == "[X]"
To:
board[0][0] == "[X]" && board[0][1] == "[X]" && board[0][2] == "[X]"
So that the inputs on each side of the && are boolean values
|
6,714,650 | 6,720,914 | Qt Quick how to create a button that will loock native to each OS app is used in? | What I need is simple: qml way to create a button that would loock native on each platform app is compiled to? (mainly I wonder about linux, windows and Mac OS X)
| There's nothing built-in.
But there is a project called Qt Quick Components, mainly for mobile platforms. There is also some development for desktop platforms, see http://labs.qt.nokia.com/2011/03/10/qml-components-for-desktop/
|
6,714,995 | 6,715,039 | pointers and char arrays | I think that this is a fairly simple question... I've tried finding the specifics and can't. The code:
#include <iostream>
using namespace std;
int main() {
char * veggie_burger = "delicious";
cout<<endl<<veggie_burger<<endl;
for (int count = 0; count < 9; count++){
cout<<veggie_burger[count]
... | veggie_burger[n] is exactly the same as *(veggie_burger+n), so &veggie_burger[n] means veggie_burger + n, or a pointer to the nth character. It has type char*, because it is the address of a character.
&veggie_burger, on the other hand, is the address of the pointer. It has type char **.
|
6,715,125 | 6,715,242 | overloading a virtual function that is used in a base classes non-virtual function | Hey so i'm trying to build the following member Functors of class ConcavePolygon, and i'm getting Linker External symbol error for some reason:
unresolved external symbol "public: virtual void __thiscall
sf::ConcavePolygon::Partition::RunAlgorithm(class TPPLPoly &,class
std::list > &)"
My goal was to simply make ... | It looks like in your descendants of Partition, you are not properly forwarding the call to the Partition constructor. Instead, you are constructing a temporary Partition object, and then immediately throwing it away.
struct Base {
Base() { cout << "Base Default" << endl; }
Base(int i) { cout << "Base Int: " <... |
6,715,131 | 6,715,159 | Undefined refrence to static variable Foo::a? | I am getting this error and I have no idea what it means:
$ mingw32-g++ Test.cpp -o Test.exe
C:\Documents and Settings\BDL\ccksiYhI.o:Test.cpp:(.text+0x11): undefined reference to 'Foo::a'
collect2: ld returned 1 exit status
This is my code.
Test.cpp
#include <vector>
#include "Test.h"
int main() {
Foo::a.clear()... | You still need to define the member variable, even if it's static. Change your Test.cpp to this:
#include <vector>
#include "Test.h"
std::vector<int> Foo::a; // <-- definition
int
main() {
Foo::a.clear();
return 0;
}
|
6,715,172 | 6,715,205 | C++: vector memory corruption when modifiying an object member from outside the copy constructor but not when modifying from within | #include <iostream>
#include <vector>
#include <cassert>
class a_class
{
public:
int num_IN;
a_class():num_IN(0){}
a_class(a_class const & origin){/*Initialise();*/} //if not called here, error occurs
void Initialise(){num_IN =5;}
};
int main ()
{
std::vector <a_class> the_vector;
for(i... | std::vector may reallocate the buffer it uses if it's size outgrows it, in which case it has to copy the old elements over to the new buffer. If you don't have a proper copy constructor that copies num_IN over, the old value is lost.
Fix this by providing a proper copy constructor:
a_class(a_class const & origin) : num... |
6,715,226 | 6,716,419 | How to read NULL value in ADO | I have a question related with NULL values I am connecting to SQL Server 2008 via ADO following the code:
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <ole2.h>
#include <oleauto.h>
#ifdef _MSC_VER
#import "c:\Archivos de programa\Archivos comunes\System\ado\msado15.dll" rename ("EOF","adoEOF"... | I'm sure there is some way to check for null values against the Recordset object but I don't know how that should be done in c++. But I do know how to fix this in the query instead.
Change your query to:
SELECT coalesce(att0, -1) as att0 FROM [dbo].[mytable]
|
6,715,247 | 6,715,274 | what is the difference between "some" == "some\0" and strcmp("some","some\0") in c++? | what is the difference between "some" == "some\0" and strcmp("some","some\0") in c++?
Why if("some" == "some\0") returns false and if(!strcmp("some","some\0")) returns true ?
| See the following diagram. It shows two strings in memory, their content is in the box, beside the box you'll see the address of each one.
When you're doing if("some" == "some\0") you are comparing the addresses. It is translated into if (0xdeadbeef == 0x0badcafe) which is obviously false.
When you use strcmp, you com... |
6,715,260 | 6,715,272 | Why increment on data pointed by Pointer crashing? |
Possible Duplicate:
C/C++ Char Pointer Crash
char *p = "atl";
char c;
c = ++*p; //crashing here
Why it is crashing?
I know the memory is not created for pointer increment should have be done on data.
| p points to const data which is the string literal "atl"; that means, *p cannot be changed. But you're trying to change it by writing ++*p. That is why its crashing at runtime.
In fact, most compilers would give warning when you write char *p ="atl". You should write:
const char *p ="atl";
If you write so, then the co... |
6,715,351 | 6,716,994 | Boost::thread how to get a pointer to the thread where my function is called? | With boost::thread how do I get a pointer to the boost::thread which is currently executing my function, from within that function?
The following does not compile for me:
boost::thread *currentThread = boost::this_thread;
| You have to be careful because boost::thread is a movable type. Consider the following:
boost::thread
make_thread()
{
boost::thread thread([](boost::thread* p)
{
// here p points to the thread object we started from
}, &thread);
return thread;
}
// ...
boost::thread t = make_thread();
// if the... |
6,715,370 | 6,715,462 | What is the lifetime of the class data member which const reference to a rvalue? | Generally this discussion is up to the local function variable only:
void foo (const int &i)
{
// use i till foo() ends
}
foo(3);
But, does this rule applies to the class member also ?
struct A {
const int &a;
A () : a(3) {} // version 1
A (const int &i) : a(i) {} // version 2
};
Now A used as,
{
return ()... | The C++03 standard (Section "12.2/5 Temporary objects") answers your question aptly:
The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a refe... |
6,715,454 | 6,715,535 | What is the default path for OSX system include files when building a C++ application? | I am building a C++ application at the command line (using make with an open-source library (Xerces 2.8)). One of the files includes an OSX system file,
#include <TextUtils.h>
When I type make -n to determine the command used to compile the given file, there is no include path for the system framework files provided.... | Executing the following command
# echo "" | gcc -xc - -v -E
will output the buildin configuration of gcc among which are the default includes.
|
6,715,490 | 6,715,561 | Conditionally copy map keys to a vector | I have a map container. I want to copy all its keys with user specified first letters to a vector. How to do that in an efficient way? Thank you!
std::map(std:string, size_t) myMap;
myMap.insert(std:make_pair("Ace", 11);
myMap.insert(std:make_pair("Ape", 12);
myMap.insert(std:make_pair("Age", 13);
myMap.insert(std:make... | Declarations left out for brevity:
begin = myMap.lower_bound("Bo");
end = std::find_if(begin, myMap.end(), first_does_not_begin_with("Bo"));
for (i=begin; i!=end; ++i)
myVec.push_back(i->first);
You can implement the first_does_not_begin_with functor class, right? It's operator should have this signature:
bool op... |
6,715,545 | 6,715,574 | Storing a 32 bit float in a file portability concerns | If I store a float in a file via this code
fwrite((void*)(&v), sizeof(v), 1, f); // v is a float.
how often will a program reading the file with this code cause a runtime error because float is 8 bytes instead of 4?
float v;
fread((void*)(&v), sizeof(v), 1, f);
return v;
Can I always read 4 bytes and cast that to an ... | I would be less worried about the size of the float and more worried about the endianness of it. I'd say the vast majority of C++ implementation use IEEE 754 which would mean float is always going to be 32 bits and double 64 bits.
You may wish to just serialize a text representation of the value, or else take particula... |
6,715,590 | 6,715,646 | Giant switch statement for constructors | I have a container which holds a bunch of pointers to a base class, and a function which takes some input and returns a class which is a subclass of the base class. Which subclass it returns depends on the input.
Right now, I have a giant switch statement like this:
class Base { ... }
class A : public Base { ... }
cla... | What you are looking for is an Factory Method pattern.
The important thing here is to remove the need for the Base class to have any knowledge of the derived class implementations. It is a bad design for a Base class to have knowledge about Derived classes.
Factory Method pattern addresses the above problem as the c... |
6,715,826 | 6,715,839 | Open source c++ debugger for windows | Does anybody know an open source C++ debugger for Windows?
It doesn't have to be good, it just has to work. (I'd prefer one written in C++)
thanks :)
| GDB but ofcourse!
And be assured it works as well as any debugger does :)
|
6,716,091 | 6,716,109 | Assigning a reference by dereferencing a NULL pointer | int& fun()
{
int * temp = NULL;
return *temp;
}
In the above method, I am trying to do the dereferencing of a NULL pointer. When I call this function it does not give exception. I found when return type is by reference it does not give exception if it is by value then it does. Even when dereferencing of NULL ... | Dereferencing a null pointer is Undefined Behavior.
An Undefined Behavior means anything can happen, So it is not possible to define a behavior for this.
Admittedly, I am going to add this C++ standard quote for the nth time, but seems it needs to be.
Regarding Undefined Behavior,
C++ Standard section 1.3.24 states:
... |
6,716,183 | 6,716,229 | DLLimport unable to load dll | I am using an unmanaged dll in cpp which I call from from my C# web project. It works fine on my localhost but simply does not work on my shared hosting, winhost. It happens when I try to use one of the function in the dll.
The error message I am getting is:
"Unable to load DLL 'dllTest.dll': The application has fail... | The problem is that your C++ DLL requires the CRT libraries to be installed in order to work. The bolded part of the error message is what gives you the hint:
Unable to load DLL 'dllTest.dll': The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log ... |
6,716,308 | 6,717,753 | How to get Authentication Type (like WindowsIdentity.AuthenticationType property) | In C#, the following code would give authentication type of current user:
System.Security.Principal.WindowsIdentity.GetCurrent().AuthenticationType;
The returned value would be either NTLM or Kerberos.
How do I get same information using Windows API. I tried locating information through GetTokenInformation, but none ... | You use LsaGetLogonSessionData(). The returned SECURITY_LOGON_SESSION_DATA.AuthenticationPackage contains the authentication package name. Get the LUID you need from GetTokenInformation
|
6,716,408 | 6,716,430 | How to avoid linking a certain object file everywhere | So I got a class that specifies a constant with a special meaning for each type.
I use something like this
template<class Type>
class SpecialKeyProvider
{
static const Type SPECIAL_KEY;
}
with one or more specializations for Types that will also be used but are not numeric.
So I initialize the static member outside ... | Put the class with static const in an unnamed namespace in your header file:
namespace
{
template<class Type>
class SpecialKeyProvider
{
static const Type SPECIAL_KEY;
};
template<>
const string SpecialKeyProvider<string>::SPECIAL_KEY = "__SPECIAL"; //<--- const
template<>
const double SpecialKeyP... |
6,716,625 | 6,716,644 | Wrapping C++ templates so they can be used in C#, Java etc | I have a C++ library (.lib) which relies heavily on templates. I'm creating a C++ wrapper to this library to expose its functions externally in a .dll. These exposed functions will in turn be used by both Java and C# libraries via JNA/JNI and PInvoke respectively.
I understand from this SO question that it is not pos... | When people say "it is not possible to export templates", that does actually mean "it is not possible to export templates.
Since it is not possible to export templates, you have no way to "retain as much as possible of their flexibility".
You can export individual functions, but not templates. You can always generate a... |
6,716,847 | 6,721,503 | Converting recursive permutation generator to iterative | I'm having some difficulty converting this recursive algorithm for displaying all the permutations of a given set of integers into an iterative one.
void getPermutationsR(int v[], int n, int i)
{
if (i == n)
{
//Display contents of v
}
else
{
for (int j=i; j<n; j++)
{
... | The challenge you are encountering is that you've got function calls and loop constructs intermingled. It is hard to disentangle those.
First let's start by replacing all control of flow operations with recursion.
// You'll want to start with getPermutionsR(v, n, 0, 0)
void getPermutationsR(int v[], int n, int i, int ... |
6,716,983 | 6,716,992 | How to find number of elements present in an array? | I have an array variable, say for an example:-
int a[10];
And suppose i have added 4 elements say 1,2,3,4 starting from a[0] till a[3].
Now how do i find that how much element is present in the array variable a whose max size is 10?
My way to obtain the number of elements present in the array assuming that user will g... | You have to build in that convention yourself.
For instance, you could initialize the whole array to some magic constant that signals "not in use", or you could track the length through a separate variable.
Either way, the framework will not help you at all, there is no way. For all intents and purposes, the array has ... |
6,717,023 | 6,717,044 | Window Procedure Not Being Called By Message Handler | I am writing a Windows Api wrapper and I have run into a problem. I am abstracting the Window Procedure (WndProc) and wrote a static MsgHandler which would call the WndProc of my WinHandler class. Here is the code:
LRESULT CALLBACK WinHandle::MsgHandler(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
WinHandle* w... | Call SetWindowLong when you receive WM_CREATE, not WM_NCCREATE. I don't think lpCreateParams is valid in WM_NCCREATE. That is:
if (msg == WM_CREATE)
{
::SetWindowLong(hwnd,GWL_USERDATA,
long((LPCREATESTRUCT(lParam))->lpCreateParams));
}
|
6,717,028 | 6,740,137 | Using boost IOStreams with std::ostream_iterator | I tried to use an array-device based stream and wantet to pass the stream to std::ostream_iterator or std::istream_iterator, but unfortunately, I get a compilation error with gcc 4.3.5.
Boost::IOStreams documentation states that the io::stream is either derived from std::basic_istream or std::basic_ostream or both (std... | You're not supplying enough template arguments for std::istream_iterator -- the second argument is the underlying character type of the stream, which defaults to char, but the underlying character type of your stream is byte (unsigned char).
Changing
std::istream_iterator<byte> in(ios_);
to
std::istream_iterator<byte,... |
6,717,045 | 6,717,265 | Should I use global variables? | I have been reading about global variables and how bad they are but I am stuck in one place due to that. I am going to be very specific about if I should use global variables in this scenario.
I am working on a game engine. And my engine consists of lots of managers. Managers do certain tasks - they store resources, lo... | I won't say you should never use globals, but:
Never use singletons. Here is why. They're horrible, and they're much worse than plain old globals.
"Manager" classes are bad. What do they "manage"? How do they "manage" it? "Manager" classes need to be broken up into something that you can describe. Once you've figured ... |
6,717,082 | 6,717,093 | C++ compile error on Visual Studio 10 | I'm getting the following error while compiling this simple program using Visual Studio:
error LNK2019: unresolved external symbol "public: void __thiscall CoList<int>::enqueue(int)" (?enqueue@?$CoList@H@@QAEXH@Z) referenced in function _main
error LNK2019: unresolved external symbol "public: virtual __thiscall CoList... | The definitions of function templates(including member functions of class templates) must be in the .h file so that they are present in every cpp file in which they are used. That's how templates work. You cant put the definitions into a cpp file. Technically, there is an export keyword which enables this but since alm... |
6,717,163 | 6,717,180 | How to access private data members outside the class without making "friend"s? | I have a class A as mentioned below:-
class A{
int iData;
};
I neither want to create member function nor inherit the above class A nor change the specifier of iData.
My doubts:-
How to access iData of an object say obj1 which is an instance of class A?
How to change or manipulate the iData of an object obj1?
N... | You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.
(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)
|
6,717,189 | 6,719,080 | How do I build wxWidget for portable CodeBlocks? | I'm new at this, so please bear with me.
Every tutorial tells me to go to the build\msw directory and start running the makefile command:
mingw32-make -f makefile.gcc BUILD=release SHARED=1 MONOLITHIC=1 UNICODE=1
The problem is that mingw32-make.exe is not in that directory. Do I just copy everything from my CodeBloc... |
Do I just copy everything from my CodeBlocks\MinGW\bin folder to that
directory?
No! The right way to make the compiler tool-chain accessible from any location is to set the system's environment PATH variable.
Usually, you don't have to set this yourself; it's likely MinGW did this for you during installation. You... |
6,717,246 | 6,717,267 | No array allocated using new can have an initializer? | In the book I am reading at the moment (C++ Complete Reference from Herbert Schildt), it says that no array allocated using new can have an initializer.
Can't I initialize a dynamically allocated array using new? If not whats the reason for it?
| That's not quite true (you should almost certainly get yourself an alternative reference), you are allowed an empty initializer (()) which will value-initialize the array but yes, you can't initialize array elements individually when using array new. (See ISO/IEC 14882:2003 5.3.4 [expr.new] / 15)
E.g.
int* p = new int[... |
6,717,622 | 6,717,634 | GCC error: incomplete type 'claculator' used in nested name specifier | I develope a library, when I compile my code with GCC (in Windows with CodeBlocks), The source code doesn't compile and this error appears:
error: incomplete type 'claculator' used in nested name specifier.
I write a sample code that generate this error exactly:
class claculator;
template<class T>
class my_class
{
... | Its very simple. Define test() after the definition of calculator class as:
class calculator;
template<class T>
class my_class
{
public:
void test(); //Define it after the definition of `calculator`
T m_t;
};
// This class SHOULD after my_class.
// I can not move this class to top of my_class.
class ca... |
6,717,701 | 6,717,714 | Should I put & while passing a struct? | The code below is passing the struct variable:
struct someStruct {
unsigned int total;
};
int test(struct someStruct* state) {
state->total = 4;
}
int main () {
struct someStruct s;
s.total = 5;
test(&s);
printf("\ns.total = %d\n", s.total);
}
(The source from Pass struct by reference in C
)
... | In C++ you can make the function take a reference as parameter:
int test(someStruct& state) {
state.total = 4;
}
You can call the function like that:
someStruct s;
test(s);
No copy will be made. Inside the function, state will behave like it was s. Note that the struct keyword is only required when declaring the ... |
6,717,803 | 6,717,840 | Are two typelists spliceable in a constant time? | I'm working a bit with typelists defined in Alexandrescu's Modern C++ Design.
In his books, he talks about Appending a type to a typelist, but he doesn't talk about splicing two typelists...
I guess it is possible to splice two typelists using the Append functionnality, but wouldn't it result in a linear-time splicing ... | The typelist concept is usually* closer to the Computer Science notion of a list than the (doubly) linked list that std::list is. The two ideas share a name but have crucial differences.
Since metaprograms are purely functional you can't modify in-place an input typelist the way std::list::splice does: you have to 'gen... |
6,717,821 | 6,717,847 | Is vector::push_back() making a shallow copy & how to solve this | In the program I am writing, I have something similar to the code here:
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
struct people
{
string name;
int st;
int sn[50];
};
int main()
{
unsigned int n,ST[10]={25,18,15,12,10,8,6,4,2,1};
vector<people> master;
cin>>n;
... | push_back is making the copy of object being inserted using its copy constructor. If there is no custom one (like in case of your struct), the default is just to copy all fields, using their own copy constructors, etc.
For your struct - containing a string and a fixed-size array of fundamental type - result should be e... |
6,717,836 | 6,718,132 | Performance bottleneck - using Visual Studio | I'm looking for a way to find bottleneck methods in a solution (lots of projects).
Lets say i have a HUGE program (1000s of methods) and i want to improve performance by finding methods that are called a lot (actually used at runtime), and optimize them.
I need this for a complex problem that's written in C++, C#, CL... | Following one of Christian Goltz links, I've found a program that might do what I want, it profiles both managed and unmanaged code:
AQTime Pro
|
6,718,047 | 6,718,180 | ESP Not saved across function call / Runtime Error #0 | I get a strange error complaining about stack corruption I'm assuming, and I have debugged it a bit but I haven't found out the issue. I also can't seem to implement nothrow in Visual Studio 2010!
XYZ::XYZ(char * d)
{
hostname = new char[HOSTNAME_LENGTH];
ip = new char[IP_ADDR_LENGTH];
/*Dynamic Memory*/
... |
typedef int (*WSAS)(WORD, LPWSADATA); //WSAStartup
That's wrong, the calling convention is missing. It defaults to __cdecl which is not the way it is declared in winsock2.h. Which is why you are getting the runtime diagnostic, after the call it pops the arguments off the stack, something that was already done by WS... |
6,718,094 | 6,718,115 | Anonymous template typename/class declarations | I'm curious as to why anonymous template typename/class declarations are allowed, such as the following:
template <typename, class, typename> struct TemplateTest1 { int a; float b ; } ;
TemplateTest1 <int, int, int> tt1 ;
Can anyone explain the practical value of these anonymous types? Do they affect the expression of... | By anonymous, I assume you meant unnamed template parameter.
It's allowed, because sometimes you may not need the template argument, and so making it anonymous makes it clear to programmer that the argument is not used anywhere in the class, although it's not that necessary.
It is similar to the way a function with an ... |
6,718,107 | 6,718,160 | Problem pushing a float to stack for console Calculator | I'm writing a C++ console based calculator.
The way it'll work is
- the readEquation consists of an iterator that reads through the sum, and puts and pushes all numbers to the stack.
-when the read equation comes across an operator e.g. '+', it calls the add() function, which takes two parameters: add(float topOfStac... | stack<float>* numberStack;
This declares that your class will hold a pointer to a stack<float>. It does not allocate that object. You need to do that yourself (probably in the constructor), and also take care of deleting that object in your destructor.
// in ctor
numberStack = new stack<float>;
// in dtor
delete numb... |
6,718,209 | 6,718,412 | When should you use friend classes? |
Possible Duplicate:
When should you use 'friend' in C++?
I have come to a stumbling block because of lack of documentation on friend classes. Most books just explain it briefly, e.g an excerpt from C++: the Complete Reference:
Friend Classes are seldom used. They are supported to allow certain special case situatio... | Friend is used for granting selective access, just like the protected access specifier. It's also hard to come up with proper use case where use of protected is really useful.
In general, friend classes are useful in designs where there is intentional strong coupling: you need to have a special relationship between tw... |
6,718,217 | 6,718,584 | Is div function useful (stdlib.h)? | There is a function called div in C,C++ (stdlib.h)
div_t div(int numer, int denom);
typedef struct _div_t
{
int quot;
int rem;
} div_t;
But C,C++ have / and % operators.
My question is: "When there are / and % operators, Is div function useful?"
| The div() function returns a structure which contains the quotient and remainder of the division of the first parameter (the numerator) by the second (the denominator). There are four variants:
div_t div(int, int)
ldiv_t ldiv(long, long)
lldiv_t lldiv(long long, long long)
imaxdiv_t imaxdiv(intmax_t, intmax_t (intmax_... |
6,718,343 | 6,718,347 | How to use floating point tolerances in the Catch framework? | I'm using the Catch test framework.
In the introductory blog post the author mentions the following feature:
Floating point tolerances supported in an easy to use way
I couldn't find any documentation on how to do this. How is this done in Catch?
| It's simple. There is a class called Approx that lets you do this test in a very readable manner:
#include <limits>
TEST_CASE("demo/approx", "Approx demo") {
double a = 1.0;
double b = a + std::numeric_limits<double>::epsilon();
REQUIRE_FALSE(b == a);
REQUIRE(b == Approx(a));
}
The tolerance can be cha... |
6,718,465 | 6,718,526 | implement a pointer to a variable sized structure | I'm trying to parse returned information that can have a variable amount of data in a structure. I'm not sure how to do this efficiently, I wrote a class that contains each variable as a function and that function returns the data by calculating the appropriate offset however its not very manageable, there must be a be... | I assume that info_t is the format of the data you are trying to parse, so you can't change it.
Is there any particular reason why using the wrapper class isn't manageable? It seems like exactly the sort of problem where OOP is useful. If you wan't a class where the interface is compatible with info_t you could use the... |
6,718,479 | 6,718,503 | C++ initialization of non constant static member variable? | I got a qualification error of the member variable 'objectCount'. The compiler also returns 'ISO C++ forbids in-class intialization of non-const static member'.
This is the main class:
#include <iostream>
#include "Tree.h"
using namespace std;
int main()
{
Tree oak;
Tree elm;
Tree pine;
cout << "*****... | You have to define the static variable in the source file that includes this header.
#include "Tree.h"
int Tree::objectCount = 0; // This definition should not be in the header file.
// Definition resides in another source file.
// In this case it is main.cpp
|
6,718,538 | 6,721,267 | Does boost::scoped_ptr violate the guideline of logical constness | In boost::scoped_ptr operator* and operator-> are declared const functions, though they return T& and T* which potentially allows clients to change the underlying data. This violates the idea of logical constness (Myers, Effective C++)
Shouldn't the const functions have had the signature ?
const T& operator*() const;
c... | The fundamental issue here is that scoped_ptr objects behave more like pointers rather than class objects (even though scoped_ptr instances are in fact class objects).
The smart pointer classes provided by Boost are designed to preserve raw pointer semantics as much as possible† while providing additional functionality... |
6,718,551 | 6,718,679 | My software is still using some memory after lots of allocations | I wrote a small queue class in C++, on Windows.
Just to test, I'm allocating 1,0000,000 ints and reading them back.
The queue is doing its job correctly and is very fast, but the problem is that after complete deallocation, there is some memory usage reported by the task manager. For example, I still get 2MB of memory ... | OK a couple of bugs.
No destructor.
You are not leaking any memory because you remove all the items. But if you did not remove them all manually then your class would leak when it goes out of scope. Add a destructor that just deletes all the items on the list.
Dequeue is not exception safe:
T retval = this->m_root-... |
6,718,572 | 6,718,753 | Get number of columns in C++ with _bstr_t and ADO | I am using Visual Studio 2008, and SQL Server, Currently I have a connection using ADO, but would like to retrieve the number of columns a table has...
Here is what I have
/*CODE FOR connecting to database**/
/*query to know number of columns in table*/
_bstr_t sSQLd="Select Count(*) From INFORMATION_SCHEMA.COLUMNS Wh... | I think the examples in this MSDN article will help: How to: Convert Between Various String Types
Quoting from the article:
The strings types that are covered include char *, wchar_t*, _bstr_t,
CComBSTR, CString, basic_string, and System.String.
Convert from _bstr_t to wchar_t* or char* and then use strtol()/wcstol... |
6,718,654 | 6,719,135 | What kind of "Traits" are used/defined in the C++0x Standard | A trait in C++ encapsulates a family of operations that allow an Algorithm or Data Structure to operator with that type with which it is instantiated. char_traits are an example for grouping string- and file-required functions.
But not all traits have "trait" in their name, right? numeric_limits comes to mind. Is this ... |
*numeric_limits* definitely represents a set of traits for the numeric types.
all requirements like "CopyAssignable" etc. are indeed traits see this paper on traits
For the others I cannot comment but when in doubt:
Think of a trait as a small object whose main purpose is to carry
information used by another object... |
6,718,723 | 6,718,803 | c++ What files and libs to include? | Many times I find useful code examples on the Internet. About half of the time they don't specify what files to include or even what libs to include on the command line with -l. How do you usually find that out?
edit note: The problem below has been solved. The remainder of this post can be skipped.
Right now, I'm gett... | The short answer is 'it depends'. For classes / functions which are part of the C++ standard library the man pages which come with your compiler will list which header(s) and libraries are required; or alternately you can use online resources such as cplusplus.com, MSDN or GNU libstdc++ doxygen docs.
For things like Bo... |
6,718,724 | 6,718,811 | Best way to generate a set of integers of size N, distributed like a normal distribution, given a mean and std. deviation | I'm looking for a way to generate a set of integers with a specified mean and std. deviation.
Using the random library, it is possible to generate a set of random doubles distributed in gaussian fashion, this would look something like this:
#include <tr1/random>
std::tr1::normal_distribution<double> normal(mean, stdDe... | This isn't possible.
The gaussian distribution is continuous, the set of integers is discrete.
The gaussian pdf has unlimited support, if you specify minimum and maximum you'll also have a different distribution.
What are you really trying to do? Is it only the mean and standard deviation that count? Other distributi... |
6,718,846 | 6,805,016 | MFC VC++ Custom Checkbox Image | How do I get a 3-state checkbox to use a different bitmap for the Indeterminate state?
I want to change the image used by my 3-state checkboxes to use a different one; the controls are in Win98-style, and the indeterminate state of such checkboxes is difficult to distinguish from disabled checkboxes (this is presumably... | Not the answer, but an answer: this custom CCheckBox I found more-or-less enables what I want. It doesn't, by default, allow 3 states, but I fixed that up with some of my own tweaks. I'm not 100% sure it works out of the box (I've had some issues, that don't seem to be due to my edits, but I can't be sure), but it was ... |
6,718,848 | 6,718,864 | The code is supposed to return string without spaces, but it returns string until first space character | I'm making a console calculator, and I want to remove any whitespace that the user might enter while using the program. This is the code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
std::cout<<"Enter sum): ";
cin>>str;
str.erase(std::remove... | Your use of remove_if and erase is fine. Your method for getting input is not. operator>> is whitespace delimited. Use getline instead.
int main()
{
string str;
std::cout<<"Enter sum): ";
getline(cin,str);
str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end());
cout<<s... |
6,719,238 | 6,719,282 | Multiple conditions in for statement | I have this code in a function, but when it runs it does a long pause and then it says:
$floating point exception
I am assuming this is due to multiple conditions in the for loop, but I don't know why it is wrong. Any ideas?
int i,j,number=5;
for (i = 2; (i < number || j==1); i++)
{
if (number%i==0)
{
... | floating point exception - This means there's an arithmetic error.
It looks like you're trying to stop the loop with j, but what you're actually doing is continuing the loop forever (because once you get j==1 the or condition is always true).
What then happens is you loop i through all the Integer values back to 0 and ... |
6,719,347 | 6,719,360 | Class imitating a "pointer to a reference" can save out of scope variables? | I thought of a strange cheat in C++. Normally, I can't smuggle a reference out of a scope because I can't define an uninitialized reference in the containing scope. However, I can define a pointer to a class containing a reference, fail to initialize it, and then assign it the address of some dynamic memory initializ... | Just because your compiler doesn't emit a diagnostic for your program doesn't mean that your program is good, valid and safe.
Your final line invokes Undefined Behaviour because you have a dangling reference. This does not need to be diagnosed by the compiler, but it also doesn't make it right. You could get 4 (just so... |
6,719,407 | 6,719,433 | The credibility of the break statement | I had recently read in a book that using the break statement in say e.g. for loops is considered inelegant (although it is widely accepted for use in the switch statement).
What is the reason for this "accusation"?
Should I use a break statement in a for loop, or should I use multiple conditions?
| You'll have to ask the author of the book (which book?), since my ESP is on the fritz today[citation needed].
Sometimes[when?] it's said that, if you write lots of break statements throughout your code body, then it's no longer easy to see the loop invariants and the control flow without performing a detailed program a... |
6,719,502 | 6,719,511 | How do I reserve space for std::vector/std::string? | I'm looking for a way that prevents std::vectors/std::strings from growing in a given range of sizes (say I want to assume that a string will hold around 64 characters, but it can grow if needed). What's the best way to achieve this?
| Look at the .reserve() member function. The standard docs at the SGI site say
[4] Reserve() causes a reallocation manually. The main reason for
using reserve() is efficiency: if you know the capacity to which your
vector must eventually grow, then it is usually more efficient to
allocate that memory all at once... |
6,719,556 | 6,719,568 | How do I properly delete an array of doubles through a pointer after the pointer has been iterated? | I have created an array of doubles using the following code:
double *points = new double[(ii+1)*(jj+1)*(kk+1)*3];
I realize that in order to delete the array, all I have to do is:
delete[] points;
However; the array is created in a function (called create_points) that passes the address of the first element as follow... | You cannot say delete[] address, doing so is undefined behavior. You have to delete it through a pointer to the original base address of the array. So, if you're going to increment the pointer, you need to remember the original pointer (or recompute it):
double *base_address = create_points(...);
double *address = ba... |
6,719,701 | 6,719,716 | Difference between C and C++ | The code given here when compiled by g++ runs fine but gives error on compiling with gcc. Obviously, this is correct for C++ but not for C. Please help me to correct the syntax for C.
# include <stdio.h>
typedef struct demo
{
int arr[20], i;
void setvalue(int num)
{for(i=0;i<20;i++)arr[i]=num;}
void pr... | You can't have methods in C (that function in the struct). There's more than one way to solve this, but I would simply pass the object as the first argument to the function:
void setvalue(struct demo *d, int num)
{
int i;
for(i = 0; i < 20; i++)
d->arr[i] = num;
}
/* ... */
setvalue(&e, 100);
|
6,719,755 | 6,719,889 | How to convert QImage format to format supported by OpenGL | I'm using QImage to load images which then used as textures in OpenGL.
The problem is that color components have different order in QImage and OpenGL.
Currently I'm using GL_RGBA format in OpenGL and QImage::Format_ARGB32 in Qt.
Because of that, I have to manually swap bytes for each pixel of loaded image, before creat... | The last three parameters to glTex(Sub)Image define how the pixel transfer to OpenGL takes place. If you have 4 8-bit values, sequentially, in the ARGB order, then I would suggest the following:
glTexImage2D(..., GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, *);
To deal with endian conversion issues, use glPixelStore paramete... |
6,719,811 | 6,719,835 | Converting a string into an integer parameter |
Possible Duplicates:
How to convert a number to string and vice versa in C++
c++ - convert pointer string to integer
Is there a way to convert a string into an integer parameter without any big algorithms?
string = "100";
integerFunction(int string);
I've tried atoi functions and tried to manually convert each num... | Like this:
int StringToInt( const std::string & str )
{
std::stringstream ss(str);
int res = 0;
ss >> res;
return res
}
|
6,719,840 | 6,719,210 | Get path of current module after using RemoteThread | I need to get the current path of the module where my code executed (dll). I've made a dll injection from .NET into a native process and used RemoteThread.
I have tried getcwd, GetCurrentDirectory, GetModuleHandle.
Also tried this solution. But it doesn't work either. I get an empty string with the length of MAX_PATH.
... | There's a "hidden" tool helper library mentionned by Raymond Chen that gets around several quirks in the Win32 APi. It seems you can use that to fetch the handle to the first module associated to a process (presumably the original executable). You can use that handle to get the path to the executable.
Looks somethin... |
6,719,882 | 6,719,915 | How do you get a global var to be instantiated as the very first thing in C++ under win32? | sI'm on Windows and I'm building a C++ project with VS2008. I'm trying to replace new/delete/malloc/free etc. Which is working i.e. my replacements are getting called.
However my replacement allocator needs to be initialised. I have done this thus far by defining it as a global variable in a .cpp file with the #pra... | You are using a static storage duration object.
But you are having problems with the order of initialization.
To solve this use a static storage duration object that is defined within a function scope.
MyAllocator& getAllocator()
{
static MyAllocator allocator; // Note the static here.
... |
6,720,160 | 6,720,216 | float << operation by setting the precision for both integer part and float part | I would like to print floating point numbers in a format like this.
01234.56
I use the following function to round a float to n digits.
double round(double val, int precision)
{
std::stringstream s;
s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
s >> val;
return val... | the fixed manipulator will do the trick I think, my example below outputs what you wanted:
#include <iostream>
#include <iomanip>
using namespace std;
int main(void) {
cout << setprecision(2) << setfill ('0') << setw(5) << fixed << 8.2 << endl;
cout << setprecision(2) << setfill ('0') << setw(5) << fixed << 4.5... |
6,720,406 | 6,720,799 | Setting the screen origin in OpenCV 2.x (C++) | I'm trying to set the origin of the image I'm getting from my camera in OpenCV and I'm using cv::Mat instead of an IplImage. I know that you can set the origin in an IplImage (img->origin = 0 or 1) but I wasn't able to find any information on how to do the same for a cv::Mat.
I want to be able to set the origin to th... | I don't believe this is possible. According to the API, IplImage has a field for the origin (naturally), but CvMat does not. This makes sense because there's no concept of an origin with matrices.
FYI here's the API I used: OpenCV
|
6,720,780 | 6,720,894 | Multimap order of equal keys in VC++ | The question whether a multimap preserves the insertion order of identical keys has been asked numerous times and I think it is pretty clear that the standard says it doesn't. Although apparently C++0x for a while said it did and then didn't again?
Anyway, I need a structure on which I can look up by key, and iterate o... | std::map<std::vector<T> > fulfills all your requirements.
|
6,720,881 | 6,736,586 | Mapping dynamic texture causing "Already Mapped Error" | I just starting using Direct3D11 and I am trying to create a dynamic texture that I plan to update with new data several times a second. My issue is that every time I update the texture with the new data, I get this error from the D3D Debugger:
D3D11: ERROR: ID3D11DeviceContext::Map: This resource is already mapped!
[... | Its funny how when you start asking questions about something your stuck on, it becomes easier to find the problem haha.
I figured out what the issue was. It was my HR macro that I was surrounding the map call with.
#define HR(x)
{ ... |
6,720,993 | 6,721,480 | Accessing USB webcam via Cortex-M3 | Afternoon all,
A am wondering if it is at all possible to hijack the video stream of a USB webcam via a microcontroller (STM32F103, Cortex M3, 73MHz) to add a HUD to the device. Then re-package the stream into the same USB endpoint plus a control endpoint?
I can not find any information what so ever on interfacing with... | It's not possible with that chip, which has only a full-speed USB device interface.
You need
a USB host port
which supports high-speed
and a faster processor to deal with that much data
|
6,721,037 | 6,721,040 | Where is __LP64__ defined for default builds of C++ applications on OSX 10.6? | I am building a 3rd-party library in 32-bit mode on OSX 10.6 (the library is Xerces 2.8). I have determined that the preprocessor definition __LP64__ is set. However, as far as I can see it is not being set within any configuration files of the 3rd-party project, and doing a global search through all files (via the F... | It's defined automatically by the compiler rather than in any header. If it's set, you're building for 64-bit targets.
(A header could define it if the compiler hasn't already, though it shouldn't. If you think this is the case, add #define __LP64__ to your code, and look at the error during preprocessing to determine ... |
6,721,097 | 6,721,152 | Is it possible to build 32-bit applications on OSX 10.6 that run on other OSX 10.6 systems? | When building C++ projects using make on OSX 10.6, I have determined that the preprocessor definition __LP64__ seems to be always automatically set by the compiler (i.e., it is not defined in any header file) (see Where is __LP64__ defined for default builds of C++ applications on OSX 10.6?). This leads to the questio... | Yes, it is perfectly possible to do that. One limited demonstration:
$ tar -xf Packages/range-1.14.tgz
$ cd range-1.14
$ ls
COPYING Makefile README gpl-3.0.txt range.c range.mk stderr.c stderr.h
$ rmk CC='gcc -m32'
gcc -m32 -g -c stderr.c
gcc -m32 -g -c range.c
gcc -m32 -o range -g st... |
6,721,153 | 6,724,197 | HttpAddUrl on localhost fails for non-admin users | Using the Windows HTTP API I'm running a HTTP file server on localhost.
This involves calling HttpAddUrl(hRequestQueue, L"http://localhost:80/", NULL).
This fails with ERROR_ACCESS_DENIED unless the user runs the application as administrator. I need this functionality for users who don't have admin privileges. (What'... | Answering my own question, but found a workaround: the IANA port numbers state ports 49152-65535 are for dynamic/private purposes. HttpAddUrl for localhost on a port >= 49152 works fine for non-admins.
|
6,721,228 | 6,721,244 | Overloading + Operator in C++ for a Dynamically Allocated Type | I'm trying to override the + operator for a type whose constructor involves calling new (that is, the constructor needs to dynamically allocate something else) and hence whose destructor involves calling delete. Somewhere, I'd like to be able to use something like:
T c = a + b;
My problem is that I obviously need to ... | You make sure T obeys The Rule of 3, and there are no worries.
|
6,721,297 | 6,721,311 | The name of function "mem_fun_t" | What does the "t" prefix of mem_fun_t of STL stand for?
The difference between mem_fun and mem_fun_t is that the first one is a function returning an object of the second one, but how it "t" related to being a class?
| t is for type. (nullptr_t is the type of nullptr, mem_fun_t is the type of mem_fun.size_t` is the type used to denote object sizes and so on)
|
6,721,370 | 6,721,413 | What does the "&SomeStruct::member" mean in C++ where "SomeStruct" is a struct and "member" is its member? | Say SomeStruct is defined as:
struct SomeStruct {
int member;
};
What does these means?
&SomeStruct::member
int SomeStruct::*
I encounter this, tried to output its type info but still cannot figure out the meaning. Below is a working example:
#include <iostream>
#include <typeinfo>
using namespace std;
struct S... | int SomeStruct::* is called a "pointer to member", in this case, a pointer to a member of SomeStruct. This is NOT strictly a pointer to a member function (although this is the most common use of this syntax).
&SomeStruct::member is a reference to the member member of SomeStruct.
See this related question
If you'd like... |
6,721,431 | 6,721,467 | Effect of `explicit` on static upcasting | May an instance of a derived class be implicitly converted to an instance of its base class, when the only candidate constructor in the base class is marked explicit?
I ran this:
struct Base {
Base() {}
explicit Base(Base const& b) {}
};
struct Derived : Base {};
int main() {
Derived d;
Base b = d;
}
An... | It's not the conversion that fails. Copy-initialization requires an accessible copy-constructor.
This also fails:
struct Base {
Base() {}
explicit Base(Base const& b) {}
};
int main() {
Base d;
Base b = d;
}
|
6,721,559 | 6,721,583 | library not found for -lboost_system | I installed boost using macports. The files appear to be in /opt/local/include/boost/
My makefile is no longer working and I get the following error
Undefined symbols:
"boost::system::generic_category()", referenced from:
__static_initialization_and_destruction_0(int, int)in client.o
__static_initialization_and_des... | You're missing a -L/opt/local/lib. You should be able to set the LDFLAGS in your Makefile:
LDFLAGS=-L/opt/local/lib
This assumes that the Boost libraries are in /opt/local/lib of course.
If you're not using the usual CXXFLAGS and LDFLAGS variables in your Makefile, then add the -L/opt/local/lib directly in your final ... |
6,721,798 | 6,722,050 | Strange error trying to read registry value with Windows/C++ | I'm trying to read the install path for an application, and I'm baffled at the behaviour I'm getting. First, here's the code that didn't work (formatted it a little so it doesn't take up a huge line):
LONG status = RegQueryValueEx(
hkRegistry,
"InstallPath",
0,
®Type, (LPBYTE)installPath,
®Siz... | It's possible that the buffer for installPath is too small compared to the value contained in regSize (which must be initialized to the size of the buffer).
If installPath is a stack-allocated value I suspect that it is overflown, causing the value of status to get overwritten.
|
6,721,842 | 6,746,259 | Scripting languages on iOS games | First of all, there are other topics covering this subject but they were posted before Apple made the latest changes in its licenses this year.
I'm quite confused with Apple's iOS developer agreement license. Does it completely forbid scripting languages on game programming? Even if I don't compile it at runtime and pr... | You can use a scripting language as long as it doesn't download any code. It's not the scripting language apple has a problem with Angry birds for instance uses (lots) of Lua code.
If though you try downloading code and executing it then Apple will reject your app. Although even this is a gray area. For instance 'when... |
6,722,024 | 6,722,194 | Making C++ Classes inherit from C Structs, Recommended? | I was recently doing some Windows Api coding (still doing it). And I was trying to find the best way to wrap the WNDCLASSEX into a C++ class, when I had this crazy idea, the WNDCLASSEX is a struct right? (even though it is written in c) and in C++ structs are treated as classes, so why don't I declare my WinCLass as a ... | The only difference between a class and a structure in C++ is that of Access specifiers.
For classes the access specifier is private by default.
For structures the access specifier is public by default.
This means if you have a class deriving from other class/struct it will be private inheritance by default &
If you... |
6,722,057 | 6,722,076 | Passing a node as an outstream operator | This prints an error message about qualifiers but don't really understand what that means and how to adjust the code for it to work? Anyways, thanks a lot for looking at the code.
Note: The ostream operator is friended in the Node class.
using namespace std;
ostream& operator(ostream& output, const Node* currentNode)
... | Your overloaded stream operator declaration should be like this:
std::ostream& operator<<(std::ostream& os, const T& obj);
^^^^^^^^^^^^^
You should be returning a reference to object of std::ostream, the & is wrongly placed in your overloaded function prototype.
Have a look at the working sample here.
Adding the sour... |
6,722,119 | 6,722,224 | Difference between scalar SQL functions and aggregate SQL functions in SQLite | What is the exact difference between scalar SQL functions and aggregate SQL functions in SQLite?
I am getting a problem with the following code when attempting to create a new function in SQLite:
int sqlite3_create_function(
sqlite3 *db,
const char *zFunctionName,
int nArg,
int eTextRep,
void ... | A scalar function is a function that operates on scalar values -- that is, it takes one (or more) input values as arguments directly and returns a value.
An aggregate function is a function that operates on aggregate data -- that is, it takes a complete set of data as input and returns a value that is computed from all... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.