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,755,647 | 7,756,000 | OpenCV extract area of an image from a vector of squares | I have an image that contains a square, and I need to extract the area contained in that square.
After applying the squares.c script (available in the samples of every OpenCV distribution) I obtain a vector of squares, then I need to save an image for each of them.
The user karlphillip suggested this:
for (size_t x = 0... | I feel like I need to clarify a few things about that code.
First, it assumes that the region detected is a perfect square because it ignores some of the points inside squares[x] to create a new Mat.
Second, it also assumes that the points that make the region were detected in the clockwise direction, starting with p... |
7,755,668 | 7,755,903 | Linking against boost_thread fails under Ubuntu 11.10 | I already updated to the new Ubuntu 11.10.The problem is now, that the software I am working on is not linking any more. I found this wiki entry which seems to describe the problem. None the less I am unable to fix it. To reproduce the problem I wrote the following small test program:
#include <iostream>
#include <boos... | Ok I mamaged to fix it, it is ridiculous:
as written in the question
g++ -o test -lboost_thread test.cc
does not work, but
g++ -o test test.cc -lboost_thread
does... So not only the order of libraries matter, but also the source files must be written before the dependencies...
|
7,755,719 | 7,755,855 | check if string starts with another string: find or compare? | If you want to know if a string starts with another, how would you do that in C++/STL? In Java there is String.startsWith, Python also has string.startwith, STL does not have a direct method for it. Instead, there are std::string::find and std::string::compare. Until now I used both methods, mostly depending on my curr... | The disadvantage of find is that if str1 is long, then it will pointlessly search all the way through it for str2. I've never noticed an optimizer being smart enough to realise that you only care whether the result is 0 or not, and stop searching after the start of str1.
The disadvantage of compare is that you need to ... |
7,756,225 | 7,757,218 | ASSERT(::IsWindow(m_hWnd)) issue, not sure what's wrong | I'm having a bug in my code that's kicking my ass, so after much attempted debugging I finally decided to see if anyone else knew what my issue was.
I'm trying to add a grid object to a dialog that I have, but I keep hitting the assert mentioned in the title and I don't know why.
LONG myDialog::OnInitDialog(UINT wParam... | Are you sure the dialog is created when you call
CDerivedDocument::SetMyDoc(myDialog * pDlg)?
What I see is that you are loading the grid (& dialog) from document, you should rather load the dialog and grid from the view using the document.
This may not be the direct cause of your assert trouble but nevertheless an im... |
7,756,393 | 7,756,530 | class with no constructor forces the use of a pointer type? | I don't want to use pointers when I don't have to, but here's the problem: in the code below if I remove the asterisk and make level simply an object, and of course remove the line level = new Level; I get a runtime error, the reason being that level is then initialized on the first line, BEFORE initD3D and init_pipeli... | You are correct that if you do:
Level level;
then level will be instantiated at that point. That is because the above expression, which appears to be a global, isn't just a declaration, but also a definition.
If this is causing you problems because Level is being instantiated before something else is being instantiat... |
7,756,401 | 7,756,500 | Determining the quantity of elements in a C array | When print_array is called, the size of the int array[] parameter (count) isn't what was expected. It seems sizeof is not returning the size of the entire array which would be 5*sizeof(int) = 20.
namespace Util
{
void print_array(int array[])
{
size_t count = (sizeof array)/(sizeof array[0]);
cout <<... | int array[] here becomes int* array, and sizeof(array) returns the same thing sizeof(int*). You need to pass an array by reference to avoid that.
template <size_t N>
void print_array(int (&array)[N]) {
std::cout << N;
}
int array[] = { 2, 1, 5, 4, 3 };
print_array(array);
|
7,756,701 | 7,756,750 | Can you cast away volatile on a member from a volatile function> | If you have a class member function marked volatile, is it possible to cast away volatile on a class member when it's bein used within that function?
| Yes. To cast away the volatile-ness of an object, const_cast is used:
T & t = const_cast<T&>(volatile_t);
This is the way. But whether you should use it in your code or not, I cannot say without looking at the code. In general, casting away the const-ness as well as volatile-ness, is a dangerous idea, and should be d... |
7,756,747 | 7,756,766 | container.erase(first,last) where first == last in STL containers | Is there a defined behavior for container.erase(first,last) when first == last in the STL, or is it undefined?
Example:
std::vector<int> v(1,1);
v.erase(v.begin(),v.begin());
std::cout << v.size(); // 1 or 0?
If there is a Standard Library specification document that has this information I would appreciate a reference... | The behavior is well defined.
It is a No-op(No-Operation). It does not perform any erase operation on the container as end is same as begin.
The relevant Quote from the Standard are as follows:
C++03 Standard: 24.1 Iterator requirements and
C++11 Standard: 24.2.1 Iterator requirements
Para 6 & 7 for both:
An iterato... |
7,756,834 | 7,757,107 | Changing QAbstractTableModel headerData using the role | I have a subclass
class TableModel : public QAbstractTableModel
I override the headerData method as follow:
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {...}
if (role == TableModel::CurrencyRole && orien... | First of all, it looks like to do exactly what you're trying to to is going to be a bit tricky.
After a quick perusal of the Qt source code it looks like there's no way to change what role is passed to your model's headerData() function just using the API.
You do, however, have the ability to subclass QHeaderView and o... |
7,756,884 | 7,757,515 | parallel program compiling error | I write a parallel code that I can compile it and run it under win7 but now I have to run it under linux ubuntu 11.04 when I compile my code I get this error:
usr/bin/ld :cannot find -lcr
collect2:ld returned 1 exit status
my compiler is mpicxx and I use mpich2.
my code has about 3000 lines but I use the following cod... |
usr/bin/ld :cannot find -lcr
Googling around shows the cr library is provided by the Berkeley Lab Checkpoint Restart (BLCR) package. I think you need to install it.
|
7,757,001 | 7,757,050 | Command line float input and output using streams | My first question on this site, here goes:
I am working on a tutorial question and it asks me to write a program that outputs the product of some entered floating point numbers from the command line: This is to be done using streams.
Now in My tutorial book it suggests using the following code:
#include <iostream>
#inc... | istream constructor expects a streambuf. You probably want to use istringstream:
istringstream cinx(argv[i]);
and #include <sstream> in the beginning.
Besides, you're computing the sum, not the product.
|
7,757,015 | 7,757,045 | Opening a file using a variable name | If I change myfile("input.txt") to myfile(file_name)...where file_name is passed to the function it does not work but gives the error no matching function call..which I'm guessing b.c. I'm not suppose to be passing a string to the constructor...if not this way..how?
void file_to_string(string file_name)
{
string lin... | Use the c_str() member of the std::string class:
ifstream myfile(file_name.c_str());
It returns a null-terminated const char * representation of the string in question, which is exactly what you need here.
|
7,757,096 | 7,757,120 | How can I store a boost::bind object as a class member? | I'm writing an application that uses boost::asio. Asio's async_receive (or async_read) is invariably shown using a boost::bind object given for callback:
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(),
chat_message::header_length... | Use boost::function:
class Whatever
{
public:
Whatever()
{
functor = boost::bind(
&chat_session::handle_read_header,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
);
boost::asio::async_re... |
7,757,312 | 7,761,064 | Detecting overwrites when using unzip from command line in Redhat | Possibly this should be on Superuser, but I'm using it in code so thought I'd start here.
My C++ program unzips a .gz file using the "system()" call. (Yes I know it's taboo, but it was the best of a bad lot when I started this project a while back, and I asked Unzipping a file from C++ on Redhat: alternatives to system... | I believe the obvious answer would be to try to detect whether there is a file with the appropriate name on disk before you even run the system command; if a file exists prior to unzipping, then an overwrite will occur. You can easily check whether a file exists by fopening it with a mode of "r" and checking the return... |
7,757,519 | 7,757,559 | forward declarations | Why do I need to use forward declarations for a class when I am already including the relevant header file? It has fixed my problem but confused me!
essentially class A needs to know about class B and visa-versa. I was getting the error "sytax error - identifier" before I included the forward declarations. I was under ... | When you have a circular include dependency, and you're properly using include guards (as you clearly are), then since there isn't an infinite circular include, the compiler has to stop at some point, and it doesn't know about the contents of the other header. When you add the forward declaration it's able to compile y... |
7,757,707 | 7,757,835 | Is it safe to disable MSVC warning C4482? | While qualifying an enumeration value with the name of the enumeration is not valid C++03, it is valid C++11, from what I understand. Despite this, MSVC 10 generates warning C4482 for the following:
enum E { A, B };
int i = E::A; // warning C4482 (but valid C++11?)
Since much of our code uses C++11 features (especia... |
Since much of our code uses C++11 features (especially lambdas), it seems safe to disable this warning.
If you're already relying on C++11 features, then yes. C++11 does allow you to use regular enums scoped by the enumeration's name. Microsoft had this as an extension for some time, so they issued a warning about th... |
7,757,837 | 7,757,873 | How do I copy a file on a http server, from the client? | In the past I used an ftp server, connected via "ftp" from the client and "GET" to copy one file from the remote machine to the local machine.
Is it possible to do the same but with the server only running a http server?
Server: GoAhead Web Server.
Both client and http server on Windows.
The copy can be either initiate... | HTTP servers will only serve up files that are located within the site's document root. If you want to get at files that are outside the document root, you'll have to have a script serve up that file from the server (php, perl, cgi, etc...), or find some way of getting that file "inside" the document root.
To download... |
7,757,843 | 7,757,869 | What's the difference between AfxOleInit and OleInitialize? | When should I use one over the other? MSDN doesn't provide any useful information.
| If you're using MFC you should use the AfxOleInit variant. This calls both OleInitialize and creates / installs an MFC IMessageFilter object. The second step is an MFC specific initialization step.
If you're not using MFC then just call OleInitialize
|
7,757,949 | 7,757,974 | typedef error: where to put typedef and how it should be written? | I'm writing a btree implementation class 'btree' inside a file btree.h and implemented inside btree.tem with an external iterator class 'btree_iterator' in a file btree_iterator.h implemented in a file btree_iterator.tem
Here is the (stripped down) content of btree.h:
#include "btree_iterator.h"
template <typename T> ... | Write this:
template <typename T>
typename btree<T>::iterator btree<T>::find(const T& elem) //LINE 24
{
//;;
}
Since iterator is a nested type, you've to write btree<T>::iterator, and since it is a dependent nested type as it depends on the template argument type T, you've to use typename as well:
typename btree<T... |
7,757,983 | 7,772,883 | Looking for code sample on creating C++ DLL then P/Invoke in C# (For Windows CE 5/6) | I am experienced in C# but not in C++. Recently my Windows CE 5 C# program is hitting performance issue and I am considering moving calculation to C++ DLL then P/Invoke it from C# since C++ supports hardware float-point co-processor while .NET CF does not.
I am searching the net all morning trying to find a complete sa... | I finally found a good article discussing how to create C++ DLL for C#
http://forums.ni.com/t5/Measurement-Studio-for-VC/How-to-create-dll-in-Visual-Studio-2008-in-Visual-C/td-p/698632
Mentioned by ChinJohn a complete example is located here: http://www.coodtec.com/wordpress/?p=130
|
7,758,129 | 7,758,442 | C++ Quadratic equation outputs: -1.#IND | My code works fine with: (1, -2, -8), It gives me the error above when I input a=1 b=0 c=1,
Here is my code:
double x=0,a=0,b=0,c=0,d=0;
complexType solu1;
complexType solu2;
cout << "\n\nEnter values of quadratic a,b,c:";
cin >> a >> b >> c;
double solution1 = (-1.0 * b) + (sqrt((b * b) - (... | You are trying to find a real solution to x^2 + 1 = 0, which only has imaginary solutions.
If you want to solve all quadratic equations, then you need to check whether the discriminant is positive to determine whether the solutions are real or complex:
double d = b*b - 4*a*c;
if (d >= 0) {
double sol1 = (-b + sqrt(... |
7,758,136 | 8,582,260 | Is there an API I can use to query Offline Files results? | If you run MobSync.exe on a Windows 7 computer with Offline Files enabled, you can click "View sync results" to get a view of the Offline Files Sync history of your computer.
Does anyone know if there's an API to get this history, or is it necessary to parse through Event logs or the registry to do this?
I know about t... | I don't believe there is any such API.
|
7,758,264 | 7,758,404 | Graph Library API design | I am writing my own Graph library Graph++, I have question regarding what should interface return. For example What should my BFS return, I am confuse on the point that whether it should return set of vertices visited in the order , or should I have callback function, which will get invoked during each visit.
What coul... | A recurring pattern in the stl is to offer iterators. Your traversal algorithms might return a start iterator, and the library user could increment it as desired, while comparing against an end() iterator that either it or the graph provides.
The visitor pattern may also be relevant to your interests.
|
7,758,353 | 7,758,450 | What API would initiate an FTP transfer and report status to a GUI? | Thinking of something like an MFC application, with one button - "Download"
User selects download and then is prompted for the location of where the file will be saved.
Connects to the remote ftp server (login, ip, file to GET all hard coded)
Displays a status bar of how much of the file has been downloaded.
Which Wi... |
User selects download and then is prompted for the location of where the file will be saved.
You've got the Common File Dialog for that. MFC has a wrapper.
Connects to the remote ftp server (login, ip, file to GET all hard coded)
There's the WinInet API, which includes function such as FtpGetFile
Displays a ... |
7,758,473 | 7,853,131 | How to compile a program to work on a 64 bit machine | I have a 32 bit application compiled on a Windows 2003 32 bit machine.
When I try to install it on Windows server 2008 or Windows 7, I get an error saying "Unable to start application 0xc0000142"
And, I am using Visual Studio 2008, and I tried setting the configruation ot x64, x86 and mixed platforms, but still not ge... | I was linking vss_uid.lib, psapi.lib and traffic.lib, all windows api libraries, and when compiled, it was packaging psapi.dll, vss.dll and traffic.dll into the program directory. On deleting those files, the program works perfectly now.
|
7,758,558 | 7,758,679 | Using -> for gsl_matrix structure pointer | I want to have a shortcut for assigning values to gsl_matrix data pointer, instead of writing gsl_matrix_set 16 times, but I can't get it to work. A small self-contained sample:
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
gsl_matrix* get_rates(double k) {
int nC... | double data[16] = {
-1, k/(k+2), 1/(k+2), 1/(k+2),
k/(k+2), -1, 1/(k+2), 1/(k+2),
1/(k+2), 1/(k+2), -1, k/(k+2),
1/(k+2), 1/(k+2), k/(k+2), -1};
memcpy(rates->data, data, sizeof data);
References:
http://www.gnu.org/s/gsl/manual/html_node/Matrices.html
http://linux.die.net/man/3/memcpy
|
7,758,627 | 7,758,714 | How can I read a video file for use in openCV? | I want to read a video file from an "avi file" and then enter it frame by frame to process it in openCV.
How can I do that?
Are there functions for that in openCV? Should I use a video reading framwork?
What are good frameworks for reading video files?
| Working with video sequences
Capturing a frame from a video sequence
Initializing capture from a camera:
CvCapture* capture = cvCaptureFromCAM(0); // capture from video device #0
Initializing capture from a file:
CvCapture* capture = cvCaptureFromAVI("infile.avi");
Capturing a frame:
IplImage* img = 0;
if(!cvGrabFra... |
7,758,641 | 7,759,535 | Augmented Reality: Render Video on top of a marker | I'd like to render a video (can be any format as long as it works) on top of a marker, but I am not sure how to do this. I am using Artoolkit for desktop-based AR and QCAR for mobile AR. Eventually I want to get it done for both systems, therefore I am preferably looking for a video-library that I could use on both pla... |
Which libraries could I use to achieve the first two steps?
Take a look into the libavcodec library (you can start here), but take into account that it is quite complex.
|
7,758,822 | 7,758,947 | Overloading the Subscript[] operator in C++ to set the size of a class(quantifier). | Good day guys.
I have the following struct and class,
template <class T>
struct Node
{
T DataMember;
Node* Next;
};
template <class T>
class NCA
{
public:
NCA();
~NCA();
void push(T);
T pop();
void print();
void Clear();
private:
Node<T>* Head;
... | If the compiler were to allow you to use brackets in your object constructor, how would it know whether you were trying to make an NCA of size 30 or an array of 30 NCA objects? C++ does not allow you to override the bracket syntax, except as an operator once you already have an object.
|
7,758,950 | 7,760,133 | Firebreath how to know if my method is called without debugging | I am using Objective-C++ in my firebreath project. The problem is that I am using Xcode 4 and I can not find the way to debug my project. So I have thought about if my method is been called from the web page.
Here is my source code:
In my OpenOnDesktopPluginAPI.h class:
class OpenOnDesktopPluginAPI : public FB::JSAPIAu... | I'll repeat what I said on the forum when you ask; perhaps you haven't seen that answer yet:
First of all, you can debug with Xcode4, at least on some browsers; the trick is figuring out which process to connect to.
Secondly, you can always use NSLog to log things to the console. Thirdly, you could use log4cplus (see ... |
7,759,126 | 7,759,158 | Sizeof Pointer to Array | If I have an array declared like this:
int a[3][2];
then why is:
sizeof(a+0) == 8
whereas:
sizeof(a) == 24
I don't understand how adding 0 to the pointer changes the sizeof output. Is there maybe some implicit type cast?
| If you add 0 to a, then a is first converted to a pointer value of type int(*)[2] (pointing to the first element of an array of type int[3][2]). Then 0 is added to that, which adds 0 * sizeof(int[2]) bytes to the address represented by that pointer value. Since that multiplication yields 0, it will yield the same poin... |
7,759,246 | 7,759,474 | C++ iterator to const_iterator | How do I acquire a const_iterator (of some container class) from an iterator (of that container class) in C++? What about a const_iterator from an insert_iterator? The resulting iterator should point at the same spot as the original does.
| Containers are required to provide iterator as a type convertible to const_iterator, so you can convert implicitly:
Container::iterator it = /* blah */;
Container::const_iterator cit = it;
std::insert_iterators are output iterators. This gives no way to convert them to a regular Container::iterator which must be a for... |
7,759,508 | 7,760,534 | How to pass a function in parameter with Boost::Phoenix? | It's my first post here so plese be kind if I don't respect the "ways and customs" :)
I'm new using Boost::Phoenix and I want to pass a function to a methods defined like :
template <typename Selector>
Result Greedy (
const t_Capacity& capacity,
BTSSet stations,
BTSSet startSet) ... | You have three issues:
boost::phoenix::function<> is lazy, so it must be evaluated twice in order to get an actual result.
rouletteWheelSelector::operator() must be const in order to be used by boost::phoenix::function<>.
sel is capturing stations by value, and consequently returning an iterator into a destroyed set; ... |
7,759,512 | 7,761,266 | TBB task_groups without using stack | I would like to perform a post-order tree traversal in C++. The tree can be so deep that I cannot use recursion (it exhausts the stack). Instead I create an std::stack<...> that puts everything on the heap, and traverse the tree in a while loop rather than with function calls. This works great.
Now I would like to para... | From TBB documentation (about implicit continuation):
Because the parent blocks, its thread’s stack cannot be popped yet.
The thread must be careful about what work it takes on, because
continually stealing and blocking could cause the stack to grow
without bound.
This is not exactly about that, but it shows th... |
7,759,590 | 7,759,613 | conversion from `double' to non-scalar type requested and some other errors | Please read my code, and help me to debug it. because Dev-C++ finds a lot of errors....
#include<iostream.h>
#include<conio.h>
using namespace std;
struct iWorker{
double salary;
}
double calSalary(iWorker worker){
double money = worker.salary;
return money;
}
int main(){
iWorker worker;
cout... | You're missing a ; after your struct declaration:
struct iWorker{
...
}; // <- this one here
|
7,759,645 | 7,759,828 | How do I convert a cli::array to a native array from native code? | I'm writing a native wrapper around a managed component written in C++\CLI.
I have the following function in managed code:
array<Byte>^ Class::Function();
I want to expose this function from a native C++ class with the following signature:
shared_array<unsigned char> Class::Function();
I've gotten as far as calling t... | There are two usual approaches:
Perform the marshaling with native code, which requires use of pin_ptr<>:
boost::shared_array<unsigned char> convert(array<unsigned char>^ arr)
{
boost::shared_array<unsigned char> dest(new unsigned char[arr->Length]);
pin_ptr<unsigned char> pinned = &arr[0];
unsigned c... |
7,759,673 | 7,761,283 | Alternatives to Windows 7 device ContainterIDs | How would I identify which devnodes belong to a single physical device in earlier version of windows?
EDIT:
The reason I would like to do this is because implementing an event system that broadcasts removal events when a device is removed would otherwise require said system to produce more events than necessary for som... | You can discover this relationship using the CM_Get_Parent function.
|
7,759,695 | 7,861,130 | Terrible performance with QMediaPlayer and QVideoWidget | I see a terrible performance while trying to play videos with QtMobility 1.2.0 and Qt 4.7.4 on Ubuntu 10.10 (Pentium 4 2.80GHz).
What's funny is that totem (which also use gstreamer as backend) and vlc are able to play these videos without a problem on this machine, even with higher resolutions (fullscreen, etc).
Acco... | There is nothing wrong with your code, you are just passing the ball to Qt for the decoding and playback of the movie.
You are either using a build of Qt that doesn't have hardware acceleration enabled, or your system doesn't have the proper hardware for Qt to accelerate decoding and playback.
|
7,759,738 | 7,761,949 | Best way to detect key presses without SDL or GLUT? | I've recently created a small application using OpenGL and GLUT via C++.
Everything was working great, and then I implemented a proper game loop with framerate and the like, and this made a lot of things better, however it also seemed to break the regular GLUT keyboard detection (which never seemed great for game keybo... |
so now I'm looking for a decent method of keyboard input in my application.
No, you're looking at not using GLUT anymore.
On Windows at least, your ability to get input is directly tied to your window. If you don't have a window of some kind, you don't have input (the console is itself a window). And more importantly... |
7,759,777 | 7,767,372 | Is it possible to test "internal" class from a c++ dll using MSTest? | We are currently trying to add unit testing to our c++ application. The application is made of 30 projects that generate 29 dll and 1 exe. We use MSTest to run our unit test since it's already included in Visual Studio 2010.
It works great for class that are declared "public". These class have this at the beginning:
#i... | There is no way, whether you're a unit testing framework or something else, to test code that you can't see. A DLL on Windows only exports symbols which have __declspec(dllexport) defined. Any other symbol is treated as internal when the DLL is compiled, and won't be visible to code using the DLL.
This is important be... |
7,759,803 | 7,802,206 | Rendering part of a bitmap using Direct2D | I'm in the process of converting a custom CAD software from GDI to Direct2D. I'm having issues when panning the drawing. What I would like to do is to create a bitmap that's 3x as wide as the drawing window & 3x as high. Then, when the user begins to pan, I would render the part of the bitmap that should be visible.
Tr... | Sorry for the trouble - the code above works OK. The problem was elsewhere in my codebase.
Not sure how to mark this question as "Nevermind," but that's likely what it should be.
|
7,759,827 | 7,815,311 | Python and Dynamically Extending C++ Classes | So I'm running into a problem with my custom types, functions and attributes in Python.
When I'm in Python, and I want to set an attribute on one of my custom types (for example Vector4), my code gets a NULL for the const char* attribute_name argument (and yes, I am importing my module).
Oddly enough, when I hard code... | The problem was in my implementation of getattro.
|
7,759,874 | 7,760,065 | Weird bug with WndProc and DispatchMessage. Member Functions don't exist? | So a bit of a weird bug going on when getting a WM_KEYDOWN msg in my Window class.
I have a Global WndProc function that determines which window instance it is and sends the message to it's own local WndProc function.
//Every Windows Message will hit this function.
LRESULT CALLBACK GlobalWndProc(HWND hwnd, UINT msg, W... | I would be guessing that you have wrong pointer obntained from GetWindowLongPtr, as it was not set by SetWindowLongPtr. As I wrote in my comment, you should not test if it's empty (I have no idea what is there by default but i wouldn't assume anything.), but set it when you recieve WM_CRERATE (which is guaranteed to be... |
7,760,198 | 7,770,707 | Should an empty base class affect the layout of the derived class? | The C++ standard (quoting from draft n3242) says the following about subobjects [intro.object]:
Unless an object is a bit-field or a base class subobject of zero
size, the address of that object is the address of the first byte it
occupies. Two distinct objects that are neither bit-fields nor base
class subobjec... | Expanding on my earlier comment:
An object is identified by its address. If you compare the addresses (like pointers) of two objects of the same type and they compare equal, the pointers are considerd to point to the same object.
Objects of different types cannot be compared directly this way, so they are allowed to ha... |
7,760,291 | 7,760,316 | Default initialization of C++ Member arrays? | This is a simple question, but I can't seem to find a definitive answer.
If we have the following class:
class Test
{
...
char testArray[10];
...
};
When we create an instance of Test, what is the default value of testArray[1]?
If it was a local array, it would be uninitialized.
If it was a static array, it would ... | From the standard, section 8.5 [dcl.init]:
To default-initialize an object of type T means:
if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
if T is an array type, each element is default... |
7,760,506 | 7,760,518 | C++ escape code parameter | I am looking at some code from one of our customers and found this function parameter I've never seen before:
some_function('ESFc');
In the debugger I set the value to
char c = 'ESFc';
and it equals 99
He also is using 'ESSc', 'ESCm' and 'ESBd' which eval to 99, 109 and 100
What is this? Is it some kind of escape cod... | It's a multi-character literal, but its value is not 99. The type of 'ESFc' is actually an int, and when you store it in a char it loses precision. See this question:
What do single quotes do in C++ when used on multiple characters?
|
7,760,605 | 7,777,425 | cmake/ctest: is it possible to use the creation of build targets as tests? | I have a program which reads a description of a file format (ISO 10303-11 for the curious) and generates c++ from it. The generated code is compiled into a library, and the library is linked with various executables to read/write that file format.
I have CMake set up to build the generator program and generate librarie... | If you are using a recent enough version of ctest (most recent official release is 2.8.6) then you can use the NAME/COMMAND signature of add_test, in conjunction with the cmake --build command line option, to build specific targets in your build tree.
For example, the following should work, assuming a custom target (or... |
7,760,678 | 7,761,045 | Is there a bitset class that's sized at instantiation time, but avoids boost::dynamic_bitset<>'s extra allocation call? | Is there a convenient analog of std::bitset<> that's dynamically sizable at instantiation time, but avoids the extra allocation required by boost::dynamic_bitset<>
You can create dynamically sized bit sets easily in C by doing something like :
typedef struct { node_t node; block_t bits[0]; } node_bitset_t;
p = (node_bi... | It would be possible to create such a class using placement new, but I'm not aware of a preexisting class which does this. The class wouldn't be instantiated directly but would be built via a factory; the factory method would use new to allocate the number of bytes necessary, then use placement new to initialize the ob... |
7,760,718 | 7,762,137 | OpenCV background subtraction/codebook? | Im trying out the codebook method, but don't really understand the point of int t in a code_book struct. Its the variable used to "Count every access", but this completely lost me. Count what access to what? By whom? Could someone please explain the purpose of the member variable to me? Please try to use non-technical... | I assume you are talking about this section of code from the OpenCV book:
typedef struct code_book {
...
int t; // Count every access
} codeBook;
Basically, you can think of the t field as a tick count each time a new frame is added to the code book. It used to determine how long it has been from the start of the ... |
7,760,868 | 7,760,917 | C++ Storing the product of two random numbers | C++ question this time.
I'm trying to store the product between two random numbers... It's supposed to be asking what the product between two random numbers that generate based on srand(time(0)), and quitting after -1 is entered...
The following is my code:
#include <iostream>
using std::cout;
using std::cin;
using std... | You shoud pay attention to operator precedence. Modulo operator % has the same precedence as multiplication *. Therefore when you write
rand()%10 * rand()%10
c++ will interpret that as
((rand()%10) * rand()) % 10
in other words the last modulo is applied to the result of everything else.
If you want to multiply two r... |
7,761,010 | 7,761,050 | c_str() == NULL not working | I was going through legacy code to fix a problem and found out that checking c_str in the following manner does not work. However if I change the comparison to string.empty() it works. So my problem is solved, but I am not sure why the c_str comparison does not work.Any idea why?
Thanks!
I am using - gcc version 4.1.2 ... | a is not null in this case. The string object has an internal pointer, which is not null, and that pointer is what c_str returns.
To verify this, try
printf("%zu\n", a.c_str());
and you will get a real address.
|
7,761,182 | 7,761,220 | Why are applications so large? | I made a complex hand detection software and it totals only around 28KB storage. I have around 600 lines of code and only have 28KB. How do other software programs manage to get so big (i.e. couple of Gigabytes). I mean I understand why games are big, but I couple of days ago I found a simple picture viewer that was ar... | It depends - what they were made with, how efficient the programmer was, and probably most importantly, the resources. Your hand detection program is probably mostly algorithms, right? Common software might include things such as localization (I know Notepad++'s huge size owes mostly to its 72-or-some languages and var... |
7,761,327 | 7,761,338 | C++ function declaration | I was looking into some C++ tutorial and encountered a function declaration inside the class
class CRectangle {
int x, y;
public:
int area (void) {return x*y;}
};
Now I am wondering what is the use of void after int area?
| void in this case means that the function doesn't take any parameters.
Also - syntax error, you probably meant {} brackets and you had the semicolon in the wrong place.
int area (void){ return (x*y); }
|
7,761,505 | 7,761,731 | Is it possible using macros to process defines contents? | I am currently working with JNI (Java Native Interface) to send data between Java and C++. After implementing a little of code I realized the code for each method was always similar. An example could be:
JNIEXPORT void JNICALL Java_com_trial_jni_Receiver_setData__II(JNIEnv * env, jobject thiz, jint nativeObject, jint v... | Well, the link you provided pretty much gives you the solution you need. Consider this:
#define CONCATENATE(arg1, arg2) CONCATENATE1(arg1, arg2)
#define CONCATENATE1(arg1, arg2) CONCATENATE2(arg1, arg2)
#define CONCATENATE2(arg1, arg2) arg1##arg2
#define JNI_TRANSLATE_TYPE_jint I
#define JNI_TRANSLATE_TYPE_jstring... |
7,761,527 | 7,761,536 | Passing static method as argument, no address-of operator required? | class ThreadWorker
{
public:
ThreadWorker(void);
virtual ~ThreadWorker(void);
static void DoSomething();
};
int main()
{
boost::thread thread1(ThreadWorker::DoSomething);
boost::thread thread2(ThreadWorker::DoSomething);
boost::thread thread3(&ThreadWorker::DoSomething);
}
I'm playing around... | It effectively does not matter. Functions (free functions and static member functions, not non-static member functions) decay to function pointers. No way is more correct than the other, I happen to prefer the explicit one though.
C++11 Standard, 4.3/1:
An lvalue of function type T can be converted to a prvalue of typ... |
7,761,620 | 7,761,704 | application keeps receiving segmentation fault - except if i add a for loop | Hi everyone: Here i have created a queue from two stacks: You add to the one and remove from the other - when you want to remove the first stack dumps all its data into the second one, and it works perfectly - BUT
whenever i try to execute this loop without the bottom for loop or cin
the program receives a segmentation... | delete this;
*this = TempStack;
There are some extreme corner cases in which delete this; actually does the right thing. This is not one of them. Specially since your Queue is placed in the stack, and you further try to delete it. If you intend to call the destructor instead do this->~Queue(), however after a ... |
7,761,676 | 7,761,711 | calling constructor of a class member in constructor | Can I call constructor of a member in my Class's constructor?
let say If I have a member bar of class type foo in my class MClass. Can I call constructor of bar in MClass's constructor? If not, then how can I initialize my member bar?
It is a problem of initializing members in composition(aggregation).
| Yes, certainly you can! That's what the constructor initializer list is for. This is an essential feature that you require to initialize members that don't have default constructors, as well as constants and references:
class Foo
{
Bar x; // requires Bar::Bar(char) constructor
const int n;
double & q;
public:... |
7,761,810 | 7,762,094 | GCC optimization trick, does it really work? | While looking at some questions on optimization, this accepted answer for the question on coding practices for most effective use of the optimizer piqued my curiosity. The assertion is that local variables should be used for computations in a function, not output arguments. It was suggested this would allow the compi... | The example given in that answer was not a very good one because of the call to an unknown function the compiler cannot reason much about. Here's a better example:
void FillOneA(int *array, int length, int& startIndex)
{
for (int i = 0; i < length; i++) array[startIndex + i] = 1;
}
void FillOneB(int *array, int le... |
7,761,816 | 7,761,852 | stringstream causes link error? | I have the following class:
#ifndef CGE_NET_MESSAGE_PARSER_HPP
#define CGE_NET_MESSAGE_PARSER_HPP
#include "Game/platform.hpp"
#include <vector>
#include <string>
#include <sstream>
namespace cge
{
class NetMessageParser
{
static std::stringstream ss;
static void clearStream();
public:
... | You have to declare storage for static variables in the CPP file. You probably want something like this
std::stringstream NetMessageParser::ss;
Oh and do not put this in header file otherwise you will get errors about multiple definitions
|
7,761,875 | 7,762,053 | Is there a way to hook mouse events for a specific button in a windows form | I want to hook the WM_MOUSEDOWN and WM_MOUSEUP events from a specific button inside a specific window. I am thinking that SetWindowsHookEx will hook the messages I want. and FindWindowEx will help me find the window handle that I want to trap these events from.
I just don't know how to make it give me the Events from s... | You can't make SetWindowsHookEx only give you thew events from a single window handle, but you can filter it yourself. If you are using the WH_CALLWNDPROC or WH_CALLWNDPROCRET (which you need to use to get the mouse messages you are interested in), the lParam value of CallWndProc and CallWndRetProc are a structure tha... |
7,761,927 | 7,761,946 | C++ Compare Method within a Class | while(getline(INPUT,textLine))
{
Object* s = new Object(textLine);
}
How would I hold a reference to the Object of the previous textLine so that I could compare the two in some compare method
s.Compare(***); <-- comparing the second iteration to the first
Note that *** is of type Object
| You want to keep track of the previous instance of Object?
Put it in a variable (called t below), and use the variable when you need it.
Remember to delete everything you allocate.
Object* s;
Object* t = NULL;
while(getline(INPUT,textLine))
{
s = new Object(textLine);
s->Compare(t);
delete t;
t = s;
... |
7,761,974 | 7,762,159 | Non-recursive merge sort with two nested loops - how? | First question here, and yes this is a homework question. We are tasked with performing merge sort on an array (which I am familiar with), but in a way I am unsure of how to do. Usually I would have a separate merge and merge sort function, and use the two. However, it sounds like he wants everything in one method? I w... | It's not so difficult. Consider the recursive merge:
+-+-+-+-+-+-+-+-+
| | | | | | | | |
+-+-+-+-+-+-+-+-+
/ \ split
+-+-+-+-+ +-+-+-+-+
| | | | | | | | | |
+-+-+-+-+ +-+-+-+-+
/ \ / \ split
+-+-+ +-+-+ +-+-+ +-+-+... |
7,762,085 | 7,762,179 | Difference between a struct and a class |
Possible Duplicate:
What are the differences between struct and class in C++
I've done my homework and had diverse answers on Google.
Some say structs do not have inheritance, some say structs do not have access specifiers, while others say they have both.
Could someone clarify then, the differences between a struct... | In C++, the only difference between a struct and a class is that struct members are public by default, and class members are private by default.
However, as a matter of style, it's best to use the struct keyword for something that could reasonably be a struct in C (more or less POD types), and the class keyword if it u... |
7,762,145 | 7,762,263 | Game does not finish when I get to 100 points for computer | It is strange, I coded my pig game here in c++ which once the user or computer reaches 100 he wins. But the problem is if I keep rolling and I go past 100 I don't win unless I hold after I get there. And the computer if it gets close to 100 around 80 to 100 it will just say it wins. I don't understand whats going on he... | Try it this way :
do
{
if((humanTotalScore < 100) && (computerTotalScore < 100))
continuePlay = true;
else
continuePlay = false;
{
humanTurn(humanTotalScore);
computerTurn(compu... |
7,762,266 | 7,763,498 | Marshalling unmanaged unicode string to .net. High chars replaced with question marks | This may or may not be a SWIG question.
I am trying to return a std::wstring by value from a C++ function to C#. The returned string has a mixture of plain old English chars and Hebrew chars. The English chars come through fine, but the Hebrew chars are being converted to the question mark symbol at some point.
I am ... | Modify the CreateWString definition to:
[return: MarshalAs(UnmanagedType.LPWStr)]
static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString)
See the examples in the MarshalAsAttribute documentation.
|
7,762,296 | 7,762,341 | C++ Error C2447? What am I missing | I don't know if I'm going crazy, or just that everything I've read on this error doesn't apply to my situation. But I'm getting these errors when I compile my project:
1>f:\program files\testengine\testengine\testengine\game.cpp(10) : error C2061: syntax error : identifier '{ctor}'
1>f:\program files\testengine\testeng... | You need to write CGame::~CGame() instead of ~CGame::CGame() for the destructor. It's always the class name first (CGame) and only then the member name (~CGame).
|
7,762,452 | 7,762,492 | Can i point to a specific location in a function? | Say i have this main int
int main();
{
cout << " Hello! ";
function1();
cout << " BYE!";
}
Is there a way to make it so once im done with the function1 to make it just point to the top of 'cout << " BYE!";' so i dont have to go through Hello again? Basically i want to just point the end of function1 to the top of... | when ever a function is completely executed. The c++ pointer tries to execute the statement which comes after the function. However if you want to point to some specific location you can use the statement
Goto to go to a specific label let us say abc:
int main();
{
cout << " Hello! ";
function1();
Goto label
...... |
7,762,672 | 7,762,704 | tr1::array in C++ deleting all elements | how to delete all elements of a std::tr1::array?
For example I have defined the following array.
std::tr1::array <int, 5> a = { 1, 2, 3, 4, 5}
Just like in vectors I am looking for a method such as a.clear() or a.erase() but couldn't find one for arrays.
Thank you
| arrays are static size, you can neither add nor remove elements, that's what vector is for.
|
7,762,739 | 7,762,746 | Have you ever written a header without guards? | I am wondering why C++ compilers don't generate header guards automatically for headers?
// Why do I have to write this for every .hpp file I create?!!
#ifndef myheader_hpp__
#define myheader_hpp__
// ...
#endif
I haven't met a situation where they aren't needed when I write my headers. I can't see a real use-case of ... | There are some preprocessor tricks that require the same header included multiple times into the same compilation unit. Another reference.
Besides that, most compilers do allow you to shorten all of that down to:
#pragma once
|
7,762,836 | 7,762,872 | Sending data over TCP between Java and C++ | I have an application that constantly fetches input in Java from a frame buffer and sends it over the wire to a C++ application.
I am having issues on the receiver side. I am trying to send one packet (or at least let TCP reconstruct it as a single packet) for each frame buffer. The frame buffer is getting splitted int... | You don't have control over TCP frame sizes. Network devices can and do fragment packets so that you will receive more packets than you sent.
The word "stream" is used for a very good reason. You are getting a stream of bytes but there is no framing unless the sender and receiver application impose framing on the stre... |
7,762,840 | 7,763,228 | error: variable or field declared void | This is actually the program my instructor had provided with us to work with, i had to make several changes thus far to get it to at least compile:
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <cctype>
#include <cstdio>
#include <string>
#include <list>
usi... | Okay, so you need to make a few changes to your instructor's sample to get it to compile.
I'm going to assume you've included the four headers needed to compile. I recommend you pull in just the following four symbols from the std namespace, rather than the whole lot. Personally I prefer to refer to std::string in my c... |
7,762,873 | 7,762,908 | Call a class function from within a child class | Suppose an object of class B is a member of class A.
class B{
//Definitions
}
class A{
public:
A();
B b_child;
int some_function();
}
One of the functions defined inside B needs to call a (public) function from its owner (parent?) A. Is there an immediate way to do this?
The only way I've managed to ... | There is no builtin method to get the 'owner' of a variable, whatever that means. Your approach of setting the owner is correct. Furthermore, doing so in the construction of B is also a correct decision. Sample code:
class B
{
public:
explicit B( A* owner ) : _owner( owner ) {}
...
private:
A* _owner;
};
... |
7,762,929 | 7,762,964 | Safety of casting between pointers of two identical classes? | Let's say I have two different classes, both represent 2D coordinate data in the same internal way like the following:
class LibA_Vertex{
public:
// ... constructors and various methods, operator overloads
float x, y
};
class LibB_Vertex{
public:
// ... same usage and internal data as LibA, but wit... | C++11 added a concept called layout-compatible which applies here.
Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9).
where
A standard-layout cla... |
7,762,988 | 7,763,009 | Side effects when passing objects to function in C++ | I have read in C++ : The Complete Reference book the following
Even though objects are passed to functions by means of the normal
call-by-value parameter passing mechanism, which, in theory, protects
and insulates the calling argument, it is still possible for a side
effect to occur that may affect, or even dama... | That passage is probably talking about this situation:
class A {
int *p;
public:
A () : p(new int[100]) {}
// default copy constructor and assignment
~A() { delete[] p; }
};
Now A object is used as pass by value:
void bar(A copy)
{
// do something
// copy.~A() called which deallocates copy.p
}
void foo ()
{... |
7,763,080 | 7,763,112 | Host for socket programming | I am studying socket programming. So far, I was able to do it on local host. However, is there an online hosting with shell access, so I can put my practice into real environment?
I heard cloud service like http://www.heroku.com/ allow shell access, though I never try it before.
| If you just want to mess around a bit while you learn something, I would recommend Amazon AWS you can deploy a VM running any OS you want in a few minutes. It is also a great skill to put on a resume and its free if you don't use it much:
http://aws.amazon.com/free/
|
7,763,321 | 8,897,187 | libpcap to capture 10 Gbps NIC | I want to capture packets from 10Gbps network card with 0 packet loss.
I am using lipcap for 100Mbps NIC and it is working fine.
Will libpcap be able to handle 10Gbps NIC traffic?
If not what are the other alternative ways to achive this?
| Whether or not libpcap will handle 10Gbps with 0 packet loss is a matter of the machine that you are using and libpcap version. If the machine, CPU and HDD I/O are fast enough, you may get 0 packet loss. Otherwise you may need to perform the following actions:
Update your libpcap to the most recent version. Libpcap 1.... |
7,763,397 | 7,763,413 | c++ pass a map by reference into function | How can I pass a map by reference into a function? Visual Studio 2010 is giving me an unresolved externals error. Currently, I have the following simplified code:
void function1(){
map<int, int> * my_map = new map<int, int>();
function2(*my_map);
}
void function2(map<int, int> &temp_map){
//do stuff wit... | Two things:
Add #include<map> at the top, and use std::map instead of just map.
Define function2 above function1 Or at least declare function2 above function1.
Here is how both should be done:
#include<map>
void function2(std::map<int, int> &temp_map); //forward declaration
void function1(){
std::map<int, int> ... |
7,763,451 | 7,763,513 | Thread with and without a memory leak | I'm stuck with a c++ assignment where I should make a simple thread and another thread that has the same logic but also have a memory leak.
This should just be an easy thread example, even not doing anything useful in itself. So I guess my question is, what is the easiest thread that can be made in c++ and if I have un... | This would be enough for a leak:
new char;
You can place it in a loop if you want more, but be careful -
while( true ) {
new char;
}
brings most systems to a halt quite quickly - they start swapping and become barely usable. IMO you should stick to leaking a couple of objects unless you have other specific requi... |
7,763,474 | 7,763,805 | How can we identify a unique nsHTTPChannel? | I am doing some development on the firefox both with javascript and C++ for some XPCOM components.
I am trying to monitor the http activity with nsIHttpActivityDistributor.
The problem now is , is there any flag or id that belong to nsIHttpChannel that I can use to identify a unique nsHttpChannel object?
I want to sa... | You can easily add your own data to HTTP channels, they always implement nsIPropertyBag2 and nsIWritablePropertyBag2 interfaces. Something along these lines (untested code, merely to illustrate the principle):
static PRInt64 maxChannelID = -1;
...
nsCOMPtr<nsIWritablePropertyBag2> bag = do_QueryInterface(channel);
i... |
7,763,546 | 7,769,342 | Connection to Postgres Database using libpqxx | I am using libpqxx to connect to a postgres database by creating a class.
class databaseConnection
{
public:
pqxx::connection* conn;
void SetConnection(){
conn=new pqxx::connection(
"username=temp "
"host=db.corral.tacc.utexas.edu "
"password=timelione "
"... | pgxx::connection(const PGSTD::string&) is basically a wrapper around libpq's PQconnectdb() function, so the supported connection parameter keywords are the same as for libpq.
The parameter key word for the PostgreSQL user name to connect as is user, not username. Perhaps correcting that will fix the problem.
Also, in y... |
7,763,611 | 7,763,706 | Sending object over network or saving into hard disk | class shape {};
class circle: public shape {};
class square: public shape {};
class doc {
shape* ar[3];
doc() {
createShape();
}
shape* appendShape();
};
doc d;
I need to save this object d into hard disk as binary format or send this data over network so that other program can populate this o... | I guess you are looking for object serialization. You might want to take a look at the Boost Serialization library. It can be used to save your objects to a file or a binary stream that could be sent over the network. It also can serialize your objects into an XML representation.
|
7,763,617 | 7,763,631 | Not copyable object and exception in copy constructor and operator= | I'd like to make object of class not copyable so I put copy constructor and operator= in private section. However one class is friend of this class so it has access to private methods. Is it good idea to put throw exception in copy constructor and operator= to be sure that object will not be copied?
| One approach to make it not copyable is just to declare the copy constructor, but don't implement it at all. That will force a linker error at compile time if anyone tries to use it.
class foo
{
private:
foo(const foo&); // not defined
foo& operator=(const foo&); // not defined
};
|
7,763,676 | 7,763,721 | How to solve the "unresolved external symbol" link error in visual c++? | I Have the Visual Studio C++ 2008 Express Edition.
I am trying to compile a program but I am getting the following Link Error:
1>MSVCRT.lib(wcrtexew.obj) : error LNK2001: unresolved external symbol _wWinMain@16
What I tried to do:
I found this on google:
For Visual C++ .NET: In the Advanced category of the Linker fold... | There are multiple ways to solve this:
Create a console application
Change the Subsystem console now in the linker settings ( Project Settings -> Linker -> System -> SubSystem (select Console))
Change the entry point in the linker settings to mainCRTStartup (Project Settings -> Linker -> Advanced -> Entry Point)
Defin... |
7,763,800 | 7,763,994 | NACHOS C++: Thread Fork to create data structures | I have a program that runs perfectly well when I have declare and initialize my List data structure at the top and then call my function generateID . It also works if I declare the List at the top and initialize the List inside the function. However the problem I am having is using threads to create the List. I keep ge... | After you Fork the new thread, generateID() is executed immediately: the thread may not have started yet or it could be in the middle of the creation of the list.
Maybe generateID() should be the function in the different thread and the creation of the list should be in the main one.
|
7,763,802 | 7,763,825 | Why can't a class have same name for a function and a data member? | Why can't a c++ class have same name for a function and a data member?
class demo{
public:
int size();
private:
int size;
};
int main(){
return 0;
}
C:\Users\S>g++ demo.c
demo.c:5:7: error: declaration of 'int demo::size'
demo.c:3:7: error: conflicts with previous declaration 'int dem... | Suppose you want to take the address of the member-function size(), then you would write this:
auto address = &demo::size;
But it could be very well be the address of the member-data size as well. Ambiguous situation. Hence, it is disallowed by the language specification.
That is not to say that it was impossible for ... |
7,764,029 | 7,765,047 | Boost property_tree for storing pointers | Is it possible to store pointers to objects in boost property trees, and then use an iterator to retrieve the data? I'm trying to do something like:
property_tree::ptree pt;
pt.put<CGUICrateElement*>("1.2.3.4", new MyObject() );
//... more tree construction here...
and then recursively itererate through all the tree n... | Adding an operator>> for a reference to MyObject won't help when you're actually trying to lexical_cast to a pointer to MyObject. You could conceivably create an operator>>(std::istream&, MyObject*&). However, remember that property_tree is designed for reading configuration from text files, so you'll have the joy of c... |
7,764,271 | 7,764,304 | Compilation issue equality/inequality operators | I have the following code sequence And I don't understand the compilation error (below the code).
Thanks in advance,
Iulian
class X {
public:
int a;
X()
{
a = 0;
}
bool operator == (const X&r)
{
return a == r.a;
}
bool operator != (const X&r)
{
return !( ... | You need to declare your operator== and operator!= functions as const.
Eg.
bool operator == (const X&r) const
|
7,764,323 | 7,764,450 | How to use the += function in a namespace | How can correctly use this '+=' function if the function is declared within a namespace?
namespace WinFile
{
std::stack <tstring> operator += ( std::stack <tstring>& s1, std::stack <tstring> s2 )
{
// Post:
if ( s1 == s2 )
{
return s1;
}
while ( !s2.empty() )
{
... | As already suggested you can use a "using" clause:
using WinFile::operator+=;
or
using namespace WinFile;
or you can use the function directly with the following code:
s1 = WinFile::operator +=( s1, s2 );
None of which are particularly ideal, but there are no other ways, to my knowledge, to do it.
|
7,764,326 | 7,765,002 | Weird behaviour of gcc 4.6 compiler | This code:
template<class Int_T, long long Min, unsigned long long Max>
class Int_Core
{
static_assert(Check_Range<Minimum>::check(Min,std::numeric_limits<Int_T>::min()),"INCORRECT Min range.");
static_assert(Check_Range<Maximum>::check(Max,std::numeric_limits<Int_T>::max()),"INCORRECT Max range.");
}
The error I'm ... | It is a compiler bug in gcc 4.6.0, gcc 4.6.1 correctly triggers the static_assert.
|
7,764,417 | 7,764,786 | WaitForSingleObject and while loops in C/++ | Here is the snippet:
prog1:
HANDLE hM;
hM = CreateMutexA(NULL,TRUE, "abc"); // I have to use TRUE otherwise WaitForSingleObject fails.. by design it wants to take ownership and w//o TRUE there is no owner anyway right? <<-- **check this please if its true**
...
prog2:
HANDLE hM;
hM = OpenMutexA(MUTEX_ALL_ACCESS,NULL, ... | To detect process crash, you shouldn't bother with a mutex. Just wait on the process handle. Once the process exits, the handle will be signaled, and WaitForSingleObject will return.
If you're creating the process, you can get the process handle from the PROCESS_INFORMATION argument. Then, just use:
PROCESS_INFORMATION... |
7,764,546 | 7,764,744 | Is there analog in C++ for Python's file.read(2)? | I'm currently trying to make analog of Python's function:
def read_two_symbols(fdescr):
return(file.read(2))
myfile = open('mytext.txt', 'rb')
two_symbols = read_two_symbols(myfile)
print(two_symbols)
Is there any way to do it in C++? That's what I've tried:
#include <iostream>
#include <string>
#include <fstream>
... | @vivek has pointed out that you can't pass an fstream "by value". Passing things by value makes copies of them (or rather, runs their copy constructor, which may or may not actually make a "deep" copy of them).
Once you fix that, iostreams are actually cute and cuddly. They can detect the type you're asking for and r... |
7,764,564 | 7,764,680 | C++11 lambdas: member variable capture gotcha | Consider this code:
#include <memory>
#include <iostream>
class A
{
public:
A(int data) : data_(data)
{ std::cout << "A(" << data_ << ")" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
void a() { std::cout << data_ << std::endl; }
private:
int data_;
};
class B
{
public:
B(): a_(ne... |
Is this behaviour specified by the standard
Yes. Capturing member variables is always done via capturing this; it is the only way to access a member variable. In the scope of a member function a_ is equivalent to (*this).a_. This is true in Lambdas as well.
Therefore, if you use this (implicitly or explicitly), then ... |
7,765,040 | 7,765,174 | I can't get the string value of a token | I try to implement a Lexer for a little programming language with Boost Spirit.
I have to get the value of a token and I get a bad_get exception :
terminate called after throwing an instance of 'boost::bad_get'
what(): boost::bad_get: failed value get using boost::get Aborted
I obtain this exception when doing :... | You can always use the 'default' token data (which is iterator_range of the source iterator type).
std::string tokenvalue(iter->value().begin(), iter->value().end());
After studying the test cases in the boost repository, I found out a number of things:
this is by design
there is an easier way
the easier way comes au... |
7,765,239 | 7,765,302 | Polymorphic copy-constructor with type conversion | I need to copy-construct an object simultaneously changing it's type to another class being a member of the same class-hierarchy. I've read about polymorphic copy-constructors and (hopefully) understand the idea behind it. Yet, I still don't know if this pattern applies to my case and, if so, how to implement it. I thi... | Simplest solution would probably be to implement a Child2 constructor taking a Child1& as parameter. Then you could simply call:
Child2* c2 = new Child2(*c1);
|
7,765,732 | 7,765,837 | Boost shared pointers C++ : shared pointer unable to free resource on release | I'm running into a problem where I can't get rid of the last shared pointer and I kinda need it actually.
So what I have is a manager and some worker threads. The manager keeps a collection of shared pointers to different resources. A worker may ask the manager for a shared pointer to a resource. There will always b... | Why is the manager holding a shared_ptr (strong reference) to the object if it doesn't need to retain control, only pass it on? Not seeing your code, it seems like having the manager hold a weak_ptr and then pass that on to the workers, who lock it into a shared_ptr on their end. That will allow the manager to pass on ... |
7,765,750 | 7,765,893 | Can you avoid using temporary buffers when using std::string to interact with C style APIs? | I should preface this question by saying I think the answer is probably no, but I'd like to see what other people think about the issue.
I spend most of my time writing C++ that interacts with the Win32 API which like most C style APIs wants to either:
Take buffers which I've provided and operate on them.
Or return ... | In C++11 you can simply pass a pointer to the first element of the string (&str[0]): its elements are guaranteed to be contiguous.
Previously, you can use .data() or .c_str() but the string is not mutable through these.
Otherwise, yes, you must perform a copy. But I wouldn't worry about this too much until profiling in... |
7,765,795 | 7,765,848 | Render a texture to a window | I've got a dialog that I'd basically like to implement as a texture viewer using DirectX. The source texture can either come from a file on-disk or from an arbitrary D3D texture/surface in memory. The window will be resizable, so I'll need to be able to scale its contents accordingly (preserving aspect ratio, while not... | IMHO the easiest way to do this is to create a quad (or two triangles) whose vertices contain the correct UV-coordinates. The XYZ coordinates you set to the viewing cube coordinates. This only works if the identity matrix is set as projection. You can use -1 to 1 on both X and Y axes.
EDIT: Here an example turorial:
h... |
7,766,087 | 7,766,135 | Is it legal to modify the result of std::string::op[]? | Consider the following from C++11:
[C++11: 21.4.5]: basic_string element access [string.access]
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
1 Requires: pos <= size().
2 Returns: *(begin() + pos) if pos < size(), otherwise a reference to... | The quote means that you cannot modify the return of operator[]( size() ), even if the value is well defined. That is, you must not modify the NUL terminator in the string even through the non-const overload.
This is basically your first option: i.e. pos >= size(), but because of the requirement pos <= size() the only ... |
7,766,115 | 7,766,138 | print variable name in a #define | I am trying to print out to console using a macro the variable name for display members value while debugging ( logging ).
How to do that? I tried the following but it doesnt' work.
#define MY_PRINT(x) std::cout << "'x'=" << x << std::endl;
int main(){
int my_variable=3;
MY_PRINT( my_variable );
// I would li... | Auch... I found the solution.
I should write the macro like this
#define MY_PRINT(x) std::cout << #x"=" << x << std::endl
|
7,766,141 | 7,767,400 | What is C++ translation for Matlabs `fread(fp, 1, 'int32')` and fread(fp, n, 'uchar') | So I try to convert such Matlab code to C++:
ss = 'file.mask'
fp = fopen(ss, 'rb');
sx = fread(fp, 1, 'int32')
sy = fread(fp, 1, 'int32')
mask = zeros(sy, sx);
mm = mask(100, 100:200);
count = zeros(10, 1);
for i = 1:sy
row = fread(fp, sx, 'uchar');
for j = 1:sx
for k = 1:10
if row(j) ==... | If you really want a C++ analog and not a C analog (or even a C/C++ analog), then you should rather use std::ifstream:
std::ifstream in("file.mask", std::ios_base::in | std::ios_base::binary);
int sx, sy;
in.read(reinterpret_cast<char*>(&sx), sizeof(int));
in.read(reinterpret_cast<char*>(&sy), sizeof(int));
std::vecto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.