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,549,826 | 7,549,873 | How to make classes in NACHOS (C++) | I am trying to implement a player class, so I created two files in my threads folder,
player.cc and player.h
player.h goes like this :
#ifndef PLAYER_H
#define PLAYER_H
#include "utility.h"
class Player()
{
public:
//getPlayerID();
};
#endif
then player.cc goes like
#include "player.h"
class Player()
{
strin... | Let's go through line-by-line:
#ifndef PLAYER_H
#define PLAYER_H
#include "utility.h"
So far so good, you might check if your compiler supports #pragma once, but the macro will work perfectly fine.
class Player()
() aren't allowed in a class name, take them off
{
public:
//getPlayerID();
};
#endif
The rest of ... |
7,549,874 | 7,550,036 | How do I fix an "ambiguous" function call? | I'm working on a C++ program for class, and my compiler is complaining about an "ambiguous" function call. I suspect that this is because there are several functions defined with different parameters.
How can I tell the compiler which one I want? Aside from a case-specific fix, is there a general rule, such as typecas... | What's happened is that you've included <cstdlib> (indirectly, since it's included by iostream) along with using namespace std;. This header declares two functions in std with the name abs(). One takes and returns long long, and the other returns long. Plus, there's the one in the global namespace (that returns int) th... |
7,549,878 | 8,366,083 | Link error while building a C++ Unit test project in VS.NET 2010 | I am trying to build a very simple C++ unit test project. The setup is just so happened to be exactly the same as what this blog described. I built a static library TestLib.lib and a C++ unit test project called TestProject. Both projects are using platform toolset v100.
The Testlib contains only one class.
BaseClas... | Does the error only show up when compiling the Debug configuration? If so, it may be related to your C++ run-time library linkage:
http://social.msdn.microsoft.com/Forums/eu/vclanguage/thread/e5a78770-4d99-40b7-951f-e4466d2744a8
|
7,549,991 | 7,550,093 | Questions about glDrawRangeElements() | I am trying to render some old level data using the glDrawRangeElements() command. My vertices are set up correctly, my indices are set up correctly, but I can't seem to get it to render. I finally checked online and came across the example found here: http://www.songho.ca/opengl/gl_vertexarray.html
From the example, I... | First, let's talk about glDrawElements, because the Range version is just a modification of that. The count is the number of indices to pull from the source index array to render. Each index pulled maps to a vertex. So if your count is "29", then you are trying to render 29 vertices. This will only render 27 vertices i... |
7,550,102 | 7,550,195 | Given an array of ints, what is the most efficient way to split the array down the middle into two arrays of shorts? | It struck me there must be a clever way to do this. This isn't for homework, or work or anything. I was just noodling around with a file format that has data interleaved.
So, in generic C/C++, (or whatever) given some array
int x[] = ...
is there a clever way of splitting it into two short arrays
short sa1[], sa2[]... | There's a lot of ways to do this:
Assumptions:
short is 16 bits.
int is 32 bits.
Method 1: (A simple loop)
for (int i = 0; i < size; i++){
int tmp = x[i];
sa1[i] = (tmp ) & 0xffff;
sa2[i] = (tmp >> 16) & 0xffff;
}
Method 2: SSE2
for (int i = 0; i < size / 8; i++){
__m128i a0 = ((__m128i*)x)[2*i ... |
7,550,129 | 7,550,141 | What are the 'ref' and 'sealed' keywords in C++? | I've just seen some (presumably) C++ code which sports two "keywords" unknown to me (I'm assuming keywords but, since I have no context, they may be simple #define things).
They also don't seem to appear in the C++11 standard, at least the draft I have but, since that's a pretty late draft, I can't imagine them being j... | This is C++/CLI.
A ref class is a managed type.
sealed means that the class cannot be inherited
|
7,550,171 | 7,550,188 | Non virtual version of virtual class | Lets say we have the following two class definitions.
#include <iostream>
#include <array>
class A
{
public:
virtual void f() = 0;
};
class B : public A
{
public:
virtual void f() { std::cout << i << std::endl; }
int i;
};
Here sizeof(B) == 8, presumably 4 the virtual pointer and 4 for the int.
Now lets say we... |
Is there a way to create an object of type B without a virtual pointer if you know it is not going to be used?
No. Objects are what they are. A virtual object is virtual, always.
After all, you could do this:
A *a = &x[2];
a->f();
That is perfectly legitimate and legal code. And C++ has to allow it. The type B is vi... |
7,550,197 | 7,550,258 | How can I capture audio from a mic to send it over a socket? | I am using Windows 7 and developing a chat-like application with Visual Studio 2010. I am looking for an EASY way of capturing audio from a microphone (or rather, from the default recording device), collect the buffer from said input, and send it over a socket. I've seen DirectX solutions recommended, but from my resea... | If you're doing the sockets yourself try checking out:
http://www.techmind.org/wave/
http://www.bcbjournal.com/articles/vol2/9810/Low-level_wave_audio__part_3.htm
http://www.relisoft.com/freeware/recorder.html
I enjoyed all of them but the last one, but then again, you might find it far more helpful.
|
7,550,229 | 7,662,638 | Collision Detection Between Rectangles - Resulting Angles | Basically I have a bunch of rectangles floating around at 8 different angles (45 degrees, 90 degrees etc). I have collision detection going on between all of them, but one thing still doesn't work as it should. I don't know if I'm just not thinking or what, but I can't seem to get the resulting angles right. I've also ... | I think you mean something like this...
Each Rectangle has this functionality, testing against, say an array of other objects.
Obstacle* obstacle = new Obstacle;
Obstacle** obstacles = obstacle*[];
For(int i = 0; i <3; i++)
{
obstacles[0] = New Obstacle(x,y, etc...);
etc...
}
Or something similar... this is a little ... |
7,550,362 | 7,550,415 | In C++11, what is the point of a thread which "does not represent a thread of execution"? | Looking over the new threading stuff in C++11 to see how easily it maps to pthreads, I notice the curious section in the thread constructor area:
thread();
Effects: Constructs a thread object that does not represent a thread of execution.
Postcondition: get_id() == id()
Throws: Nothing.
In other words, the default co... |
Is there some other way that a "thread of execution" can be attached to that object, like thrd.start() or something similar?
// deferred start
std::thread thread;
// ...
// let's start now
thread = std::thread(functor, arg0, arg1);
std::thread is a MoveConstructible and MoveAssignable type. So that means that in c... |
7,550,878 | 7,550,929 | Variable Value Changes By Itself | I've been pretty confused while programming before, but this one takes the cake. Basically I set the value in one for loop, and in the following iteration it changes to the value of the next one.
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < numWords[i]; ++j) //numWords [0] = 9, numWords [1] = 7
{
s... | This is pretty simple. Your program has undefined behaviour (if my assumptions about is() are correct).
is(int, length) returns a std::string by value. You get a pointer to some internal structure in that string by using c_str(). This string is then destructed at the end of the full-expression. This destruction invalid... |
7,550,923 | 7,550,996 | C++ cannot create new key in registry | I really need your help. I tried everything but the result is always the same, nothing. Please advise.
And this is my code
#include <windows.h>
#include <iostream>
#include <windef.h>
using namespace std;
int main (void)
{
HKEY hKey;
LONG regOpenResult;
const char PATH[] = "C:\\Users\\les\\Documents\\vis... | Check the return status of each API call!!!! Use GetLastError () for each failure.
Knowing the error should lead you to resolve the problem.
Otherwise, you're flying completely blind...
Yes, PATH shouldn't be an 8-bit character string if you're calling a 16-bit Unicode API. But it's not necessarily the only problem.
... |
7,551,052 | 7,571,487 | Vector rotation problem | I'm working on a program with IK and have run into what I had at first thought was a trivial problem but have since had trouble solving it.
Background:
Everything is in 3d space.
I'm using 3d Vectors and Quaternions to represent transforms.
I have a limb which we will call V1.
I want to rotate it onto V2.
I was gett... | You are correct when you write in a comment that the axis should be computed in the local coordinate frame of the joint:
I'm wondering if this issue is occuring because I'm doing the calculations to get the axis and angle in the world space for the joint, but then applying it to the local space.
The rotation of the a... |
7,551,093 | 7,551,216 | Displaying Bar Chart (and other funky graphics) | Any suggestions on freely available libraries to display a bar chart and other "cool" graphics in Visual C++?
PS: Please don't say MFC. MFC-based libraries are fine!
| Although not a graphing library, Qt should work pretty nicely for drawing basic graphs, more advanced things can be done using Qwt. Plus you get the advantage of system portability.
|
7,551,206 | 7,551,700 | Inheriting from an instance of a template class | I have two classes as follows in a header file
template<size_t N>
class Parent{
protected:
char array[N];
size_t i;
public:
virtual void operator()(int i);
};
template<size_t N>
void Parent<N>::operator()(int i){
this->i = i;
}
class Child: public Parent<16>{
public:
virtual void opera... | Apart from the errors in your code, this is an example of hiding: Your derived class declares a function of the same name but with different signature as a base class. Thus the base function is hidden:
class A { virtual void foo(); };
class B : public A { virtual void foo(int); /* hides A::foo() ! */ };
Inheritance o... |
7,551,241 | 7,551,956 | How to pass two dimensions array to a function and how to call it | I've tried many time to pass the array to a function then do some calculation such as getting the total of the columns, the problem is I don't know how to call the result form the function, usually I get errors.
this is just one code I'm trying to solve it from yesterday :
#include <iostream>
using namespace std;
//pr... | int marks[row][col]
This means that marks has type int[2][3].
int get_total(int whatever[][2], int row);
You've however declared get_total to accept an int(*)[2]. int[2][3] can decay to int(*)[3] but that is not compatible with int(*)[2], hence why you can't pass marks to get_total. You can instead declare get_total ... |
7,551,325 | 7,551,381 | C++: Is it safe to move a jpeg around in memory using a std::string? | I have an external_jpeg_func() that takes jpeg data in a char array to do stuff with it. I am unable to modify this function. In order to provide it the char array, I do something like the following:
//what the funcs take as inputs
std::string my_get_jpeg();
void external_jpeg_func(const char* buf, unsigned int size);
... | My recommendation would be to use std::vector<char>, instead of std::string, in this case; the danger with std::string is that it provides a c_str() function and most developers assume that the contents of a std::string are NUL-terminated, even though std::string provides a size() function that can return a different v... |
7,551,667 | 7,551,729 | why the result is not in my expectation? | #include <iostream>
using namespace std;
typedef void (*pFun)(void);
class A
{
private:
int a;
int b;
virtual void outPrint()
{
cout << b << endl;
}
public:
A()
{
a = 3;
b = 4;
}
};
int main()
{
A obj;
cout << *((int*)(&obj)+1) << endl;
... | Seems that you assume that the address of the object obj can be interpreted as an address of a function of the type you defined.
It cannot.
I'm not entirely sure why would you have such an assumption to begin with. You're probably assuming things about the internal implementation of the dynamic dispatch. But do take a ... |
7,551,755 | 7,552,824 | how to store data , and add button in firefox / chrome javascript plugin | im beginner to java script / XUL development and c++ if needed .
i have 2 basic questions and i need some directions .
background : i like to build simple plugin that schedule by date actions to preform.
1. can i store data ( dates + ids ) so the plug in could read and write to it , what is the limitations ?
2. what ... | To perform automatic date operations, you need your own Date()function & these links wil help you:
https://developer.mozilla.org/en/CSS/Getting_Started/XUL_user_interfaces
https://wiki.mozilla.org/XUL:Specs:DateTimePickers
Regarding read & write to any files in XUL javaScript is pretty simple:
https://developer.mozilla... |
7,551,942 | 7,563,625 | Getting certificate chain to a private root | I'm trying to verify that the certificate from a signature chains back to a particular root certificate, which is not trusted by Windows (it's a private certificate for the app).
My current attempt to do this involves creating a chaining engine which only trusts the specific certificate I want as the root, so that no o... | I've found a half-baked workaround now; it's a little ugly but it does kinda work. I got the basic idea from Chromium's test suite; it involves installing a hook into Crypt32 such that when it tries to open the system stores to build the chain it gets my custom store instead, containing only my desired certificate.
Th... |
7,552,308 | 11,909,513 | RapidXML is throwing exception | ifstream fin("tree.xml");
if (fin.fail()) return 1;
fin.seekg(0, ios::end);
size_t length = fin.tellg();
fin.seekg(0, ios::beg);
char* buffer = new char[length + 1];
fin.read(buffer, length);
buffer[length] = '\0';
fin.close();
xml_document<> doc;
doc.parse<parse_full>(bu... | You may be able to nail down exactly what is causing this by looking at this link http://rapidxml.sourceforge.net/manual.html#classrapidxml_1_1parse__error
In particular (bold text is my emphasis)
class rapidxml::parse_error
Defined in rapidxml.hpp
Description
Parse error exception. This exception is thrown by the par... |
7,552,343 | 7,552,405 | How to access AfxGetMainWnd() from CWinThread? | I'm trying to create a worker thread in a class called ClientManager, but I can't get access to AfxGetMainWnd() from the new CWinThread, i.e:
UINT ClientManager::WorkerThreadProc( LPVOID param ){
ClientManager *pThis = reinterpret_cast<ClientManager*>(param);
return pThis -> DoThreadJob();
}
UINT ClientManager:... | The documentation says:
If AfxGetMainWnd is called from the application's primary thread, it returns the application's main window according to the above rules. If the function is called from a secondary thread in the application, the function returns the main window associated with the thread that made the call.
So ... |
7,552,443 | 7,553,785 | What's the numerically best way to calculate the average | what's the best way to calculate the average? With this question I want to know which algorithm for calculating the average is the best in a numerical sense. It should have the least rounding errors, should not be sensitive to over- or underflows and so on.
Thank you.
Additional information: incremental approaches pre... | You can have a look at http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.43.3535 (Nick Higham, "The accuracy of floating point summation", SIAM Journal of Scientific Computation, 1993).
If I remember it correctly, compensated summation (Kahan summation) is good if all numbers are positive, as least as good as sor... |
7,552,568 | 7,554,072 | Remove QLayoutItem from a Layout, but still use it later on? | Here is the environment first:
I have a self defined "Property Editor" which is a QGroupBox (derives from QWidget)
Currently I have a class let's call it "Holder", which has a reference to two of the Property Editors.
Now I have multiple "Holder" classes and one vertical QVBoxLayout (called Sidebar).
In this layout I w... | QLayout::takeAt() doesn't remove the widget of the QLayoutItem from its parent widget. The only reason it may seem to work the first time is probably because the other widgets were above (z-index wise) the first ones.
Rather than playing with the layout, you could
just hide/show your 2 PropertyEditor whenever the hol... |
7,552,707 | 7,724,379 | More comfortable way renaming a Class in Eclipse using CDT for C++? | I'm wondering if there's an easier way using CDT for this refactoring task. Not only a simple renaming, also a rename of header and source files, correcting all #include statements, rename member-attributes in other classes and so on.
Don't know if it's possible or if one has to fumble around in all project files, or ... | The Alt+Shift+R does everything except it doesn't change the filenames of .cpp and .h files.
Everything else is done by this operation.
|
7,552,896 | 7,554,821 | Most efficient way to clamp values in an OpenCv Mat | I have an OpenCv Mat that I'm going to use for per-pixel remapping, called remap, that has CV_32FC2 elements.
Some of these elements might be outside of the allowed range for the remap. So I need to clamp them between Point2f(0, 0) and Point2f(w, h). What is the shortest, or most efficient, way of accomplishing this wi... | Try splitting, using cvThreshold and then merging. You may also get away with using cvSetImageCOI to avoid the splitting. I'm not sure if thresholding code supports the COI.
You may want to profile both versions and compare their performance. I have a feeling it will do the same thing.
|
7,552,977 | 7,553,056 | Howto avoid copying when casting a vector<Derived*> to a vector<Base*> | Is there a way to avoid copying large vectors, when a function expects a vector with (pointer to) baseclass objects as input but I only have a vector of (pointers to) derived objects?
class Base {};
class Derived : public Base {};
void doStuff(vector<Base*> &vec)
{
//do stuff with vec objects
}
int main()
{
... | If you could use a vector<Derived*> as if it where a vector<Base*>, you could add a pointer to a class OtherDerived : public Base to that vector. This would be dangerous.
|
7,553,017 | 7,553,167 | Is accessing volatile local variables not accessed from outside the function observable behavior in C++? | In C++03 Standard observable behavior (1.9/6) includes reading and writing volatile data. Now I have this code:
int main()
{
const volatile int value = 0;
if( value ) {
}
return 0;
}
which formally initializes a volatile variable and then reads it. Visual C++ 10 emits machine code that makes room on th... | The thread's entire stack might be located on a protected memory page, with a handler that logs all reads and writes (and allows them to complete, of course).
However, I don't think MSVC really cares whether or how the memory access might be detected. It understands volatile to mean, among other things, "do not bother ... |
7,553,050 | 7,553,107 | COleDateTime alternative for linux | Good Day.
I have to make a C++ project Linux compatible. In the existing Project some old MFC functions were used. I am searching for a substitute for the COleDateTime wrapper. Does a alternative object exist for Linux or do I have to implement my own wrapper? (examples would be appreciated)
| Boost DateTime library: http://www.boost.org/doc/libs/1_47_0/doc/html/date_time.html
Using Boost, you can make many other things portable: file system, multithreading, interprocess communications, sockets etc.
More about Boost Datetime here: http://en.highscore.de/cpp/boost/ Chapter 10: Date and Time
|
7,553,100 | 7,723,091 | Linking error in MSVC 2008 | I have a file structure like this:
file1.h
extern const char *build_info[][3];
file1.cpp
#include "file1.h"
const char *build_info[][3] = {
{ "abc", "de", "feg" },
{ ... },
...
};
file2.cpp
// Use build_info
Now I am getting this erro under MSVC 2008 Express
file2.obj : error ... | Okay I found the problem, file1.cpp was actually file.c. Only I enclosed that in
extern C { .. }
it is working fine.
|
7,553,338 | 7,553,572 | Implementing thread-safe arrays | I want to implement a array-liked data structure allowing multiple threads to modify/insert items simultaneously. How can I obtain it in regard to performance? I implemented a wrapper class around std::vector and I used critical sections for synchronizing threads. Please have a look at my code below. Each time a thread... | The best way is to use some fast reader-writer lock. You perform shared locking for read-only access and exclusive locking for writable access - this way read-only access is performed simultaneously.
In user-mode Win32 API there are Slim Reader/Writer (SRW) Locks available in Vista and later.
Before Vista you have to i... |
7,553,409 | 7,553,493 | Polymorphic static const member variables in an ABC? | I have a rather strange situation where I would like to be able to define certain constants that a subclass of an ABC can override.
struct A {
static const int a = 20;
virtual int func() = 0;
};
struct B : public A {
static const int a = 3;
int func() { return 5; }
};
struct C : public A {
static co... | Constants, especially static constants, cannot be overriden like you are asking for. You would have to use a virtual function instead:
struct A {
virtual int get_a() { return 20; }
int func() = 0;
};
struct B : public A {
virtual int get_a() { return 3; }
int func() { return 5; }
};
struct C : public... |
7,553,640 | 7,555,446 | Asynchronous File I/O in C++ | I can't find information about asynchronous reading and writing in C++. So I write code, function read() works correctly, but synchronization doesn't. Sync() function doesn't wait for the end of reading.
For my opinion variable state_read in thread has incorrect value. Please, understand me why.
struct IOParams{
c... |
Maybe you know how to write the asynchronous reading in more reasonable way.
Since your question is tagged "Windows", you might look into FILE_FLAG_OVERLAPPED and ReadFileEx, which do asynchronous reading without extra threads (synchronisation via an event, a callback, or a completion port).
If you insist on using a ... |
7,553,687 | 7,553,815 | OpenGL performing very slowly | Working on a game, and I was testing out my renderer. It unfortunately only runs at about 4 frames per second. Profiling reveals that surprisingly, only 5% of that runtime belongs to my code, and the remaining 95% of the total run time was spent in nvoglnt.dll.
Only one 256x256 texture is used though, and beyond that... |
It is executed only 134217728 times for a total of 33554432 quads.
Each of those "few" calls makes your system to switch execution context between your program and the OpenGL driver. This is not "few". Honestly I'd consider this question some fine trolling, because each and every OpenGL tutorial these days will tell ... |
7,553,950 | 7,554,016 | How to calculate sha1 hash for image | Hi i am trying to calculate sha1 hash for image.
Is there any function available to calulate hash of image directly?
Sorry i forgot to mention .. its in c++ i am trying.
| Read the image file into memory, then call the SHA1 function on that. Python:
from hashlib import sha1
h = sha1(open(image_file, 'rb').read()).hexdigest()
This will give you the SHA1 of the image, including the headers, comments, etc. that are stored with it in the file. Remember that SHA1 just transforms a string of ... |
7,554,039 | 7,554,172 | Is string::c_str() no longer null terminated in C++11? | In C++11 basic_string::c_str is defined to be exactly the same as basic_string::data, which is in turn defined to be exactly the same as *(begin() + n) and *(&*begin() + n) (when 0 <= n < size()).
I cannot find anything that requires the string to always have a null character at its end.
Does this mean that c_str() is ... | Strings are now required to use null-terminated buffers internally. Look at the definition of operator[] (21.4.5):
Requires: pos <= size().
Returns: *(begin() + pos) if pos <
size(), otherwise a reference to an object of type T with value
charT(); the referenced value shall not be modified.
Looking back at c_st... |
7,554,427 | 7,555,318 | c++ Binary Search on dates sorted -> i need a range (cca) | I have a binary search on a file. The file is filled with log messages where each line begins with a date (dates or sorted based on event occurs)
example:
2011-09-18 09.38.20.123
2011-09-18 09.38.20.245
2011-09-18 09.38.20.393
2011-09-18 09.38.20.400
2011-09-18 09.38.20.785
If i need to find this date for example: ... | Try to implement an algorithm equivalent to std::equal_range which returns a pair of result of std::lower_bound and std::upper_bound
Find the position of the first element in the sorted range which does not compare less than the value (lower bound)
Find the position of the first element in the sorted range which compa... |
7,554,472 | 7,618,189 | Getting window coordinates of the insertion point - Cocoa | What is the best way to get window coordinates of the current caret position in a text edit control in Cocoa?
Here is how I do that in other platforms
Windows - EM_POSFROMCHAR
GTK - Using gtk_text_view_get_iter_location and gtk_text_view_buffer_to_window_coords.
I am wondering how the same can be done using Cocoa. I... | Assuming textView is a variable that points to the text view and window is a variable that points to the window:
// -firstRectForCharacterRange:actualRange returns a frame rectangle
// containing the insertion point or, in case there's a selection,
// the first line of that selection. The origin of the frame rectangle ... |
7,554,545 | 7,555,599 | accessing first n variadic function arguments | I have the following code :
template<size_t sz,typename T=float> class Vec{
T v[sz];
Vec(const T& val,const T&... nv){
//how do i assign `sz` number of first arguments into `this->v` array
}
}
I want to create constructor, that receive generic number of constructor argument, and assign the firs... | This is possible, but complicated. Here is some code that does it. It may be possible to eliminate the holder type, but I leave that as an exercise for the reader. This has been tested with g++ 4.6.
#include <iostream>
#include <typeinfo>
template<size_t ... Indices> struct indices_holder
{};
template<size_t index_to... |
7,554,583 | 7,578,398 | directing OpenSSL not to free a BIO object upon setting a new BIO | In this sample code:
BIO *bio1 = BIO_new(BIO_s_mem());
BIO *bio2 = BIO_new(BIO_s_mem());
SSL_set_bio(ssl, bio1, bio1);
SSL_set_bio(ssl, bio2, bio2);
the last call to SSL_set_bio automatically calls BIO_free(bio1).
Is there anyway to tell OpenSSL not to do so?
I know that upon creating a memory bio with BIO_new(BIO_s_m... | There's no way to prevent SSL_set_bio from freeing the current BIO in the public API. You can see in the source code that it simply checks whether each bio is not null and then frees it.
The main idea is that after you call SSL_set_bio, OpenSSL owns the BIO and is responsible for it.
void SSL_set_bio(SSL *s,BIO *rbio,... |
7,554,829 | 7,554,891 | c++ generalized operator templating | I'm doing some numerical simulations where it is nice to overload operations on vectors (similar to valarrays). For example, I can write
template <typename T>
vector<T> operator*(const vector<T>& A, const vector<T>& B){
//blah blah
}
But what if I want to generalize this template so as to act on two different types... |
Now, the above does indeed work if I use the operator in a situation
"A*B" where A and B are distinct and return a different type.
To be honest, this doesn't make sense. Your template shouldn't work at all because V cannot be deduced and it is the third template parameter. If you had written:
template <typename V, ... |
7,555,125 | 7,555,179 | Trying to link SDL in MinGW's G++ is failing miserably.. :/ | Late last night I got bored.. so I began writing a small 'Noughts and Crosses' type game in C++ and SDL. I wrote a fair majority of the basic part of the game, but when I compiled it to check for errors I got the error message: Undefined reference to WinMain@16; So, "Aah, simply add -lmingw32 should help!", I was think... | Your main function needs this exact signature: int main(int, char**)
|
7,555,138 | 7,555,997 | Operator new with nothrow option still throws exception | There is such code:
#include <iostream>
int main(){
for(;;){
int* ptr = new (std::nothrow) int;
if(ptr == 0){
std::cout << 0 << std::endl;
break;
}
}
std::cin.get();
return 0;
}
However, this program still throws std::bac_alloc exception, altough new is ... | I just ran your sample from VC2010. It is not new(nothrow) that throws, but __security_check_cookie.
|
7,555,180 | 7,555,339 | How to get a string of union set from a vector string? | I have a vector string filled with some file extensions as follows:
vector<string> vExt;
vExt.push_back("*.JPG;*.TGA;*.TIF");
vExt.push_back("*.PNG;*.RAW");
vExt.push_back("*.BMP;*.HDF");
vExt.push_back("*.GIF");
vExt.push_back("*.JPG");
vExt.push_back("*.BMP");
I now want to get a string of union set from the above-m... | See it live here: http://ideone.com/0fmy0 (FIXED)
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <set>
int main()
{
std::vector<std::string> vExt;
vExt.push_back("*.JPG;*.TGA;*.TIF");
vExt.push_back("*.PNG;*.RAW");
vExt.push_back("*.BMP;*.HDF"... |
7,555,202 | 7,558,107 | How to correctly return callbacks from C++ engine to obj-c program? | First the situation:
There is C++ written engine implemented in Objective C program. iPhone xcode to be precise. It uses OpenGL to draw everything. It has "renderFrame" method that is called every frame (approximately 50 times per second). User has many buttons that navigate to other Objective C views. These buttons ar... | It's a bad design for a number of reasons. First, what happens if more than one event took place? Two button clicks at once? Do you send 2 + 3? Do you ignore one and hope it wasn't important?
What happens when what you need to send isn't just a single binary fact? What if you want to send what button was clicked and wh... |
7,555,253 | 7,561,805 | Boost named_mutex and remove() command | I have a class which can be created by multiple threads. But at one function the code needs to be protected, so I decided to use the boost interprocess mutex. Every class creates or opens the same Mutex in it's constructor:
MyClass::MyClass()
{
boost::interprocess::named_mutex m_Lock(
boost::int... | From the boost docs, the remove call, is unnecessary. The destructor of named_mutex will automatically take care indicating to the OS that the process no longer needs the resource. You're probably fine with just relying upon the built-in behavior of the destructor for cleanup.
If you explicitly call remove, you'll like... |
7,555,255 | 7,555,315 | c++ even more generalized operator templating | So I just learned (thanks guys) about decltype. I now can write really nice vector templates that actually outperform valarrays(!):
template <typename T, typename U>
vector<decltype(T()*U())> operator*(const vector<T>& A, const vector<U>& B){
vector<decltype(T()*U())> C = vector<decltype(T()*U())>(A.size());
typena... | As you expected, this answer is "no." :)
However, you can use the preprocessor to generate such functions:
#define OPERATOR_BLOB(optype) \
vector<…> operator optype (…) { … }
OPERATOR_BLOB(*)
OPERATOR_BLOB(+)
…
|
7,555,321 | 7,555,397 | Why to pass mutex as a parameter to a function being called by a thread? | At some places I have seen people creating a thread pool and creating threads and executing a function with those threads. While calling that function boost::mutex is passed by reference. Why it is done so? I believe you can have a mutex declared in the called function itself or can be declared a class member or globa... | Mutex's are non-copyable objects, and while they can be members of a class, it would greatly complicate a parent class's copy-ability. Thus one preferred method, should a number of class instances need to share the same data, would be to create the mutex as a static data-member. Otherwise if the mutex only needed to b... |
7,555,419 | 7,555,504 | the "|=" operator in c++ | I have a question about "|=" in c++, how this operator works, for example:
bool result;
result |= callFunctionOne(sig);
result |= callFunctionTwo(sig);
result |= callFunctionThree(sig);
result |= callFunctionFour(sig);
and the function called above, will reutrn "true" if the paramater sig is processed in the functio... | | is bitwise OR.
|= says take what is returned in one of your function and bitwise OR it with the result, then store it into result. It is the equivalent of doing something like:
result = result | callFunctionOne(sig);
Taking your code example:
bool result;
result |= callFunctionOne(sig);
result |= callFunctionTwo(sig... |
7,555,545 | 7,555,579 | Defining copy constructor in a class inherited from POD struct | As you know compiler defines default constructor, copy constructor, assignment operator and destructor for POD structures if it weren't defined manually. Usually (or maybe should I say always) it's a bit copy operation. So I've decided to inherit my class from Win structure BITMAP to provide memory allocation in constr... | BITMAP(frame) will do the trick with no cast needed as the compiler will know the type of the parent and be able to implicitly convert the argument. Note that if you want to use a cast to explicit show what you're doing, cast as a reference type: BITMAP( static_cast<const BITMAP&>(frame) ),
Also, seriously consider thi... |
7,555,820 | 7,556,771 | How to work with null pointers in a std::vector | Say I have a vector of null terminates strings some of which may be null pointers. I don't know even if this is legal. It is a learning exercise. Example code
std::vector<char*> c_strings1;
char* p1 = "Stack Over Flow";
c_strings1.push_back(p1);
p1 = NULL; // I am puzzled you can do this and what exactly is stored at t... | I have a funny feeling that what you would really want is to have the vector contain something like "Stack Over Flow Answer" (possibly without space before "Answer").
In this case, you can use a std::vector<char>, you just have to push the whole arrays, not just pointers to them.
This cannot be accomplished with push_b... |
7,556,255 | 7,556,305 | How to free c++ memory vector<int> * arr? | I have a vector<int>* arr, which is actually a 2D array.
arr = new vector<int> [size];
Is it ok that I just do
delete arr;
Will arr[i] be automatically be deleted, since it is a standard vector?
| No, you should be using delete[] when you used new[].
But this is madness. You're using nice happy friendly containers for one dimension, then undoing all the goodness by resorting to manual dynamic allocation for the outer dimension.
Instead, just use a std::vector<std::vector<int> >, or flatten the two dimensions int... |
7,556,469 | 7,557,030 | Extending QString to overload construction | I would like to extend the QString class from Qt to provide some convenience for converting to/from various string types.
For example, I would like to be able to write lines like:
MyStringClass myString(_T("Hello World!"));
and get a MyStringClass object that behaves just like a QString. Using just QString, that would... | You really aren't abstracting anything there, it's a bad idea. If you bite the bullet and fix it now you won't ever have to deal with it again. If you keep deferring it, the cost will increase as you go.
You really want to keep your basic types as simple as possible.
Having 6 different string types is not manageable ... |
7,556,636 | 7,556,870 | Strange behavior of default constructor in a class inherited from POD struct | This question relates to this one.
As I mentioned in previous question I've decided to inherit my class from Win structure BITMAP to provide some extended functionality.
I've noticed interest detail in compiled program behavior. First I have defined default constructor for my class like below:
CPreviewFrame::CPreviewFr... | If you do not provide an explicit initializer for a POD-struct, then the object has an indeterminate initial value per Section 8.5/9 of the C++ standard. Adding an initializer for BITMAP that is an empty set of parenthesis to the initializer list of your CPreviewFrame constructor value-initializes the BITMAP object pe... |
7,556,693 | 7,556,757 | Is it possible to run standard algorithms on vector<MyType> in an elegant way? | I know if I have a vector<int> I can run algorithms on it like so:
int max = *max_element(myints.begin(), myints.end());
But what if I have a vector<MyStruct> where one of the fields within the struct is an int. Is there a nice elegant way to run an algorithm on just the ints in all of my structs?
| Provide a comparator to max_element:
MyStruct max = *max_element(v.begin(), v.end(),
[](const MyStruct & lhs, const MyStruct & rhs) { return lhs.theInt < rhs.theInt; });
If your compiler does not yet support lambdas, you will have to write a separate function or function object class.
Alternatively, if you overloa... |
7,556,852 | 7,557,270 | MSPaint-like app writing. How to do BitBlt right? | I'm writing now simple mspaint-like program in C++ using windows.h (GDI). For my program I need only pen tool. So, I need to store somewhere main window's picture (for ex. in memory HDC and HBITMAP) to draw it after in WM_PAINT message.
When I first have to store window's HDC to my memory HDC and HBITMAP? In what mess... | 1: I would recommend you lazy load your off-screen canvas as late as possible. If you need it in WM_PAINT and you haven't created it yet, create it then. If you need it at the point someone begins drawing, create it then. If it exists when you need it, then use it.
2: PatBlt fills a region of a bitmap using the device ... |
7,556,895 | 7,557,003 | OpenCV - only working with g++. Not gcc or nvcc | I have installed OpenCV.
I have been able to compile some code but sometimes it does not work. The example below does not work.
#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/gpu/gpu.hpp"
int main (int argc, char* argv[])
{
try
{
cv::Mat src_host = cv::imread("building.jpg", CV_LOA... | For compiling and linking C code you should use gcc
For compiling and linking C++ code you should use g++
Although gcc can often correctly guess what language to compile a file as, it can usually not link to the needed libraries.
|
7,557,027 | 7,557,208 | How to read a std::wstring written in linux into windows | We have a program which runs on Windows and Linux. It writes out std::wstrings in binary to a file. We need to be able to read in files written from linux into windows. We write out strings as a list of wchar_t. On linux each wchar_t occupies 4 bytes. On Windows each wchar_t occupies 2 bytes.
When reading the file wri... | You can use UTF8-CPP to easily convert the file from UTF-32 to UTF-16:
#include <fstream>
#include <iterator>
#include <utf8.h>
int main(int argc, char** argv) {
std::ifstream file("source.txt");
std::string intermediate;
std::wstring result;
utf8::utf32to8(std::istreambuf_iterator<char>(file),
... |
7,557,153 | 7,557,195 | Defining an object without calling its constructor in C++ | In C++, I want to define an object as a member of a class like this:
Object myObject;
However doing this will try to call it's parameterless constructor, which doesn't exist. However I need the constructor to be called after the containing class has done some initialising. Something like this.
class Program
{
public:
... | Store a pointer to an Object rather than an actual Object
thus:
class Program
{
public:
Object* myObject; // Will not try to call the constructor or do any initializing
Program()
{
//Do initialization
myObject = new Object(...); // Initialised now
}
}
Don't forget to delete it in the destruct... |
7,557,179 | 7,557,212 | Move constructor for std::mutex | Many classes in the c++ standard library now have move constructors, for example -
thread::thread(thread&& t)
But it appears that std::mutex does not. I understand that they can't be copied, but it seems to make sense to be able to return one from a "make_mutex" function for example. (Not saying it's useful, just that... | Well... mainly because I don't think they should move. Literally.
In some OS-es a mutex might be modeled as a handle (so you could copy them) but IIRC a pthreads mutex is manipulated in-place. If you are going to relocate that, any threadsafety is going fly right out of the window (how would the other threads know tha... |
7,557,213 | 7,557,357 | Visual studio for c++? | I have installed visual studio express 2010 c++. However when trying to follow a beginners book and make the hello world program, visual studio opens up a project with this in it:
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
return 0;
}
The... | As Alex said start with C++ Win32 console project, but select empty project so that the IDE don't fill things out automatically! Go to Source Files in your Solution Explorer, right click on it and add new item and choose C++ file (call it main.cpp for example).
At that point you should be ready to go.
Try this sample ... |
7,557,222 | 7,558,183 | C++ nested preprocessor directions | I'm using preprocessor directives to de-bloat some templated operator definitions. E.g.
#define BINARY_VECTOR_RETURN_OPERATOR(optype) \
template <typename T, typename U> \
vector<decltype(T() optype U())> operator optype (const vector<T>& A, const vector<U>& B){ \
vector<decltype(T()*U())> C; \
C.reserve(A.size()... | You can't have a #if inside a #define, but you can have a #define inside the code controlled by a #if.
For example:
#ifdef DEBUG
#define BINARY_VECTOR_RETURN_OPERATOR(optype) \
first-part \
debug-code \
last-part
#else
#define BINARY_VECTOR_RETURN_OPERATOR(optype) \
first-part \
last-part
#endif
If first-part and ... |
7,557,406 | 7,557,469 | Why was "this" used as a non const deprecated in C++ | Why was this deprecated in C++? How is the this pointer in C++ different than this in Java?
Or is Wikipedia just wrong
Early versions of C++ would let the this pointer be changed; by doing
so a programmer could change which object a method was working on.
This feature was eventually deprecated, and now this in C++... | I believe your mistake is in how you interpret that line. They're not saying "The this feature was deprecated". Merely the ability to reassign the this pointer was deprecated.
|
7,557,594 | 7,558,163 | How can I make my QThread block and wait for a function called from the main thread to return a value? | I am doing some work in a QThread reimplementation. Every now and then, I'd like to ask the user a Yes/No question, so I was planning on using QMessageBox::question(). Problem is, I can't call it from the thread. That's not a big one, I can emit a signal that connects to a slot in the main GUI thread which will display... | If you are working with signals and slots anyway, you can also use the Qt::BlockingQueuedConnection connection type. This connection will wait until the slot (in another thread) is finished executing. Be careful not to deadlock though.
|
7,557,804 | 7,558,451 | Is there any way to get a direct pointer to a Java array via JNI? | I need to get a pointer containing the direct memory address of a Java array, via JNI, without invoking some sort of copying (ie direct access).
GetArrayElements returns a pointer to a copied array - I need to be able to modify an int[] on the Java layer directly from a the native layer.
Casting from a jintArray to an... | You can use an IntBuffer using direct memory (with native byte order). In JNI you can use the address as a pointer. In Java you have to use the get() and put().
|
7,557,816 | 7,557,928 | Does it matter if this is used in a C++ setter? | Suppose I have a c++ class with a private variable, x. For it's setter, is there any difference using this? Is there the potential for unwanted / unexpected behavior is I don't use this?
Setter:
void setX(double input)
{
x = input;
}
Setter using this:
void setX(double x)
{
this->x = x;
}
| Because of two-phase lookup for class templates, this might be required to
explicitly state you mean a member
because of lookup rules, the compiler might assume another entity that is visible there is meant
(see the first example) Both are equivalent.
In a non-template situation, you usually avoid using this; the g... |
7,557,941 | 7,557,963 | Error Writing to Memory of Particular Data Member | Okay, I have a struct, TextBlock, that simulates moving blocks of text around the screen. Here's the header:
struct TextBlock
{
RECT textArea;
RECT rectArea;
double whatBlock;
double x;
double y;
double angle;
double speed;
double width;
double height;
char *word;
bool stuck;... | Without you posting more code, I can only tell that you likely have a memory corruption bug in your program - i.e. you are reading or writing beyond the end of allocated memory.
If you post more code, I'll edit this answer accordingly.
|
7,557,968 | 7,558,010 | a strange use of typedef | I have never see a grammar in c++ like this before:
typedef int (callback)(int);
what really does this really mean?I just find that if I create a statement
callback a;
It's effect is very very similar to a forward function declaration.
below is the code I had written
#include<cstdio>
int callbackfunc(int i)
{... | Its because of the fact that in the parameter declaration, the function-type is adjusted to become a pointer-to-function-type.
typedef int type(int);
typedef int (*type)(int);
The first typedef defines a type which is called function-type, while the second typedef defines a type which is called pointer-to-function-t... |
7,557,990 | 7,558,035 | C++ method name as template parameter | How do I make the method name (here some_method) a template parameter?
template<typename T>
void sv_set_helper(T& d, bpn::array const& v) {
to_sv(v, d.some_method());
}
| There is no such thing as a 'template identifier parameter', so you can't pass names as parameters. You could however take a member function pointer as argument:
template<typename T, void (T::*SomeMethod)()>
void sv_set_helper(T& d, bpn::array const& v) {
to_sv(v, ( d.*SomeMethod )());
}
that's assuming the functio... |
7,558,036 | 7,558,134 | Is there some way to create a class that have an object of a class that have an object of this class in C++? | In C++, is there some way to create a class that have, as attribute, an object of a class that have, as attribute, an object of the first class?
e.g.:
class A {
B attribute;
public:
A(){}
};
class B {
A attribute;
public:
B(){}
};
The code above does not compile. Is there some way to do something alik... | First, you need to forward declare your class B. If not, the compiler wouldn't know what the B is. Also, change the attributes to be pointers, or else you will still have a compiler error, even though you forward declared B, it still doesn't know the implementation yet!
The following code may help, good luck...
class B... |
7,558,058 | 7,558,080 | Accessing a variable in a union which is inside a class | Sorry for naive question in C++. For below code, there is a class, inside which there is a union declaration having two variables. How to access the variables in the union using the class object in code below:
class my
{
public:
//class member functions, and oeprator overloaded functions
public:
union uif
{... | You are only defining the union within the scope of the class, not actually creating a member variable of its type. So, change your code to:
class my
{
public:
//class member functions, and oeprator (sic) overloaded functions
public:
union uif
{
unsigned int i;
float f;
} value... |
7,558,268 | 7,558,281 | Friend operator behavior (const vs non-const) | I have the following C++ code:
#include <iostream>
template <class T>
void assign(T& t1, T& t2) {
std::cout << "First method" << std::endl;
t1 = t2;
}
template <class T>
void assign(T& t1, const T& t2) {
std::cout << "Second method" << std::endl;
t1 = t2;
}
class A {
public:
A(int a) : _a(a) {};... | It doesn't return a const A at all. It returns a temporary A, which may only bind to a const reference.
|
7,558,554 | 7,560,612 | Strange shader corruption | I'm working with shaders just now and I'm observing some very strange behavior. I've loaded this vertex shader:
#version 150
uniform float r;
uniform float g;
uniform float b;
varying float retVal;
attribute float dummyAttrib;
void main(){
retVal = dummyAttrib+r+g+b; //deleting dummyAttrib = corruption
gl_Pos... | In case of your artificial usage (float c = dummyAttrib) the attribute will be optimized out. The question is what your mesh preparing logic does in this case. If it queries used attributes from GL it will get nothing. And with no vertex attributes passed the primitive will not be drawn (behavior of my Radeon 2400HD on... |
7,558,595 | 7,561,325 | How to set pixel on mouse click in C++ using WinApi (GDI) in GUI window? | I'm trying to set pixel by mouse click, but nothing happens when I click. Here is part of my code.
First, I control window size changing in WM_SIZE.
Than, at first time when I want to set pixel by mouse I get window's width and height, then copy window's content to memory HDC and HBITMAP (in Store Window) (HBITMAP size... | When you call RestoreWindow() to draw the bitmap onscreen, you are wiping out your memoryDC variable that you used to draw the pixels with. The bitmap is still selected into the original HDC that you have now lost, and a bitmap cannot be selected into multiple HDCs at the same time (the MSDN documentation for SelectOb... |
7,558,837 | 7,558,911 | What exactly is a type cast in C/C++? | What exactly is a type cast in C/C++? How does the compiler check if an explicit typecast is needed (and valid)? Does it compare the space required for an value? If I have for example:
int a;
double b = 15.0;
a = (int) b;
If I remember correctly a double value requires more space (was it 8 bytes?!) than an integer (4 ... | A type cast is basically a conversion from one type to another. It can be implicit (i.e., done automatically by the compiler, perhaps losing info in the process) or explicit (i.e., specified by the developer in the code). The space occupied by the types is of secondary importance. More important is the applicability (a... |
7,558,907 | 7,559,004 | How to specialize member of template class with template template parameter | I have a template class with an int and a template template parameter.
Now I want to specialize a member function:
template <int I> class Default{};
template <int N = 0, template<int> class T = Default> struct Class
{
void member();
};
// member definition
template <int N, template<int> class T> inline void Class<... | You can't partially specialize a single member function, you'll have to do it for the entire class.
template <int I> class Default{};
template <int N = 0, template<int> class T = Default> struct Class
{
void member();
};
// member definition
template <int N, template<int> class T> inline void Class<N, T>::member()... |
7,559,059 | 7,559,215 | JNI "env->GetStaticMethodID()" crashed program | I'm trying to call a Java function from C++.
This is my code so far:
#include <jni.h>
typedef struct JavaVMCreationResult {
JavaVM* jvm;
JNIEnv* env;
} JVMCreationResult;
JVMCreationResult* CreateJavaVM() {
JavaVM* jvm;
JNIEnv* env;
JavaVMInitArgs args;
JavaVMOption opts[1];
opts[0].opti... | Your variable "cres" is a point in the CreateJavaVM call that is never initialized, so you're probably dereferencing a null or otherwise invalid pointer at that point.
One solution is to define cres (not a pointer to cres) in main, and pass a pointer to that to CreateJavaVM as a parameter, and then use the parameter in... |
7,559,122 | 7,559,237 | Strange program and debugger if statement behavior | This is a sanity check because I've lost mine.
I have a method IsCaptured() which compares an enum state member to a given value and returns a bool. I use this in conjunction with a mouse threshold check to determine if a drag begin message should be sent and a drag operation begun. The problem is this is being trigger... | There's nothing strange in your output. && has higher precedence than ||, which is why your
if (IsCaptured() &&
abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y)
is interpreted as
if ((IsCaptured() && abs(delta.x) >= thresh.x) ||
abs(delta.y) >= thresh.y)
I.e. if the abs(delta.y) >= thresh.y condition is... |
7,559,236 | 7,559,373 | Dynamic Sieve Algorithms for Prime Generation | I'm implementing the Sieve of Eratosthenes, for an explanation of this see http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. However I would like to adapt it to generate M primes, not the primes 1 through N. My method of doing this is simply to create a large enough N such that all M primes are contained in this rang... | To generate M primes, you need to go up to about M log M. See Approximations for the nth prime number in this Wikipedia article about the Prime Number Theorem. To be on the safe side, you might want to overestimate -- say N = M (log M + 1).
Edited to add: As David Hammen points out, this overestimate is not always good... |
7,559,313 | 7,559,382 | ShellExecute async (launch program from within C++ and exit immediately) | I want to launch MYAPPLICATION from within a C++ program and immediately exit the C++ program (so I do NOT want to wait until MYAPPLICATION has finished or get a reference to the program): just start the MYAPPLICATION and exit.
I tried ShellExecute, but the C++ app is still running after the MYAPPLICATION is started. I... | You need to terminate your process using ExitProcess(), TerminateProcess(), or returning from WinMain() after you start the child process.
|
7,559,319 | 7,559,579 | 2d array from boost::multi_array - unable to compile | I am trying to create a 2d array class based on boost::multi_array. I face two issues in the code given below. (1) The code for the member function col() does not compile saying that ::type’ has not been declared. Where am I going wrong? (2) Is it possible to define the member function data() outside the class? My atte... | array_type::array_view<1>::type
You need template and typename here :)
typename array_type::template array_view<1>::type
^^^^^^^^ ^^^^^^^^
The keyword template is required because otherwise the < and > will be treated as less and greater because the array_type is a dependent name, and therefore whether ar... |
7,559,803 | 7,559,916 | IP falls in CIDR range | I have an IP like this: 12.12.12.12
I'm looping through different IP ranges (in 12.12.12.0/24 (example)) format, and trying to see if the IP is in the range.
I have tried various methods such as inet_addr and comparing but I can't seem to get it.
Is there an easy way to do this? I'm using Windows.
| Just test whether:
(ip & netmask) == (range & netmask)
You can determine the netmask from the CIDR parameters range/netbits as follows:
uint32_t netmask = ~(~uint32_t(0) >> netbits);
|
7,559,908 | 7,559,964 | Can you use assert to test type defintions in C++? | Can I use assert to enforce type definitions. Suppose there is a variable, double d, how can you use assert to assert that d is a double? If assert is not applicable (which I am betting isn't), is there another option? I am specifically looking to test for implicit type casting during debugging, while benefiting from t... | It's really a compile time check, so you should use static asserts for this.
Here is an example using boost's static asserts and type traits.
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
template<typename T>
void some_func() {
BOOST_STATIC_ASSERT( (boost::is_same<double, T>::value) );
}
... |
7,559,928 | 7,560,020 | STL Sort on nested Classes | I have a graph class that has a vector of nodes. In each node, there is a vertex and a STL list of edges. Essentially it's an adjacency list.
For my assignment, I am trying to display the vertices with the most edges. I figured I would sort the graph's vector of nodes by edge size and print the top N vertices.
So I am ... | Your member function needs to be const-qualified:
bool operator<(const Node<T>& rhs) const{
EDIT
Per request, here is a bit more how I knew that you needed to make the member function const.
Divining the hidden meanings in stdlib-related compiler errors is something of an art, and something that you get better at with... |
7,560,109 | 7,560,281 | visual studio weird behavior | I am making a win32 application using visual studio 2008.
When ever i compile my code which generates a simple dialog, all of the dialogs text show in Chinese language. I have not set Chinese anywhere. can some one elaborate what the issue is?
My code is
#include <windows.h>
int WINAPI WinMain(
HINSTANCE nowIn... | It sounds like you're mixing Unicode and ANSI.
Have you tried
MessageBox(NULL, _T("My First Program"), _T("Our University"), MB_OK);
And does that give you the expected results?
|
7,560,114 | 7,560,151 | Random number c++ in some range |
Possible Duplicate:
Generate Random numbers uniformly over entire range
I want to generate the random number in c++ with in some range let say i want to have number between 25 and 63.
How can I have that?
| You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:
25 + ( std::rand() % ( 63 - 25 + 1 ) )
|
7,560,148 | 7,560,187 | Something wrong with linking | I have 3 C++ files:
genericStack.h:
template <class T>
class Stack{
public:
Stack (int size){
top = -1;
MAX_SIZE = size;
v = new T (size);
}
~Stack(){ delete v;}
T pop();
void push (T);
class Underflow{};
class Overflow{};
private:
int top;
int MAX_SIZE;
T* v;
};
genericStac... | Generally speaking, template definitions need to also be in the header file. An exception to this is when you are explicitly instantiating, or using explicit specialisations, neither of which you are doing.
One way to solve this would be to move the contents of genericStackImpl.c++ to the bottom of its header file.
The... |
7,560,170 | 7,560,201 | logical operations on large files binary data in C/C++ | I have two binary files (order of tens of MB) and I want to or every bit of these files. And of course, I want it to be as efficient as possible.
So I have two ways in mind to do that, but I still think (I kinda feel) that should be a more efficient way that I do not know of.
Given file a and b .. what I want to do is ... | Don't go byte-by-byte. That'd be seriously slow. Instead, read the files in chunks. Find what the block size is for your system (4k? 8K? 64k?) and read the file using chunks of that size. Then you can loop through the byte streams in memory and do the OR operations there.
In logical terms, even though you might only be... |
7,560,215 | 7,560,241 | Google Mock giving compile error when attempting to specify a return value | I'm using Google Test and Google Mock for my C++/Qt application. I've been having great success with this setup until just now when I tried this:
QList<AbstractSurface::VertexRow> rowList;
for (unsigned i = 0; i < rows; ++i)
{
AbstractSurface::VertexRow curRow(new AbstractSurface::Vertex[cols]);
for (unsigned j... | The simplest solution is :
EXPECT_CALL(surface, popAllRows_impl()).WillOnce(Return(rowList));
EDIT :
ON_CALL has WillByDefault, but no WillOnce method. Check the gmock cookbook
|
7,560,471 | 7,560,495 | Try-Catch Problem in c++ | I am trying queue implementation in c++. During that I am having this problem.
void Queue::view()
{
int i;
try
{
if(Qstatus==EMPTY)
{
UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY");
throw ex;
}
}
i=front;
cout<<"Queue contains...\n";
while(i <= rear)
{
cout<<queue[i]<<" ";
i... | catch block must follow the try block. If you want the catch to be in main - that's where the try has to be too. You can throw everywhere, doesn't have to be inside a try block within the same function.
It should be something like this:
void Queue::view()
{
int i;
if(Qstatus==EMPTY)
{
UnderFlowException ex = Un... |
7,560,792 | 7,560,822 | Shared Header Causes Multiply Defined Symbol Error | Consider the following header file example: shared_example.h
#ifndef SHARED_EX
#define SHARED_EX
const int Shared_Int = 1;
const char * Shared_CString = "This is a string";
#endif
The shared_example.h file is included in multiple compilation units, which leads the linker to (correctly) complain that:
error LN... | The first declaration is of a constant integral value. In C++, const has internal linkage by default.
The second declaration is of a pointer to const char. That declaration is not const itself, and has no other linkage specifiers, so it does not have internal linkage. If you changed the declaration to const char * cons... |
7,560,852 | 7,560,898 | char* to double and back to char* again ( 64 bit application) | I am trying to convert a char* to double and back to char* again. the following code works fine if the application you created is 32-bit but doesn't work for 64-bit application. The problem occurs when you try to convert back to char* from int. for example if the hello = 0x000000013fcf7888 then converted is 0x00000000... | On 64-bit Windows pointers are 64-bit while int is 32-bit. This is why you're losing data in the upper 32-bits while casting. Instead of int use long long to hold the intermediate result.
char* hello = "hello";
unsigned long long hello_to_int = (unsigned long long)hello;
Make similar changes for the reverse conversion... |
7,561,033 | 7,561,118 | I'm lost in boost libraries (specifically boost_program_options) | Hi all I've been banging my head against the wall all day now.
So I want to move my program onto the university supercomputer, but it doesn't have boost (and I used boost program_options in my code). On my pc, I just have -lboost_program_options and that works fine, but obviously won't work anymore.
So, I need to packa... | One option is to build boost on that machine. Install it in your home. Change your CXXFLAGS and LDDFLAGS to point to the proper header and library directories and build your code there.
The other option is to cross compile both on your PC (if you have such a cross toolchain). Link your code statically to boost and take... |
7,561,049 | 7,561,083 | What is the difference between GetClientRect and GetWindowRect in WinApi? | What of these should I use in InvalidateRect to refresh my window? And why?
| The window rect includes the non-client area, i.e. the window borders, caption bar etc. The client rect does not.
GetWindowRect returns a rect in screen coordinates whereas GetClientRect returns a rect in client coordinates.
InvalidateRect receives a rect in client coordinates. If you want to invalidate your entire cli... |
7,561,165 | 8,225,983 | Rendering Kinect Point Cloud with Vertex Buffer Object (VBO) | I´m trying to make a dynamic point cloud visualizer. The points are updated every frame with Kinect Sensor. To grab the frames I´m using OpenCV and GLUT to display.
The OpenCV API returns a 640 x 480 (float *), for the points xyz position , and a 640 x 480 (int *) for the rgb color data.
To get the maximum performance,... | PS: The program is up and running, but I can't see any improvement in the average performance when compared to the Vertex Array version. Is that alright?
THE PROBLEM WAS SOLVED. I´ve done three alterations:
1 - I though that glGenBuffers first parameter was the number that
would be associated to the buffer, instead, it... |
7,561,265 | 7,621,826 | Recording an audio stream in C# from C++ ASIO library | I need to find the best way to record an audio stream. I have already built the low level code in C++ and interfaced parts of it to C#.
So i have a C++ callback that gives me an array of array of floats - the audio signal.
At the moment, my C++ lib is recording the data straight to the file in the wav format and it ju... | Question 1: You want to pass a C# delegate matching the unmanaged C signature into your C++. You can then call back on this as if it was a C function pointer. For example,
delegate void ASIOCallback(IntPtr signal, int n);
You would then need to either manually marshal the signal memory into a managed buffer, or copy i... |
7,561,342 | 7,581,694 | Completer of QLineEdit get Memory | I have q method that shown at below:
void MainWindow::slotResults( const QList<QSqlRecord>& records )
{
ui->lineEditWord->setCompleter(0);
QStringList wordList;
for(int i = 0; i < records.count(); i++)
{
wordList.append( QString("%1").arg( records.value(i).value(0).toS... | The QCompleter constructor you are using takes a QStringList as parameter. It is certainly (while this is not documented properly), a convenience constructor that creates a QStringListModel filled with the strings passed to the constructor and set this model as the completion model with QCompleter::setModel().
You can ... |
7,561,468 | 7,561,492 | Placing C++ class in another file: compilation error | I am learning about C++ classes and I realized that if I tried to move my class declaration and definition of class Date from main.cpp to another c++ file, say test.cpp and compiled the two files I got an error saying Date was not declared. Why is that?
| This is why you have header files. You need a header file test.h that contains only the class definition (that is mostly function declarations) and test.cpp that contains the actual function definitions (the code).
In main.cpp you'll have to #include "test.h".
|
7,561,656 | 7,562,152 | Why escaping 'w' ('\w') character reverses memory representation of a int variable? | Consider the following code sample:
int i1 = 'w\"';
int i2 = '\w\"';
int i3 = 'w"';
int i4 = 'w\"';
Note: MSVS SP1 2005 C++ compiler, just default debug compilation/linkage settings. x86 machine. The compiler outputs warning C4129: 'w' : unrecognized character escape sequence and everything else is just fine.
The raw ... | It's a bug in the compiler. I suggest you file a bug on Microsoft Connect (though I wouldn't bet on them fixing it any time soon). It also occurs with real escape sequences such as \n or \x6e, so it has nothing to do with the invalid escape sequence \w.
In VS 2008 and VS 2010, the output of this program:
#include <st... |
7,561,690 | 7,561,710 | Why do we not pass POD by reference in functions? | I've always been told that we should not pass POD by reference. But recently I've discovered that a reference actually takes no memory at all.
So why do we choose to write:
void DoSomething(int iNumber);
instead of:
void DoSomething(const int& riNumber);
is it not more efficient?
| Actually in this case (using int) passing by value is probably more efficient, since only 1 memory-read is needed instead of 2, to access the passed value.
Example (optimized using -O2):
int gl = 0;
void f1(int i)
{
gl = i + 1;
}
void f2(const int& r)
{
gl = r + 1;
}
int main()
{
f1(1);
f2(1);
}
As... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.