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 |
|---|---|---|---|---|
7,479,946 | 7,480,147 | what's an expression and expression statement in c++? | I've read that usually statements in c++ end with a semi-colon; so that might help explain what an expression statement would be. But then what would you call an expression by giving an example?
In this case, are both just statements or expression statements or expressions?
int x;
x = 0;
| An expression is "a sequence of operators and operands that specifies a computation" (that's the definition given in the C++ standard). Examples are 42, 2 + 2, "hello, world", and func("argument"). Assignments are expressions in C++; so are function calls.
I don't see a definition for the term "statement", but basica... |
7,480,146 | 7,480,320 | Difference between exception handling in C++ and Java? | In Java, if a specific line of code causes the program to crash, then the exception is caught and the program continues to execute.
However, in C++, if I have a piece of code that causes the program to crash, like:
try
{
int x = 6;
int *p = NULL;
p = reinterpret_cast<int*>(x);
*p = 10; // the program c... | The line that crashes is dereferencing an invalid pointer. In C++ this will not throw an exception. Instead it is undefined behaviour.
There's no such thing as a null pointer exception in C++, unlike Java which will throw a null pointer exception. Instead dereferencing an invalid pointer will lead to undefined behaviou... |
7,480,467 | 7,480,481 | C++ String Class Input | I'm attempting to read in user inputted values about put them into a string class array, but I'm getting a BAD EXCESS error, I'm guessing its something really simple that I'm doing wrong. Here is what I got. Any help would be great
int main()
{
const int SIZE = 5;
string fruity[SIZE];
int i;
cout << "Enter... | cout << fruity[i] << endl;
This is invalid. Do this instead:
for(i = 0; i < SIZE; i++)
cout << fruity[i] << endl;
Because at that point your i will be equal to SIZE, and fruity[SIZE] is invalid.
|
7,480,802 | 7,480,892 | GetThreadContext returning error 6, Invalid Handle? | #include <iostream>
#include <Windows.h>
using std::cout;
using std::endl;
using std::cin;
int main()
{
cout << "1." << GetLastError() << endl;
PROCESS_INFORMATION processInfo;
STARTUPINFOA startupInfo = {0};
CONTEXT context;
context.ContextFlags = CONTEXT_FULL;
cout << "3." << GetLastError(... | You should use processInfo.hThread as that is the handle to the primary thread of the new process. processInfo.hProcess is a process handle, not a thread handle.
As for GetLastError() returning ERROR_FILE_NOT_FOUND, presumably someone else called an API that called SetLastError(ERROR_FILE_NOT_FOUND). From the documenta... |
7,481,621 | 7,481,644 | Using overload operator new within class | Lets say I have a class A and I overload operator new in the class.
class A{
public:
A();
void *operator new(size_t size);
void operator delete(void *p);
}
How would I use this overloaded operator new inside of class A instead of the global new?
For example
A::A(){
...
int *temp = new int[10]; ... | That overloaded version will be used for creating objects of class A and its descendants only - such as when you have new A() in your code. It won't be called for new A[] unless you overload operator new[]() as well.
In order to have your operator new[]() function used when you do new int[] you have to replace global o... |
7,481,825 | 7,481,886 | enum initialization issue | Here is a sample program :
class BASE
{
public:
enum ABC
{
ZERO,
ONE,
TWO,
LAST
};
BASE(ABC exp): type(exp)
{
A[ZERO] = "1111";
A[ONE] = "22222";
A[LAST] = "LLLL... | A is an array of three pointers, A[0], A[1], and A[2].
You have a pointer to "LLLL" which is OK. But when you try to assign that pointer to A[3], there is no such object as A[3].
|
7,481,868 | 7,488,312 | Interrupt thread after amount of time, without blocking while waiting | I'd like to start a thread in the background and want to stop it after a certain amount of time if it not finishes. Main Problem is, while waiting for the thread to finish or a timer to reach a deadline, the program should not block. Its important to guarentee that.
I tried this example, but while waiting for timed_joi... | You can start a thread that will start your thread and wait for the timed_join.
main
|
|---thread
| |
| |-----thread
| |
| |
| |
| join<------
|
|
But if you just want a warning, put it before starting the thread. If it is a graphical application and you sti... |
7,481,967 | 7,482,017 | variable not declared in scope using template inheritance | OMStatic.h
template<class Concept> class OMStaticArray :
public OMAbstructContainer<Concept> {
protected:
Concept *theLink;
int count;
void* AllocateMemory(int size);
bool ReleaseMemory(void* pMemory);
//...
};
OMCollec.h
template<class Concept> class OMCollection :
public OMStat... | This is best explained in the C++ FAQ: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19.
To paraphrase:
Within OMCollection<Concept>::add(), the name count does not
depend on template parameter Concept, so count is known as a
nondependent name. On the other hand, OMStaticArray<Concept> is
dependent... |
7,481,968 | 7,483,608 | samsung bada development without using pointers | Objects in C++ can be created using the methods listed below(that I am aware of):
Person p;
or
Person p("foobar");
or
Person * p = new Person();
Then, why does not the Samsung Bada IDE allow me to do the first two methods? Why do I always have to use pointers? I am ok with using pointers and all, just that I want t... | In this code:
// Create a Label
Label pLabel;
pLabel.Construct(Rectangle(50, 200, 150, 40), L"Text");
pLabel.SetBackgroundColor(Color::COLOR_BLUE);
AddControl(pLabel);
the label object is destroyed when it goes out of scope and hence it fails to show up on the form. It is unfortunate that the AddControl method takes a... |
7,482,026 | 7,489,484 | Can i use the latest features of C++11 in XCode 4 or OSX Lion? |
Possible Duplicate:
Can I use C++11 with Xcode?
It seems like xcode 4 contains older versions of clang and gcc. Can i uppgrade gcc or clang and use them with xcode 4? I would like to use gcc >= 4.6 or the latest clang.
My main goal is to be able to have as much of the new features from C++11 available when programmi... | The version of clang in Xcode 4.1 does support some C++11 features, including variadic templates and rvalue references. Also libc++, an implementation of the C++11 standard library is included in Lion.
See my answer to Osx Lion: Xcode 4.1 how do I setup a c++0x project for details on setting this up.
|
7,482,567 | 7,482,752 | Is there a clean separating definition between "STL" and "C++ Standard Library"? |
Possible Duplicate:
What's this STL vs. “C++ Standard Library” fight all about?
I am very much used to the term STL ("Standard Template Library") and I catch myself often using it when I really mean the C++ Standard Library. So, since almost everything in the C++(-11) Standard Library is a template nowadays, I wonde... | STL has evolved into C++ Standard Library, it contained containers, iterators and algorithms but not streams. It is better not to use term "STL" it is the name of the old library.
|
7,482,891 | 7,483,544 | inheriting noncopyable has no effect in dllexport classes | UPDATE the belowmentioned bug is fixed in VS2012, and noncopyable works as epected
This is both a question and a way to provide information / warn others so they don't fall into the same trap as I did: it seems that using a noncopyable base class (like the one in boost) has no effect in exported classes when using the ... | To answer 1 (for VS2010), I just tried it in VS2010 (with SP1) and it compiles just fine, which means it has not been fixed. Unfortunately I do not have 2011 to test
To 2. I guess one way to do it would be to:
no longer derive from noncopyable
declare the copy ctor and assignment operator as private in CantCopyMe wit... |
7,483,634 | 7,483,820 | Determining if one array is contained in another | How do I determine if one array is contained (element by element and in order) in another array? I have written the program below in MSVS 2010 but not too sure how to complete the boolean function that determines if one array appears in the other one
void isContained( int ar1[], int ar2[] );
int main( int argc, char... | Simple. Let's say you want to check if ar2 is contained in ar1.
An example:
Ar1: 1 2 3 4 5 6 7 8 9 10 5 2 8 2 4 2 4 6 2 9 1
Ar2: 2 4 6 2
Let's also assume you have the lengths of the arrays in Ar1_len and Ar2_len
You have to go through Ar1, find an element that matches the first element of Ar2 then from there on, try ... |
7,483,739 | 8,491,563 | Is this hack to remove aliasing warning UB? | We just upgraded our compiler to gcc 4.6 and now we get some of these warnings. At the moment our codebase is not in a state to be compiled with c++0x and anyway, we don't want to run this in prod (at least not yet) - so I needed a fix to remove this warning.
The warnings occur typically because of something like this:... | SomeDataPage page;
new(page.vData) SomeType(); // non-trivial constructor
reinterpret_cast<SomeType*>(page.vData)->some_member();
This was okay with 4.4; in 4.6 the above generates:
warning: type punned pointer will break strict-aliasing rules
You can try:
SomeDataPage page;
SomeType *data = new(page.vData) SomeTy... |
7,483,809 | 7,484,380 | LuaBind: How to bind specific instance of class to Lua? | (sidenote: This is game programming)
Binding entire classes to Lua using LuaBind is easy:
class test
{
test()
{
std::cout<<"constructed!"<<std::endl;
}
void print()
{
std::cout<<"works!"<<std::endl;
}
}
//somewhere else
module[some_lua_state]
[
class_<test>("test")
.def... | You don't bind instances of classes to Lua. Instances of classes are just data, and you can pass data to Lua via the usual means. C++ objects are special though; because they're registered through Luabind, you have to use Luabind methods to provide them to Lua scripts.
There are several ways to give data to Lua, and Lu... |
7,483,858 | 7,483,960 | qsorting an array of class pointers | I've read a lot of material on how to do this. Unfortunately, they all resort to using something other than qsort (sort, usually). However, this is impossible for me as I'm not allowed to use anything from the algorithm library. I have to implement this from scratch, pretty much. What I've got:
class String {
publi... | You have used list->size instead of list->size(). The code should be:
qsort(list->list, list->size(), sizeof(String**), compare);
|
7,484,130 | 7,485,625 | How can I increase the available memory for a process on Windows Mobile? | The amount of virtual memory available to my process is 32MB, although there's plenty more actual RAM. Is there a way (e.g. a function call or project property) that can increase this limit? I am finding the limit very....limiting.
I am looking at the usage by calling GlobalMemoryStatusEx. If there was something that ... | No, there's no way to increase that. Windows CE 5.0 and earlier had a hard, baked in limit of 32MB of virtual memory for any of the supported 32 simultaneous processes. It's part of the kernel.
Now it is worth mentioning that not all allocations come from that 32MB. From the docs (and experience):
If you call Virtu... |
7,484,133 | 7,484,171 | how many times will an unsigned Char loop run | I'm a noob at C/C++ So excuse the simplicity of the question, but here goes
unsigned char i;
for (i=0; i<1000; ++i)
if ((i%4) == 0)
printf("hello\n");
how many times will the code print "hello". I say 63, but alas its not one of the options. Can someone provide an answer, but more importantly an explanation as t... | Note: I am assuming 8 bit char types.
You will overflow when you perform ++i for i equal to 255. At that point the language standard decrees that i becomes 0, a phenomenon commonly known as wraparound.
So, you have an infinite loop, since i<1000 for all values of i.
|
7,484,159 | 7,484,266 | C++ converting file stream function to use a stringstream | I have loads of c++ classes that reads data from a file stream. The functions looks like this.
bool LoadFromFile(class ifstream &file);
I'm creating a new function to read from memory instead of a file. So I googled around and a istringstream seems to do the trick without any modifications to the code.
bool LoadFromDa... | Write an own basic_streambuf class! More details.. (This way you could work on the current memory.)
To create string from pointer and size: string str(data,data+size); (it will copy the data).
On more thing: you should rewrite your functions to based on istream:
bool LoadFromStream(istream &is);
In this way you could ... |
7,484,200 | 7,484,254 | C++ UNIX: Threading: Make Main-Thread wait or sleep until processing is over - main-thread doesnt know pthread_t refrences | sc->start_server runs an endless loop in which a MyClass processing method is invoked in a thread.
How can i replace the while(true) statement in main so that my program waits for all threads to terminate?
EDIT: pthreads-lib is used and main() does not know the pthread_t references
THX
int main(int argc, char** argv)... | Use join on any thread you want to wait.
|
7,484,271 | 7,487,262 | DBX core file truncated? | I'm using the latest version of dbxtool (Solaris Studio ) on RHEL6.1.
I'm working through the tutorial example here using their example code, but when trying to run dbxtool on the core file generated, I get the following:
(dbx) cd /users/rory/Desktop/debug_tutorial
(dbx) debug /users/rory/Desktop/debug_tutorial/a.out c... | This is a known dbx problem on RH6 (CR 7077948). The core file size is miscalculated if a data segment has a memory size larger than the file size (p_filesz) in the elf header. This problem has been identified and fixed in dbx 7.9.
|
7,484,340 | 7,484,792 | Templates instantiation in C++ | I am confused by how C++ instantiate template. I have a piece of code:
template <class T, int arraySize>
void test1(T (&array)[arraySize])
{
cout << typeid(T).name() << endl;
}
template<class T>
void test2(T &array)
{
cout << typeid(T).name() << endl;
}
int main()
{
int abc[5];
test1(abc);
test2(a... | In test1 the compiler creates a template with T[arraySize] being its form.
When you call test1(abc) you are providing an input argument of type int[5] which the template matcher automatically matches.
However, if you were to write
int n=10;
int *abc = new int[n];
test1(abc);
test1<int,n>(abc);
then the compilation wou... |
7,484,464 | 7,484,573 | Is there a way of causing a compile error if trying to assign a negative number to an unsigned container? | Is there a way of guarding against the resulting binary from the code in this question? Ideally by way of an error at compile time. Example code from the question:
unsigned int nVal = 0;
nVal = -5; // no error!
| If you are using g++, the switch -Wsign-conversion will warn about the conversion, and -Werror will make that warning an error.
|
7,484,548 | 7,484,637 | Wrap many C calling functions to single implementation | ``I have a requirement that the function call will have different names but all of them should refer to the same definition while executing.
For example,
i have a function calls like
UINT8 vsignal;UINT8 vsignal1;void Read_Message1_Signal1(&vSignal);void Read_Message2_Signal2(&vSignal1);
but this should be linked to
vo... | Is there some reason you can't just write your own wrapper?
void Read_Message1_Signal1(&vSignal)
{
Read_Message_Signal(vSignal);
}
void Read_Message2_Signal2(&vSignal)
{
Read_Message_Signal(vSignal);
}
You can autogenerate these with a macro if there are a lot of them.
|
7,484,730 | 7,750,276 | QGraphicsDropShadowEffect hogs cpu on embedded system | I created a widget that serves as some kind of popup window und hence should have a drop shadow all around to optically raise it from the background. I initialize the drop shadow effect in the constructor of my popup widget as follows:
dropshadow = new QGraphicsDropShadowEffect(this);
dropshadow->setBlurRadius(32);
dro... | The problem was only partly with the drop shadow. It seems that repainting a drop shadow requires quite a lot of CPU time - which is OK if it is not redrawn too often. The problem was simple really. The widget that was behind this popup was redrawn four to five times per second and hence, the popup needed to be redrawn... |
7,484,784 | 7,485,079 | Copying a GpuMat row to a std::vector | How can I transfer cv::gpu::GpuMat rows to std::vector with as little as possible copy operations?
The fastest way I can think of is:
GpuMat fooGpu(numRows, numCols, CV_32FC1);
Mat foo = fooGpu;
Mat fooRow = foo.row(i);
std::vector<float> vec;
vec.resize(numCols);
memcpy(&vec[0], fooRow.data, sizeof(float)*numCols);... | Here is the method that does not produce any unnecessary copying:
GpuMat fooGpu(numRows, numCols, CV_32FC1);
std::vector<float> vec;
vec.resize(numCols);
fooGpu.row(i).download(Mat(vec).reshape(1/*channels*/, 1/*rows*/));
|
7,484,913 | 7,485,177 | Why can't static_cast be used to down-cast when virtual inheritance is involved? | Consider the following code:
struct Base {};
struct Derived : public virtual Base {};
void f()
{
Base* b = new Derived;
Derived* d = static_cast<Derived*>(b);
}
This is prohibited by the standard ([n3290: 5.2.9/2]) so the code does not compile, because Derived virtually inherits from Base. Removing the virtua... | The technical problem is that there's no way to work out from a Base* what the offset is between the start of the Base sub-object and the start of the Derived object.
In your example it appears OK, because there's only one class in sight with a Base base, and so it appears irrelevant that the inheritance is virtual. B... |
7,484,958 | 7,485,917 | Boost IPC Equivalent (qt?) | I am working on an application which currently has a plugin to a particular software suite and then a separate application which communicates with the plugin using boost ipc.
The latest version of the application we are plugging into was just released with a very old version of boost (1.35 I think) as part of their SDK... | Using XML and TCP/IP? It is future proof and independent from the OS and the implementation.
Check QTcpServer, QTcpSocket, QXmlStreamReader and QXmlStreamWriter!
For classical IPC: check Qt documentation.
|
7,484,961 | 7,485,143 | image manipulation library | I need a library for mostly color manipulation, I want to make a image become black and white, and augment the contrast, so that Tesseract (Google OCR library) can read better the images that I throw at it.
Or if someone has a better idea on how to improve Tesseract results, I am all for it.
| Try OpenCV
http://sourceforge.net/projects/opencv/
Or imagemagick
http://www.imagemagick.org/script/magick++.php
or CImg, probably the easiest to use: no install it's just a header file.
If you do not want to use a big library you can code the algorithm yourself:
https://web.archive.org/web/20140825114946/http://bobpow... |
7,485,088 | 7,485,105 | What does the operation c=a+++b mean? | The following code has me confused
int a=2,b=5,c;
c=a+++b;
printf("%d,%d,%d",a,b,c);
I expected the output to be 3,5,8, mainly because a++ means 2 +1 which equals 3, and 3 + 5 equals 8, so I expected 3,5,8. It turns out that the result is 3,5,7. Can someone explain why this is the case?
| It's parsed as c = a++ + b, and a++ means post-increment, i.e. increment after taking the value of a to compute a + b == 2 + 5.
Please, never write code like this.
|
7,485,332 | 7,485,478 | HMACSHA1 off by 2 bytes | I am using this class in MSVC++ 2010 Express: http://www.codeproject.com/KB/recipes/HMACSHA1class.aspx. I am running Vista 32bit. Pretty much to get it working I just changed...
SHA1.cpp:
fIn = fopen(szFileName, "rb");
to
fIn = fopen_s(szFileName, "rb");
because without this change it would say: "error C3861: 'fope... | I guess it's because some byte-values in digest are < 10 which means only one character is written.
Maybe this solves your problem:
for(int i=0;i<sizeof(digest);i++)
std::cout << setfill('0') << setw(2) << hex << (int)digest[i];
|
7,485,436 | 7,485,560 | Is it possible to do simple arithmetic (e.g. addition) on "compressed" integers? | I would like to compress an an array of integers, initially initialized to 0, using a yet-to-be-determined integer compression/decompression method.
Is it possible with some integer compression method to increment (+1) a specific element of an array of compressed integers accurately using C or C++?
| You can certainly implement this, if your increment method:
Decompresses the entire array.
Increments the desired entry.
Compresses the entire array again.
If you want to increment in less of a dumb way you'll need intimate knowledge of the compression process, and so would we to give you more assistance.
|
7,485,462 | 7,486,700 | How to document macro-generated classes with Doxygen? | I use macros to generate classes in the following way:
generator.h:
class CLASS_NAME : public parent
{
//generate variables with names given by CLASS_VARIABLES using complicated
//Boost.Preprocessor stuff.
};
#undef CLASS_NAME
#undef CLASS_VARIABLES
myclass.h:
#define CLASS_NAME MyClass
#define CLASS_VARIABLE... | It won't work. The Doxygen preprocessor doesn't really perform full blown file inclusion (it only looks in the included files for macro definitions; otherwise, the ENABLE_PREPROCESSING directive would be totally useless!). So the #include "generator.h" has no effect.
If you physically replace the #include directive wi... |
7,485,584 | 7,485,710 | Why does this call by reference create a new instance? | Im calling a method foo by const ref:
// method, which is being called
void foo(const Entity & ent);
// call
Entity* e = new Entity;
foo(e); // wrong: missing * but compiles
This piece of code does not only compile, it creates a new instance of Entity with its default values in the scope of foo. I'd expect that th... | [Edited] You have an implicit converting constructor (that also happens to be a default constructor) from Entity* (via parent QObject*) to Entity and it's being used to create a temporary instance to pass in.
For this reason I always suggest by default making all single-parameter callable constructors (for example wher... |
7,485,593 | 7,486,164 | Better interface for a class that hide container | I have MyClass that hide the container inside it, I want to control when new item is added to the container and when an item is to be deleted from container, but i don't need to control read-only operation such as getter function
class MyClass {
protected:
std::vector<MySubClass> subclasses;
public:
}
... | If you invent your own member functions for manipulating the internal list of objects, then I will have to learn your interface when I want to use your class.
I much rather you use the conventions of the standard library, which I already know, so I can use your class immediately:
class MyClass {
protected:
... |
7,485,606 | 7,485,656 | Destructor called for each object in an array | I have an array of objects:
Square sq[81];
I think it uses the default constructor to created each.
When I go though a for loop to initialize each, it calls the destructor for each Square object in the array.
for (int k=0; k<9; k++) {
for(int j=0; j<9; j++) {
sq[count++] = Square(k, j);
}
}
When Square(k... | sq[count++] = Square(k, j);
When Square(k, j) is called, is it deleting the object in sq[] and creating a new one?
No.
Square(k, j) creates a new temporary object and = copies it into the old one. The temporary object is then destroyed as it is not longer required and goes out of scope.
BTW, you're not actually in... |
7,485,807 | 7,486,390 | Java Code For Pulling Hard Drive Information From Linux | I've recently been tasked with developing a program to monitor a bunch of hard drive information (serial, maker, type, etc) from multiple hard drives. In my initial research I found that this was pretty easy to do using some C# code and created a test program that way. Unfortunately, I'm required to use a linux OS whic... | Depending on the exact information you need there might be no need to use JNI.
Linux make a lot of information about the hardware available in the sysfs and procfs virtual filesystems. For instance, you can find the harddisk model for the fist disk in /sys/block/sda/device/model, which you should be able to read in J... |
7,486,609 | 7,486,962 | Custom archive format File Reading | C#.NET 4.0
I'm having an interesting problem here with reading a custom file archive format. In C#, I wrote a program that creates an archive header (some overhead info about the archive as a whole, number of files, those kinds of things). It then takes an input file to be stored, reads and bytes, and then writes som... | Given that the first n bytes appear to be correct, did you by chance forget to open the file in binary mode ("rb")? If you didn't then it's helpfully converting any sequences of \r\n into \n for you which would obviously not be what you want.
Since this question is tagged C++ did you consider using the canonical C++ ap... |
7,486,721 | 7,487,230 | QTcpSocket and deletion | I'm writing a tcp based server using Qt.
I plan this server to be multithreaded,
so my tcpserver class inherits from QTcpServer and overrides incomingConnection(). Everything is fine, except when it comes to deleting a user.
The TcpServer class manages
a list of QSharedPointer<Client>. When I remove the said client fro... | You need to use deleteLater on the Object. Incoming messages may come in after you delete the QTCPSocket. It is documented in Assistant. You can find an example here: qthelp://com.trolltech.qt.472/qdoc/qt4-network.html
M
|
7,486,896 | 7,489,630 | Need help using NtCreateFile() to open by fileIndex | I have written a program that queries the change journal records and lists them. The change journal returns:
1) filereferencenumber( combination of fileindex.high and fileindex.low)
2) parentfilereferencenumber(same as above except it is for directory)
3) szReason(Reason it appears in the change record)
4) Filename an... | Here is the code I used:
http://www.ragestorm.net/blogs/?cat=7
#include windows.h
typedef ULONG (__stdcall *pNtCreateFile)(
PHANDLE FileHandle,
ULONG DesiredAccess,
PVOID ObjectAttributes,
PVOID IoStatusBlock,
PLARGE_INTEGER AllocationSize,
ULONG FileAttributes,
ULONG ShareAccess,
ULONG Creat... |
7,487,036 | 7,487,104 | If I know .NET 4.0 is installed on a user's machine, can I assume .NET 2.0 is as well? | Pretty self-explanatory question, but here's a bit of context:
My app (C++, unmanaged) has a feature written as a C# app. This feature is only available when we know .NET is installed. So, must I maintain separate versions of this C# application for each framework version we want to support, or will a lowest-common-den... | The .NET framework dependencies page for .NET 4 on MSDN says that yes, you can count on it:
You do not have to install previous versions of the .NET Framework or
the CLR before you install the latest version; each version provides
the necessary components.
|
7,487,254 | 7,488,446 | Taking key/value pair from string and storing in map | What is the best way to split a string in two? I have this but can't get 'name' right as the substr doesnt allow me to set where to start from and where to finish, only where to start from and for how many characters (which is unknown to me):
string query = "key=value";
string key;
string value;
int positionOfEquals =... | Yours is a fine approach, but you still have one bug. What if there is no '='?
string query = "key=value";
string key;
string value;
int positionOfEquals = query.find("=");
key = query.substr(0, positionOfEquals );
if(positionOfEquals != string::npos)
value = query.substr(positionOfEquals + 1);
|
7,487,303 | 7,502,145 | It's legal to mix c++0x threads with gio GCancellable? | If I'm not wrong there is no easy way to make a c++0x thread cancellable. I'm wondering if it's legal to use GCancellable mixing it with c++0x thread.
If the answer is
No
I guess I should use glib threads or it's not so legal too?
| I am not very familiar with GCancellable. After a quick read through, it appears to be a hierarchical notification system.
If that is the case then yes you can easily mix GCancellable with std::thread.
There is no easy way to make a std::thread cancellable.
This is wrong.
There is no non-zero cost way to make all ... |
7,487,305 | 7,712,720 | Are there any registry entries that indicate whether a specific C Run-Time is already installed? | I've been looking online and at my registry and I think not, but it would be nice if we could get a definitive answer on here.
Just the run time, as in for re-use on the client side.
I see it is possible for VC10, http://blogs.msdn.com/b/astebner/archive/2010/05/05/10008146.aspx, but prior to that we need to call the M... | It is still possible to do a private install of the Dll's into the application's folder. I recently installed 3 different version of the VC9 runtime when I was setting up my Visual Studio Express environments. All show up in Control Panel and appear to be readily removable.
For that reason I believe the current best pr... |
7,487,409 | 7,487,440 | Are global structs allocated on the stack or on the heap? | I am writing in an environment where I am not allowed to allocate new memory after program startup, nor am I allowed to make operating system calls. In tracking down a page fault error (likely caused by inadvertently violating one of the above) the question occurs to me (since this bit me in the butt with std strings)... | It's implementation-defined (the C++ standard doesn't really talk about stack and heap).
Typically, objects with static storage duration (such as globals) will end up in a special segment of address space that is neither stack nor heap. But the specifics vary from platform to platform.
|
7,487,502 | 7,488,252 | Equation parser efficiency | I sunk about a month of full time into a native C++ equation parser. It works, except it is slow (between 30-100 times slower than a hard-coded equation). What can I change to make it faster?
I read everything I could find on efficient code. In broad strokes:
The parser converts a string equation expression into a ... | It's hard to tell from your description if the slowness includes parsing, or it is just the interpretation time.
The parser, if you write it as recursive-descent (LL1) should be I/O bound. In other words, the reading of characters by the parser, and construction of your parse tree, should take a lot less time than it t... |
7,487,614 | 7,487,639 | what is the meaning of the following expression in c++ | What is the meaning of the following expression in c++?
(variable1 | (variable2 << 8))
What is the meaning of it? And what does it represent?
| It concatenates the two variables.
Suppose you have two chars, a and b. a|b<<8 shifts the b 8 bits to the left, | sets every bit that is in a or b.
So in this example the result would be "ab".
'a' is 97, 'b' is 98, so bitwise the following happens:
a: 01100001
b: 01100010
b<<8: 0110001000000000
a|b<... |
7,487,771 | 7,487,824 | member function pointer problem | Works:
static void WINAPI ServiceStart(DWORD argc, LPTSTR* argv);
int main() {
SERVICE_TABLE_ENTRY DispatchTable[] = {
{"MyService", ServiceStart},
{NULL, NULL}
};
}
Doesn't work:
error C2440: 'initializing' : cannot convert from 'void (__stdcall Service::* )(DWORD,LPTSTR *)' to 'LPSERVICE_MAIN_FUN... | You must use & in that context to obtain a correct pointer.
|
7,488,011 | 7,490,574 | Windows Mobile C++ Tray Icon | I'm trying to place my application that is mainly running in the background in a 'tray-like' area on the Windows Mobile 6.5.
I do it the obvious way by with Shell_NotifyIcon
BOOL ShowTrayIcon(HWND hWnd, HINSTANCE hIns, BOOL bShowIcon)
{
BOOL bRet = FALSE;
g_structNotifyIconData.cbSize = sizeof(NOTIFYICONDATA);
g_struc... | Indeed, Shell_NotifyIcon doesn't support adding the icon in the Today screen. This is even one of the first things mentioned in the function documentation:
This function sends a message to the system to add, modify, or delete an application-specific icon from the taskbar status area. It does not affect icons appearing ... |
7,488,039 | 7,488,076 | expression must have a constant value error in c++ |
Possible Duplicate:
Is there a way to initialize an array with non-constant variables? (C++)
I have the following code:
vector<vector<vec2>> vinciP;
int myLines = -1;
myLines = drawPolyLineFile("vinci.dat", vinciP);
if (myLines > -1)
{
cout << "\n\nSUCCESS";
vec2 vPoints[myLines];
... | vec2 vPoints[myLines];
Since myLines is not a const expression ((which means, it is not known at compile-time), so the above code declares a variable length array which is not allowed in C++. Only C99 has this feature. Your compiler might have this as an extension (but that is not Standard C++).
The solution to such c... |
7,488,056 | 7,495,413 | a problem with cl.exe and ml.exe | I used cl command to compile a cpp file:
cl test.cpp //the generated test.exe can work well
then I used another way:
cl /Fa /c test.cpp //generate a test.asm assembly file
ml test.asm // there failed!!!
why? How to solve it?
source code:
//:test.cpp
#include<iostream>
using namespace std;
int main()
{
... | The compiler produces an invalid assembly listing when exception handling code is produced. There's a bug open on Microsoft Connect: http://connect.microsoft.com/VisualStudio/feedback/details/556051/cl-facs-generates-bad-masm-for-c-exception-handlers
In a response to the bug, there's a half-hearted "we will consider f... |
7,488,086 | 7,488,173 | Efective search in set with non-key type | I have a similar data structure like this:
struct Data { std::string id; Blob data; };
Now I can use a std::map to store the structure and search by ID, but I searching for a way to achieve the same thing with a std::set (since I don't really need to separate the ID and the structure).
std::set::find of course takes t... | Unless the overhead is demonstrably unacceptable I'd go for std::map<std::string, Data *>, or possibly std::map<std::string, boost::shared_ptr<Data> >, assuming you don't have access to a compiler that provides shared_ptr natively.
|
7,488,251 | 7,489,220 | Using C++ to make a generic type - a template with shared implementation | As an example, consider a simple data structure like a linked list. In C, it might look like:
struct Node
{
struct Node *next;
void *data;
};
void *getLastItem(struct Node*);
...
I'd like to have the same struct and functions, but with better type checking by declaring the type of the data field, which will ... | As the other answers and comments said, use std::forward_list, or another existing library. If you refuse, this is more like I would do:
#include <stdio.h>
struct NodeImpl
{
NodeImpl *next;
void *data;
public:
// we have pointers, so fulfill the rule of three
NodeImpl() : next(NULL), data(NULL) {}... |
7,488,363 | 7,488,400 | Check precision to nth decimal place? | I have to calculate the values of a hot plate and have it accurate only to the first decimal place. I am stumped on trying to figure out how to check all the array values if they changed. I found out that 724 runs made no change after that to the 4th decimal (how many were being printed).
Is there a way to compare doub... |
Is there a way to compare doubles variables only up to the n-th decimal place?
Yes there is, check whether the absolute value of the difference between them is less than 10^-n.
|
7,488,642 | 7,488,792 | Questions about address spaces in C++ | Please read the following C++ code and the results. According to some wiki pages, static, automatic and dynamically-allocated variables are allocated in different address spaces, namely, data segment, stack and heap. However, it seems to me that the address of static and dynamic variables are at about the same place. W... | Only the OS can tell you which sections are in which parts of the address space. If you're using Linux, From within the program, output the contents of /proc/self/maps:
I've added
std::ifstream maps("/proc/self/maps");
std::cout << maps.rdbuf();
at the end of your program, and it prints:
8
0x6021c0
0x7fffe07f60bc
0x60... |
7,488,896 | 7,489,040 | Discrepencies between std::lower_bound and std::set::lower_bound | The C++ draft says about std::lower_bound:
§ 25.4.3.1 lower_bound [lower.bound]
template<class ForwardIterator, class T>
ForwardIterator lower_bound(ForwardIterator first,
ForwardIterator last,
const T& value);
template<class ForwardIterator, class T, clas... | A std::set container is ordered according to a comparison object that is given at construction time. When std::lower_bound is called, there is no way to check that it was passed a matching comparison object, so the implementation can't know whether to use the standard algorithm or one specialized to sets, as the latter... |
7,489,024 | 7,491,274 | C++ list of bits as numbers | I wish to have a list of bits where I can perform maths operations on a section of the list, for example.
value: 864
as bits, pos: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
as bits, value: 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0
If I take bits 1 to 4 and 6 to 9 I get 0, 1, 1, 0, 1, 0, 0, 0 (104). Then if I add 3 it becomes 0... | The possible fast way didn't work and would be verry limited.
unsigned int n = 8;
unsigned short *p1, *p2;
p1 = reinterpret_cast<unsigned short*>(&n);
p2 = reinterpret_cast<unsigned short*>((&n)+1);
std::cout<<*p1<<", "<<*p2<<std::endl;
Here is the full solution, thanks for the info that allowed me to complete this. I... |
7,489,067 | 7,489,221 | Implicit upcasting question | I find when writing functions (that use function overloading) that accept either a main class or subclass argument, that often implicit upcasting will occur (the subclass is upcasted as the main class and the main class function called). I don't want this implicit upcasting to occur as it means subtle bugs sneak in and... | class Base
{
};
class Derived1:public Base
{
};
class Derived2:private Base
{
};
void doSomething(Base *ptr)
{
}
int main()
{
Derived1 *ptr1 = new Derived1;
Derived2 *ptr2 = new Derived2;
doSomething(ptr1); //works fine
doSomething(ptr2); //Gives error
return 0;
};
Upcasting:
A Base class ... |
7,489,069 | 7,489,162 | What's the difference between cout<<cout and cout<<&cout in c++? | This might be a beginner question and understanding how cout works is probably key here. If somebody could link to a good explanation, it would be great.
cout<<cout and cout<<&cout print hex values separated by 4 on a linux x86 machine.
| cout << cout is equivalent to cout << cout.operator void *(). This is the idiom used before C++11 to determine if an iostream is in a failure state, and is implemented in std::ios_base; it usually returns the address of static_cast<std::ios_base *>(&cout).
cout << &cout prints out the address of cout.
Since std::ios_b... |
7,489,175 | 7,489,211 | Are Win32 windows thread safe? | I'd like to create a window on one thread, and then have that HWND migrate to one of any number of threads on which it will execute. My program will have multiple such windows. Is this possible or was the Win32 API not designed for this?
| No, this is not possible. The thread that a window uses for its message loop (what you refer to as "executing on") is defined at the time the window is created. You can create multiple threads and start message loops from them (and thus create windows on them), but this is generally regarded as dangerous.
|
7,489,255 | 7,492,107 | Annotations for NULL Dereference in Prefast and Compiling on GCC | I have the following example code and would like to know what kind of annotations I can use to avoid them.
int Function(classA* pInput) {
if (pInput == NULL) {
classA::Create(pInput);
}
return pInput->value;
}
The problem is that since Prefast evaluates only the function it doesn't know that Create ini... | MSalter’s answer sounds very much like the correct technical answer. Happily I don't know SAL so I can't say for sure, but it looks like the technical level solution.
However, I would just recommend that you rewrite your current code …
int Function(classA* pInput) {
if (pInput == NULL) {
classA::Create(pInput)... |
7,489,282 | 7,489,323 | C++ problem in declaring a struct | I am unable to see what is wrong in the following (very contrived) code. It might be the way I have declared a size 2 vector inside the mystruct. But isn't that how we declare a vector of size 2 whose contents we have yet to initialize?
struct mystruct
{
int a;
int b;
vector<double> c(2); };
int main(int ... | You cannot initialize mystruct::c in the class definition, this has to be done in the constructor.
struct mystruct {
mystruct() : c(2) { }
vector<double> c;
};
|
7,489,398 | 7,489,482 | How to find which elements are in the bag, using Knapsack Algorithm [and not only the bag's value]? | Here I have code which calculates the optimal value using the knapsack algorithm (bin packing NP-hard problem):
int Knapsack::knapsack(std::vector<Item>& items, int W)
{
size_t n = items.size();
std::vector<std::vector<int> > dp(W + 1, std::vector<int>(n + 1, 0));
for (size_t j = 1; j <= n; j++)
{
... | Getting the elements you packed from the matrix can be done using the data from the matrix without storing any additional data.
Pseudo code:
line <- W
i <- n
while (i > 0):
if dp[line][i] - dp[line - weight(i)][i-1] == value(i):
// the element 'i' is in the knapsack
i <- i-1 // only in 0-1 knapsack
... |
7,489,571 | 7,491,787 | OpenGL, How to create a "bumpy Polygon"? | I am unsure of how to describe what I'm after, so I drew a picture to help:
My question, is it possible within OpenGL to create the illusion of those pixel looking bumps on a single polygon, without having to resort to using many polygons? And if it is, what's the method?
| I think what your looking for is actually Parallax mapping (Or Parallax Occlusion mapping).
Demos:
http://www.youtube.com/watch?v=01owTezYC-w
http://www.youtube.com/watch?v=gcAsJdo7dME&NR=1
http://www.youtube.com/watch?v=njKdLvmBl88
Parralax mapping basically works by using the height map to alter the texture UV coordi... |
7,489,787 | 7,490,056 | Creating a unknown data type array into a structure? | I have a structure that I used to populate Class Structures with values:
MyType structMy[] =
{
{ START, INTEGER_TYPE, 3, (void *)&classStart->statusStart.set },
{ STABLE, CHAR_TYPE, 5, (void *)&classtStable->statusStable.set },
{ STOP, DOUBLE_TYPE, 1, (void *)&classStop->statusStop.set }
}
But for... | The compiler wants pointers there, so try declaring the data elsewhere:
int is[] = {0, 1, 2};
char cs[] = {'A', 'B', 'C', 'D', 'E'};
double ds[] = {2.4};
MyType structMy[] =
{
{START, INTEGER_TYPE, 3, (void*)is },
{STABLE, CHAR_TYPE, 5, (void*)cs },
{STOP, DOUBLE_TYPE, 1, (void*)ds }
}
|
7,490,095 | 7,490,267 | Getting the size of the callstack | Is there a way to get the size of the callstack (in bytes) in C++?
Or at least the bottom address of it (and then I can subtract it from the ESP register?
| You can try using VirtualQuery twice.
The first time you can use the address of any value on the stack to get the base address and size (in bytes) of the committed stack space.
Subtract the size from the base address and call VirtualQuery again. This way you get the space reserved for the stack.
Adding the two sizes y... |
7,490,219 | 7,490,287 | C++ Class: Object that creates Thread + pointer to the function = Access violation | I am very surprised by the strange exception, that I got.
class Threads {
public:
Threads() {}
~Threads() {}
void StartThread(int (*p)()); //pointer to a function
private:
HANDLE hThread;
DWORD dwThreadID;
};
Method StartThread should receive pointer to my... | It looks like you are actually calling the function on this line...
(LPTHREAD_START_ROUTINE)(*p)()
...and it returns an int that you're casting. That just can't work. How about:
(LPTHREAD_START_ROUTINE)p
...instead?
|
7,490,290 | 7,490,455 | c++ How Can I Achieve This Class Structure? | I'm racking my brain trying to find out how to write cross platform classes while avoiding the cost of virtual functions and any kind of ugliness in the platform specific versions of classes. Here is what I have tried.
PlatformIndependantClass.hpp
class PlatformIndependantClass {
public:
PlatformIndependant... | I think what you are trying to accomplish can be accomplished much easier...
Object.h:
#include <normal includes>
#if WINDOWS
#include <windows includes>
#endif
#if LINUX
#include <linux includes>
#endif
class Object
{
private:
#if WINDOWS
//Windows Specific Fields...
#endif
#if LINUX
//Linux Specific Fields...
#e... |
7,490,312 | 7,490,392 | Accessing a method of a member object in C++ | I am trying to access a method of an object (myEOS.calc(...)) from a method of an object (myPlanet) of another class containing an instance of the first class (static EOS myEOS):
// class in class
class EOS {
public:
static float Y;
float calc(float);
};
float EOS::calc(float x){
return x; ... | class Planet {
public:
static EOS myEOS; // want only one instance; cf. below
This code says "Compiler: Somewhere later will be a global EOS myEOS for this class. And the compiler says "ok", and does it's thing, waiting for you to tell it where the global EOS myEOS is.
Then the linker comes along to ... |
7,490,323 | 7,490,690 | What is the name for this in Design Pattern? | class MyType
{
public:
A ( unsigned _a ) : a (_a-1)
{
}
operator unsigned& ()
{
return a;
}
operator const unsigned () const
{
return a;
}
unsigned a;
};
In the above example, I created a class MyType which is comprised of just one unsigned integer.
is there... | Don't know what the design pattern name is, but there is a use for it.
It can be useful if you have a set of classes that all implement that same member functions, and you want to treat them all in the same way. Some of these classes contain simple types like int and unsigned, while others contain more complicated clas... |
7,490,329 | 7,492,327 | Tensor Product Algorithm Optimization | double data[12] = {1, z, z^2, z^3, 1, y, y^2, y^3, 1, x, x^2, x^3};
double result[64] = {1, z, z^2, z^3, y, zy, (z^2)y, (z^3)y, y^2, z(y^2), (z^2)(y^2), (z^3)(y^2), y^3, z(y^3), (z^2)(y^3), (z^3)(y^3), x, zx, (z^2)x, (z^3)x, yx, zyx, (z^2)yx, (z^3)yx, (y^2)x, z(y^2)x, (z^2)(y^2)x, (z^3)(y^2)x, (y^3)x, z(y^3)x, (z^2)(y^... | A good compiler will autovectorize this I guess none of my compilers are good:
void tensor(const double *restrict data,
int dimensions,
double *restrict result) {
result[0] = 1.0;
for (int i = 0; i < dimensions; i++) {
for (int j = (1 << (i * 2)) - 1; j > -1; j--) {
double alpha = ... |
7,490,603 | 7,490,720 | C++ polymorphism and type casting | I am relatively new to C++ and I have been working on a basic 3D rendering engine using OpenGL.I have the following issue:
I have a class called GeomEntity which is the base class for all geometry primitives.I have another class called DefaultMaterial which is the base class for all materials(consists of different typ... | In C++ you can do this using dynamic_cast, that is I believe closest equivalent of that C# feature:
AnimatedMaterial* panim = dynamic_cast<AnimatedMaterial*>(sphere.material);
if(panim)
panim->interpolateColor(timerSinceStart);
|
7,490,652 | 7,490,688 | How to get back the two components of a long integer | DWORDLONG index = ((((DWORDLONG) i.nFileIndexHigh) << 32) | i.nFileIndexLow);
Given index, I want to find out what the components of i.fileindexhigh and i.fileindexlow are. Is it possible? A general idea would be helpful.
| Yes, its possible, you just need to do the inverse operation of what you posted: instead of << and |, >> and &,
nFileIndexLow = index & 0x00000000FFFFFFFF;
nFileIndexHigh = index >> 32;
Consider researching on bitwise operations, or at least put your calculator in hexadecimal/binary mode and play with masks and shifts... |
7,490,749 | 7,490,771 | Unusual typedef use in C++ | I came across a new use of the keyword typedef in C++.
What does this typedef statement mean ?
int typedef foo;
| It's the same as
typedef int foo;
i.e. it defines foo to be the type int. While the grammar allows to swap typedef and int in this case, you usually would not do this because it impairs readability.
|
7,490,869 | 7,490,905 | Using boost to handle COM variants | I'm working with a c++ project that has a lot of COM functions. The majority of the inputs and outputs are VARIANTs. Is there an easy way to serialize/deserialize these into long, string, etc using Boost?
| Boost has absolutely nothing with regards to Microsoft's COM technology. The closest thing to COM's variant in Boost would be boost::any. You can write COM's variant_t to boost::any converter, then you can serialize, cast etc.
|
7,490,972 | 7,491,064 | How should I handle invalid values passed to a setter method? | If I have a simple class such as...
class Rectangle
{
private:
double length;
double width;
public:
void setLength(double l) { length = l; }
void setWidth(double w) { width = l; }
void getLength() { return length; }
void getWidth() { return width; }
void getArea() { return length * width... | You have a couple choices. In the real world, it will depend on who is using your class (other internal code or public API) as well as conventions agreed upon by your company.
You can:
Throw Exception
Pros:
Simple to implement
Keeps error handling code clean
Allows passing of error messages and other variables
Stand... |
7,491,654 | 7,491,696 | C++ string array slice | How would I split an inputted string such as "one two three four five" into an array.
currentyly I have this:
const int SIZE = 5;
string digit[SIZE];
cout << "Enter the five here:";
for(int i = 0; i < SIZE; i++)
{
cout << i+1 << ")";
getline(cin, digit[i]);
}
but as it stands, the user has to hit enter every ... | If you want to read words separated by whitespace, you can take advantage of the fact that extracting a string from an input stream will stop at whitespace:
for(int i = 0; i < SIZE; i++)
{
cout << i+1 << ")";
cin >> digit[i];
}
|
7,491,877 | 7,491,904 | c++: Catch runtime_error | I am learning c++ at home and I am using the rapidxml lib.
I am using the utils provided with it to open files:
rapidxml::file<char> myfile (&filechars[0]);
I noticed that if filechars is wrong the rapidxml::file throw a runtime_error:
// Open stream
basic_ifstream<Ch> stream(filename, ios::binary);
if (!stream)
thr... | You need to add an exception declaration next to the catch statement. The type thrown is std::runtime_error.
try
{
rapidxml::file<char> GpxFile (pcharfilename);
}
catch (const runtime_error& error)
{
// your error handling code here
}
If you need to catch multiple, different kinds of exceptions, then you can tack... |
7,492,026 | 7,492,262 | Can C++ class instances on the stack be captured by Objective-C blocks? | I'm seeing some strange behavior when trying to capture an instance of a C++ class on the stack in an Objective-C block. Consider the following code:
#import <Foundation/Foundation.h>
#include <stdio.h>
struct Test
{
Test() : flag(0) { printf("%p default constructor\n", this); }
Test(const Test& other) : flag(0) ... | I'd say its a bug in GCC.
When I try it with GCC, I get:
0x7fff5fbff5d0 default constructor
0x7fff5fbff5c0 copy constructor
about to call blk
0x7fff5fbff570 copy constructor
0x7fff5fbff570 destructor
flag=1 (test=0x7fff5fbff570)
0x7fff5fbff5c0 destructor
0x7fff5fbff5d0 destructor
But using LLVM 2.0:
0x7fff5fbff610 d... |
7,492,120 | 7,492,153 | Problem when executing a function | I'm trying to run a simple C++ program (as I'm JUST starting to learn C++) and tried this example code off a website as a program that adds two numbers together. When I execute the program, I never get errors, but c always returns as 0. Help??
#include <iostream.h>
int Add (int x, int y)
{
std::cout << "In Add(),... | Since Add returns 0, c will always be 0. You need to, you know, actually add the numbers you pass into Add and return that from the function.
|
7,492,448 | 7,492,524 | Selective suppression of output to the terminal C++. | I have a bunch of .cpp files which together process similar data files but of various sizes. For the larger data files I want to do some timing studies on the functions inside the .cpp files.
I would like to suppress the output the results for these big data sets, and only print the timing results. For smaller data se... | Your intuition is correct -- use the argc and argv values passed into your main function -- but they are not global variables. You need to make your information global somehow: I'd recommend parsing the arguments once, and keeping a set of global flags that can easily be queried.
For example:
// In a common header fil... |
7,492,529 | 7,492,837 | How to simulate a mouse movement | How can I simulate a mouse event causing the pointer to move 500 pixels to the left, then click using C++. How would I do something like this?
| Here's some modified Win32 code I had lying around:
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0500
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
#define X 123
#define Y 123
#define SCREEN_WIDTH 1024
#define SCREEN_HEIGHT 800
void Mouse... |
7,492,594 | 7,492,701 | Creating a Parent/Child relationship with objects | Okay, so I am having some troubles in creating a Parent/Child relationship. The easiest way I can explain this is having an object, with a reference (or pointer) to another object of the same type, and then an array of children references (or pointers) to more objects. The object should have functions like .getChildren... | This
printf("B.parent.pos.z %d should equal 0\n", B.parent->getPos()
raises your error because of this
protected:
Base* parent;
You're trying to reference B.parent from outside of the class implementation. Because parent is declared protected it isn't available there. In your declaration of Base, you should add a... |
7,492,842 | 7,492,865 | Convert One Dimensional Arrary to Two Dimensional in C++ | I have a 49 space one dimensional array declared as int boardArray [49]; and I also have a two dimensional 7x7 array declared as int boardArrayTwo [7][7]' I am trying to use nested for loops to throw the one dimensional array into the two dimensional array here is the code I am using to test it.
for (int i = 0; i > 50;... | for (int x = 0; x >= 7; ++x)
{
for (int k = 0; k >= 7; ++k){
for (int n = 0; n >= 49; ++n)
{
this is wrong. x and k should be < 7 (and the third cycle shouldn't be used) :
for (int x = 0; x < 7; ++x)
{
for (int k = 0; k < 7; ++k){
boardArrayTwo[x][k] = boardArray[7*x + k];
EDIT:
like @Fa... |
7,492,920 | 7,493,022 | Tools and ways to understand object-oriented code | In my work / study, I have had to look at, understand, and modify non-trivial code written in an object-oriented style, with little documentation. For my case these are architectural simulators in C++.
I would like to know from more experienced people about what are some of the more efficient ways to look at and under... | This Wikipedia page gives a decent list of tools that you may find helpful. I'm fond of cpplint, myself.
|
7,493,082 | 7,493,100 | Native Win32 window in WPF Control | I am developing an application that needs to a host native Win32 window and somehow i have no clues how to do that.
I need to create a WPF dialog window that could display native Win32 control on it. This dialog window will have WPF controls on it as well, so i am looking for some sort of Grid that i could take HWND of... | you can start by following the instructions/steps here: Hosting Win32 Content in WPF
from the article introduction:
A Walkthrough of Win32 Inside Windows Presentation Framework (HwndHost)
To reuse Win32 content inside WPF applications, use HwndHost, which is
a control that makes HWNDs look like WPF content. Like Hwn... |
7,493,109 | 7,493,417 | What happens if I assign a number with a decimal point to an integer rather than to a float? | A friend of mine asked me this question earlier, but I found myself clutching at straws trying to give him an adequate explanation.
| If you assign a value of any numeric type (integer, floating-point) to an object of another numeric type, the value is implicitly converted to the target type. The same thing happens in an initialization or when passing an argument to a function.
The rules for how the conversion is done vary with what kind of types yo... |
7,493,192 | 7,519,893 | "?" help button triggers WM_HELP _and_ WM_LBUTTONUP | I have a Windows application that registers one CALLBACK procedure that handles WM_HELP messages for the dialog, and one CALLBACK procedure that handles WM_LBUTTONUP messages for a custom button.
Now, when the user clicks the "?" button, then clicks the custom button, the help opens up as expected (on mouse down), BUT ... | Okay, I fixed it by creating the custom button (static control) with the SS_NOTIFY style, then handling the STN_CLICKED notification in the WM_COMMAND message. (SS_NOTIFY causes WM_COMMAND to trigger in the parent when it is clicked.) This does not trigger when using the "?" button. Thanks!
|
7,493,443 | 7,493,454 | Dynamic Array Output Problem | I am working on a homework assignment where I had to convert all of the static arrays in a program into dynamic arrays using pointers. I am pretty sure I am understanding the concept, I have made the changes and my program runs. The problem is with my output results. I suspect I am inputting the data incorrectly from t... | You are creating an array of one char and one int with this code:
allCandidates = new char[1];
votes = new int[1];
I believe you meant:
allCandidates = new char[numCandidates];
votes = new int[numCandidates];
which creates dynamic arrays of size numCandidates.
Also, as you are inputting names of candidates you probab... |
7,493,484 | 7,493,864 | Video Processing OpenCV? | I am trying to pass in a HSV frame from a video to the function, but the function does not seem to do anything to it. What am I doing wrong? The function is supposed to go through each pixel, and depending on its hue range supposed to make it black or white, leaving me with a binary image. Instead it doesn't seem to af... | Doing an operation like thresholding pixel-by-pixel is usually the wrong way to go about achieving this in OpenCV - there are functions that work on whole image arrays that are simpler and are already optimized for speed.
In this case try first splitting the image to separate out the H/S/V channels, then threshold on t... |
7,493,578 | 7,493,594 | C++ returning stringstream.str() | I have a static method that should return the next available id. Several static members in other classes call this function, so each gets a different id assigned. However, when I am printing the assigned values I dont get "id0", "id1" but just a symbol like "*". I'm using this code:
int A::i = 0; //static member
... | Look at
const char* C::id = A::id().c_str();
You are creating a new id string, then you take a pointer to its data (as a c-string), and inmediately after that the temporary string to which contents you are pointing gets destroyed. Simple answer: either stick to std::string or to plain int ids.
|
7,493,695 | 7,493,728 | Program always producing same value? | the point of my program is to write the numbers 1 - 1,000,000 to a text file, generate a random number between 1 and 1,000,000, search for that line in the text file, take the value, and square it (this is just an exercise for me, it has no practical application). The problem is that whenever I run it, the value remain... | You never enter the while loop as you are using:
while(!(randomLine > min) && !(randomLine < max))
while immediately evaluates to false. You should use:
while(randomLine < min || randomLine > max)
Also, why do all your variables have different types? This could lead to unintended errors. You should change them to hav... |
7,493,887 | 7,493,934 | Strange assignment problem - C++ | Having a strange problem making a new string class and assigning an array of char* to it in the GCC compiler. Source code:
#include "../Include/StdString.h"
StdString::StdString()
{
//ctor
internstr = std::string();
}
char* StdString::operator=(StdString other) {
return other.cstr();
}
StdString StdStrin... | std::string can do its conversion because it defines a conversion constructor. Something like this.
class std::string {
// ...
std::string(const char *);
};
NOTE: the actual std::string is more complicated.
With the assignment operator you should be able to do
StdString str;
str = "hello";
but not
StdString str = ... |
7,493,932 | 7,493,964 | What causes C++ compiler error: must have argument of class or enumerated type? | Function declaration:
template <typename T>
Point<T>* operator +(Point<T> const * const point, Vector<T> const * const vector);
It's been a while since I've used C++ so maybe I'm doing something really stupid. Let me know.
Also, no, I am not using namespace std.
| What you're doing wrong here on the language level is overloading operators for pointers. At least one argument of an overloaded operator must be of a user-defined type, or a reference to one.
But you're also doing this wrong on another level. You're returning a pointer, which means you will probably need to allocate s... |
7,494,004 | 7,494,033 | C++ program to accept int and print * | I am self studying C++ and I was thinking of a simple program to get comfortable with the syntax.
int main(){
int num;
cout << "Enter a positive number:";
cin >> num;
printStar(num);
}
void printStar(int num){
.............................
}
Such that the function printStar accepts an integer and prints * for instanc... | Since this is for your own learning, i am not giving a solution, a hint is using For or While loop. If it works, its good, otherwise post your code and problem.
A link to get you started
|
7,494,109 | 7,494,110 | Why would you ever want to create a method called *foo() instead of just foo()? | I see this in other people's code sometimes:
public void *foo() {
...
}
public void bar() {
...
}
but I never understood what the meaning of the * was for, and if there is any difference between public void *foo() and public void foo()?
***This is C++ code here!
| public void *foo() is a public function that returns a void pointer (which can be anything essentially). More documentation on pointers can be found here: http://www.cplusplus.com/doc/tutorial/pointers/ (specifically the void pointer section).
public void *foo() and public void* foo() are the same and the position of *... |
7,494,130 | 7,494,143 | C++ floating point comparison | Suppose you have have a rectangle, bottom-left point 0,0 and upper-right point is 100,100.
Now two line intersects the rectangle. I have to find out the coordinate of the intersection point. I have done that. Now the problem is I can't tell whether it is inside the rectangle or not. I used double comparison. But I thi... | Your math looks like it's right. By the way, If a line intersects something, it is always inside that something.
|
7,494,260 | 7,494,622 | float numerical error. How does c++ know 0.99999982 is 1? | I normalized a vector and length of it should be 1. But the result of length method is 0.99999982
I don't know it's right or wrong. But if I print it out, the result is 1. Not 0.99999982( printed by cout )
But how std::cout knows it's 1? [This is my first question]
And another question is why the result of comparing fu... | The IEEE standard requires that the result of addition, subtraction, multiplication and division be exactly rounded. The result must then be rounded to the nearest floating-point number. Floating point error is accumulated in the many operators it takes to normalize a vector.
Like the other poster said FLT_EPSILON is t... |
7,494,399 | 7,494,460 | Would C++ exception stops function from being inlined? | Suppose I have a very simple function that I expect the compiler to inline it. But I may need to throw exception on seeing some invalid input, would that stop the compiler from inlining the function?
| A compiler can refuse to inline for any reason. gcc lists reasons why it might not inline a function, but exception throwing is not among them. Also, the option -Winline will cause the compiler to issue a warning if it can't inline a function that you marked as inline. You can try that and see if you are doing anyth... |
7,494,546 | 10,710,644 | Is YDL.net's Eclipse CUDA plugin ready for CUDA 4.0 | I've just installed the CUDA 4.0 Toolkit, and also the CUDA plugin for Eclipse Helios on top of an AMD64 Ubuntu 10.10 machine. I have been able to compile successfully all of the NVIDIA GPU Computing SDK examples, so my build system looks fine. But I cannot make the Hello World CUDA template of the plugin to compile on... | Please note that there is now Nsight Eclipse Edition that is a part of CUDA Toolkit. It supports all new CUDA Toolkit 5.0 features.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.