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 |
|---|---|---|---|---|
4,252,912 | 6,871,290 | Qt + protobuf, types? | I would like to dip into Google's protocol buffers in Qt development, but I am having trouble figuring out how to incorporate them best.
Ultimately, I want to send with QUdpSocket and QTcpSocket using protocol buffers.
What is the best method for going between a protocol buffer message to sending the data over a socket... | Instead of:
std::ostringstream out;
person.SerializeToOstream(&out);
QByteArray byteArray(out.str().c_str());
you can also write:
QByteArray byteArray(person.SerializeAsString().c_str());
EDIT: Above two gives the same result, but I'm not sure wether it's correct. This one seems to work better:
QByteArray byteArray(Q... |
4,252,935 | 4,253,076 | Qt/C++: Signal for when a QListWidgetItem is checked? | In my form I have a QListWidget which contains checkable QListWidgetItems. I'm looking for a way to capture the event of a QListWidgetItem being checked/unchecked. I don't see any such signal existing for this but maybe I'm wrong. What I'm currently doing is using the QListWidget::itemClicked() signal and checking the ... | Apparently no such signal is provided, your best bet is to use QListWidget::itemChanged(QListWidgetItem* item) , and scan the resulting item->checkState(). This should be a slight improvement over using itemClicked
|
4,253,106 | 4,253,116 | How can I return an array in C++ functions? | I am a C++ noob and I wanna know how can i return an array from a C++ function.
I tried the following code but doesn't seem to work.
char some_function(){
char my_string[] = "The quick brown fox jumps over the lazy dog";
return my_string;
}
| The reason that code isn't working is that the minute the function ends, so does the lifetime of the string you have created. Instead, if you're going to be working in C++ use std::string and return that.
std::string myFunc(){
return string("hey a new string");
}
For other arrays use std::vector, std::deque or on... |
4,253,158 | 4,257,369 | Trouble with structs, CUDA C/C++ and VS 2008 | Hey there... so I am here using VS2008, programming with CUDA C. I have the 3.2 toolkit installed and working.
Now my problem is, i have a file with this:
#ifndef _cuda_rng_cu_included_
#define _cuda_rng_cu_included_
#include <stdio.h>
static void HandleError( cudaError_t err,
const char *fi... | Files with the .cu extension are handled by nvcc which automatically includes the CUDA-specific headers such that the CUDA types are declared. When you name it .c/.cpp you need to include the relevant header to get the types. Since you're using the runtime API, try include cuda_runtime_api.h.
The fact that you're not f... |
4,253,164 | 4,253,550 | How to get hardware information in Windows using C++? | How to get hardware information (for example cpuId, biosId, diskId, baseId and videoId) in c++?
Can anyone give me an example visual studio project for this?
| There are very different ways to get a disk id (serial number? volume id?) or a CPU ID or ... . I think you want to build a fingerprint of the computer.
The most comfortable way is to use Windows Management Instrumentation (WMI) and access the DMI . See MSDN for a start.
See MSDN here for a hint how to get the mainboar... |
4,253,290 | 4,253,353 | How to read/write std::string values from/to binary files | I want to write an Item to a binary file, close it, and open it again to read it. The code is simple and straightforward, it compiled and ran without error using Visual Studio 2008.
However, it got 'segment fault' when running with the GCC compiler.
What am I doing wrong?
#include <iostream>
#include <fstream>
#inclu... | The two lines:
outf.write( reinterpret_cast<char *>( &temp ), sizeof( Item ) );
and
inf.read( reinterpret_cast<char *>( &temp ), sizeof( Item ) );
are wrong. You are writing the binary layout of the object, including std::string instances. This means you are writing the value of pointers to a file and reading them b... |
4,253,292 | 4,253,307 | passing objects as arguments | Can anyone give example about passing an object of a class as argument to the function of same class.
| class X
{
public:
void func(X x) {}
};
int main()
{
X a,b;
a.func(b);
}
|
4,253,441 | 4,254,760 | how to use an exported class (__declspec(dllexport))in an stl template? | I am using an exported class
class __declspec(dllexport) myclass
{
private:
template __declspec(dllexport) class std::map<myclass*,int>;
std::map<myclass*,int>m_map;
//something
};
When I do this, I get a warning C4251 saying m_map:class 'std::map<_Kty,_Ty>' needs to have dll-interface to be used b... | You should not be using __declspec(dllexport) into the header files that code using your DLL will be using, as they need to be using __declspec(dllimport).
Therefore you should create a macro that uses dllexport if a particular other define is set, and dllimport if it is not.
In a common header somewhere:
#ifdef EXPORT... |
4,254,059 | 4,469,207 | How to set a timeout for MySQL query using C API | I know there are lots of similar questions here, also there are lots of results, when I google it, but none of them answers my question. I read this, this, this and this but none of them works for me. I don't talk about any locks, I don't wanna do this using MySQL c++ connector, just the C API.
Also, what is very impo... | Okay, I found a solution.. Thanks to Will and PRR( my co-worker ).
I cannot start a new thread on each query, as this is a real-time application, that is supposed to process 1000+ messages per second..(anyway, thanks to R.. for the idea).
Also, it was not possible to terminate the connection through the library, nor t... |
4,254,250 | 4,276,580 | Embedded Database in Qt | I have a SQLite database for my Qt application. I assume that it would be logical to add the database as a resource.
I can't get my app to compile with the embedded resource.
connection.h
#ifndef CONNECTION_H
#define CONNECTION_H
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery... | Even if you solve you compilation problems, embedding a sqlite database in the qrc file will not work. See e.g. the discussion in the Qt Centre Forum or on the Qt-interest mailing list. The best solution would be IMHO to include a dump of a database in the qrc file, create a memory sqlite db and rebuild the database fr... |
4,254,315 | 4,254,980 | windows service in c++ | I want to make an application in c++ which will run periodically. much like an windows service. Is it possible to create a windows service in C++. If yes how?
Any tutorial for this?
EDIT: How can I create an installer for the Windows service?
| As indicated in another answer, you need to create a normal C++ program (starting with main), and call StartServiceCtrlDispatcher Win32 API to tell Windows that you want to run this program as a service. Some information on this function can be found in MSDN.
Additionally, you'll need a mechanism to install your servic... |
4,254,433 | 4,257,123 | problems using webkit libs in c# | I tried using this example to create a wrapper for the webkit library. But, when I try to use the method, in c#, from the compiled c++ dll, I get an "method inaccessible due to it's protection level" error.
The method I'm trying to get to is
CG_EXTERN CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void) CG_AVAILABLE_STAR... | There is a project called WebKit.NET: http://webkitdotnet.sourceforge.net/ Why not use it instead of reinventing the wheel?
|
4,254,460 | 4,254,630 | OpenCV - could not find encoder for the specified extension | Here is my code I am using to convert *IplImage to jpg:
IplImage* fIplImageHeader;
fIplImageHeader = cvCreateImageHeader(cvSize(160, 120), 8, 3);
fIplImageHeader->imageData = (char*) memblock;
vector<int> p;
p.push_back(CV_IMWRITE_JPEG_QUALITY);
p.push_back(10);
vector<unsigned char> buf;
cv::imencode("JPEG", fIplImag... | Ok. I've figured this out. This works:
cv::imencode(".jpg", fIplImageHeader, buf, p);
They should mention it somewhere in the documentation that there should be a full stop before extension.
|
4,254,609 | 4,256,488 | change order of elements inside linked list | I'm trying to use simple linked list:
struct index
{
struct index* next_element;
int data;
struct index* previous_element;
}
What is the best way to change order of elements in terms of performance?
For example, i have 1 2 3 4 5 6 7 8 and i need 1 4 2 3 5 6 7 8.
| It's hard to tell in general. It seems that you want to move element 4 after element 1. Do you have the index* for both? Or do you just know that the fourth element has to move by two places? This obviously affects the amount of listwalking you have to do.
In general, for maximum efficiency, you'd want a function
void... |
4,254,615 | 4,254,644 | How to cast vector<unsigned char> to char* | I have a buffer like this:
vector<unsigned char> buf
How can I cast it to char*?
If I do:
(char *)buf
I get this error:
/home/richard/Desktop/richard/client/src/main.cc:102: error: invalid cast from type ‘std::vector<unsigned char, std::allocator<unsigned char> >’ to type ‘char*’
For those wondering why I am trying ... | reinterpret_cast<char*> (&buf[0]);
The vector guarantees that its elements occupy contiguous memory. So the "data" you seek is actually the address of the first element (beware of vector <bool>, this trick will fail with it). Also, why isn't your buffer vector<char> so that you don't need to reinterpret_cast?
Update f... |
4,254,653 | 4,254,702 | How to get a virt size from C/C++? | Is there a simply way how to get the virt size of the Linux process from the C/C++ code? Thanks
| If you want to find out your the virtual size of own process you simply need to read /proc/self/status and find there the VmSize field
FILE* handle = fopen("/proc/self/status","r");
// and then read its conttent find the VmSize string and its value
If you want to know the virtual size of an arbitrary process then open... |
4,254,708 | 4,254,803 | C++:boost: pass by value parameter | I use smart pointer from Boost library. Suppose I have this object:
boost::shared_ptr<A> a(new A);
a->fileName = "/temp";
In the class B, I have:
bool open(A *a);
and
private: boost::shared_ptr<A> myA;
Then I declare an object B:
boost::shared_ptr<B> b(new B());
b->open(a.get());
bool B::open(A *a)
{
*B::myA = ... | If you use a smart-pointer pointer for an object once, you should use it for that object always. In your case, open should look like this:
bool B::open(boost::shared_ptr<A> a) {
myA = a;
}
This way you would have reference semantics for the object passed to open. Your code example tried to assign the object, not t... |
4,254,811 | 4,254,985 | memory management & std::allocator | In reviewing my code I see some "ugly" structure I use, in a class (called "map") I have a vector which contains a "data" class:
std::vector<PointerToHUGEClass> vector;
Where PointerToHUGEClass is just like the name describes. (though the object pointed too is also owned by the map class, and created with the "new" pa... |
Am I correct in assuming the allocator is responsible for the memory management from the items? (And making sure it is declared from stack/freestore/heap/whatever)
No you are not. The allocator is just sugar coating over new and delete and in general responsible of deciding where the memory will be allocated. The r... |
4,254,886 | 4,254,935 | Raw BGR image after JPG compression is the same length? | Ok. This is a bit odd. Long story short. I am fething raw BGR images from a camera, compressing them to JPG with OpenCV and sending with UDP protocol to a PC. This is how I compress images:
// memblock contains raw image
IplImage* fIplImageHeader;
fIplImageHeader = cvCreateImageHeader(cvSize(160, 120), 8, 3);
fIplImage... | The "size" you pass to send is the size of the compressed buffer, right? It's not obvious from your code snippets where "size" comes from (as ypnos suggests, I would have expected buf.size() ).
|
4,254,906 | 4,255,042 | Type requirements for std::map | Today I created a map, where the value type has no default constructor. I was surprised that I could not use operator[] to insert the elements to this map, but I had to use the insert method.
So, what exactly are requirements for the key and value types for std::map?
Here is short example :
#include <map>
struct A
{
... | operator[] does indeed require default-constructibility because the semantics of this method mandate that if the key doesn’t yet exist, an appropriate entry is created. Thus:
map<TKey, TValue> mymap;
TKey foo = …;
TValue& x = mymap[foo];
will create and store a new object TValue() if foo doesn’t exist in the map, and ... |
4,254,907 | 4,255,268 | Safe conversion to const char * - temporary lifetime problem | I have a following template defined so that I can perform an explicit, but safe cast:
/// cast using implicit conversions only
template <class To,class From>
inline To safe_cast( const From &from ) {return from;}
Frequently (e.g. when passing arguments into sprintf and similar functions) I would like to use this templ... |
I can perform an explicit, but safe cast
I would call it an implicit cast done explicitly, or just and explicit implicit cast.
1) If I am not mistaken, the standard says the temporary life time is a statement (unless extended by being bound to a const reference, in which case it is the life time of the reference). W... |
4,255,222 | 4,255,283 | Overloading a Qt-function in a sub-class of QTcpServer | I have a subclass of QTcpServer:
.h-file:
#ifndef GEOLISTENER_H
#define GEOLISTENER_H
#include <QTcpServer>
class GeoListener : public QTcpServer
{
Q_OBJECT
public:
explicit GeoListener(QObject *parent = 0);
bool listen(void);
signals:
public slots:
void handleConnection(void);
};
#endif // GEOLIST... | First of all, just a remark: those QT classes are designed for composition, not for inheritance.
Anyway, the problem here is that your listen() function is hiding the base's listen().
Your problem is resolved by:
static_cast<QTcpServer*>(this)->listen(QHostAddress::Any, 9871);
|
4,255,406 | 4,256,678 | C++ : Cookie not stored in one machine, but stored in another | I am using a small C++ app that I wrote myself using VS 2010.
This app accesses a website through HTTPS using these functions :
InternetOpen(), InternetConnect(), HttpOpenRequest(), HttpSendRequest(),
HttpQueryInfo(), InternetReadFile()
The app has been working fine for the last 2 years on a 32-bit machine running -i... | See Managing Cookies in MSDN. It explains that cookies live in AppData\Roaming\Microsoft\Windows\Cookies\Low
I can't see any possible reason why the cookie mechanism could fail on x64. I'd rather expect that some local (IE) configuration option is in force that disables use of cookies for that site (e.g. the site being... |
4,255,481 | 4,255,657 | Disabling default constructor for non-POD classes | As far as I understand, C++ default copy constructor only behaves as expected when the class is a POD class.
I would like to know if there's a solution for preventing the programmer to write code which (implicitely or not) uses the default copy constructor if the object is not POD.
I know you can always make your copy... | The centralized way to disable default construction is to make the default constructor inaccessible.
You write: "I would like to know if there's a solution for preventing the programmer to write code which (implicitely or not) uses the default copy constructor if the object is not POD. ."
Presumably you mean you'd like... |
4,255,578 | 4,469,394 | My program crashes on fflush because of seg fault, ... but not always? | What possible reasons do you know for the situation, described in the title? Here's what my bt looks like:
#0 0x00a40089 in ?? ()
#1 0x09e3fac0 in ?? ()
#2 0x09e34f30 in ?? ()
#3 0xb7ef9074 in ?? ()
#4 0xb7ef9200 in ?? ()
#5 0xb7ef9028 in ?? ()
#6 0x081d45a0 in LogFile::Flush ()
#7 0x081d45a0 in LogFile::Flush ... | It appeared, that for some reasons, there was something strange with the permissions (not sure what exactly), but this had happened on a hour change, as different files are written for each hour. So, In some way, the file was created, but there were no permissions to write in it, or something like this. No one actually... |
4,255,727 | 4,255,762 | c++ vector of vectors destruction | hi I've vector<vector<int> > matrix; I initialize it by:
inline void resize(const UINT nrows, const UINT ncols, T val) {
vector<T> v_rows(ncols, val);
matrix.resize(nrows, v_rows);
}
now I'm concerned if I call resize again where the old ones go, do I have to call clear ? for the outer matrix ? or clear for each one ... | You don't have to do anything as long a T manages it's own resources. Which, if it doesn't, clear() isn't going to help.
|
4,255,740 | 4,256,179 | design class aggregation - stack allocation vs dynamic memory allocation | Please have a look at the two simplified examples of designing a class aggregation below.
Solution 1
Header
// need include, forward declaration is not enough
#include "door.h"
class CGarage
{
public:
CGarage(const std::string &val);
private:
CDoor m_door;
};
Source
#include "garage.h"
CGarage::CGarage(cons... | It is rare that we get question design (I mean, interesting ones).
Let's forget for a moment the (obviously) contrived example and concentrate on the notion.
We have 2 solutions:
Hard containment: pull in the header and build the object directly
Soft containment: forward declare the header and use a pointer
I'll volu... |
4,255,747 | 4,255,777 | C++ #include can't find file | I need to build this c++ project.
its failing on the line
#include <wkhtmltox/image.h>
#include <wkhtmltox/pdf.h>
fatal error C1083: Cannot open include file: 'wkhtmltox/image.h': No such file or directory
fatal error C1083: Cannot open include file: 'wkhtmltox/pdf.h': No such file or directory
clearly its not findi... | Goto "Tools->Options->Projects and Solutions" then select "VC++ directories" and select "Include files" in the combo box at top right corner. Specify the directory where the file is present. That should solve the problem.
|
4,255,806 | 4,556,133 | SWIG C++ bindings with callback | I am writing some SWIG/Python bindings for some C++ code. This is for what is called the Kinect Accidental API, I have the motor and led functions working. The callbacks to the Listener class which parse and populate the RGB and Depth buffers do not seem to get called from SWIG. The data capture threads evidently start... | There is a way using the directors feature.
Enable it for your KinectListener proxy, one line of code :
%feature("director") KinectListener
Then you can inherit from KinectListener class in python code and define your functions.
|
4,255,980 | 4,256,005 | C++ template basic program, linker cannot find constructor and destructor |
Possible Duplicate:
Why can templates only be implemented in the header file?
Hello. I have a stupid program in c++ consisting in a header file with a class using template and a cpp file with implementations of methods.
This is the header:
namespace SynQueueing {
template < class T, unsigned long SIZE = 0 >
cla... | For templates you usually have to put the implementation in the .h/.hpp file. This may seem unnatural, but think of templates as some special "macros" that the compiler expands once you give the actual types or values (in your case, the type T, and the value SIZE). As most compilers are implemented (in your case GCC), ... |
4,256,020 | 4,256,588 | Flush File Read Cache | How do I flush (empty) the windows file read cache using C++ win32api?
| Try DeviceIoControl with IOCTL_DISK_SET_CACHE_INFORMATION.
|
4,256,024 | 4,256,838 | Access modifiers of a variable: Private vs Protected | I have a case that I could not find a proper solution. I need to have template base class and a manager class that does some work to that base class. Here is the code
class Base;
class Manager
{
public:
void DoSomethingTo(Base * bclass)
{
if(bclass->PrivateVar == 0)
// Some code
}
}
cl... | Remove access protection inside Base, then inherit privately.
class Manager
{
public:
void DoSomethingTo(struct Base * bclass);
};
struct Base
{
int PrivateVar;
};
void Manager::DoSomethingTo(struct Base * bclass)
{
if(bclass->PrivateVar == 0)
; // Some code
}
template<class T>
class TempBase : p... |
4,256,803 | 4,256,990 | Is there any way to replace a function in a library? | I work with a library which defines its internal division operator for a scripting language. Unfortunately it does not zero-check the divisor. Which leads to lot of headaches. I know the signature of the operator.
double ScriptClass::Divide(double&, double&);
Sadly it isn't even a C function. Is there any way I could m... | Generally speaking it's up to the programmer, not the underlying divide operator to prevent division by zero. If you're dividing by zero a lot that seems to indicate a possible flaw in the algorithm being used. Consider reworking the algorithm, or if that's not an option, guard calls to divide with a zero check. You co... |
4,256,817 | 4,259,436 | Initialization of 2D array with dynamic number of rows and fixed number of columns. C++ | I'm having problem with creating my 2D dynamic array in C++. I want it to have dynamic number (e.g. numR) of "rows" and fixed (e.g. 2) number of "columns".
I tried doing it like this:
const numC = 2;
int numR;
numR = 10;
double *myArray[numC];
myArray = new double[numR];
Unfortunately, it doesn't work. Is it possible ... |
Is it possible to do it in such a way?
Yes:
double (*myArray)[numC] = new double[numR][numC];
// ...
delete[] myArray;
This may look a little unusual, but 5.3.4 §5 clearly states:
the type of new int[i][10] is int (*)[10]
Note that many programmers are not familiar with C declarator syntax and will not understand ... |
4,256,961 | 4,258,097 | Do optional elements break RAII and if yes what is a better approach? | I have a 2-dimensional matrix of cells. Usually only invisible algorithms work with these cells. But sometimes I want to visualize each cell so I added a pointer to a graphical object
class Cell
{
...
QAbstractGraphicsItem* representation_;
...
}
The constructor of Cell sets representation_ to 0. Sometimes an... | RAII is misnamed, as (I think) Scott Meyers points out.
It shouldn't be called "Resource Acquisition is Initialization", it should be called "Destruction is Resource Release". But we are where we are.
If the Cell "owns" the object pointed to by representation_, and deletes it in its destructor, then this is still a for... |
4,257,010 | 4,257,366 | How to just invalidate the background of window, not any pixel of the client area? | just want repaint the background, not any part of the client area.
| You can't. The background is painted IN the child area of the window. IF the window uses child controls to draw objects (in its client area) then you could use the WS_CLIPCHILDREN style to ensure that the background painting of the parent window does not over-paint any children.
You'd need to just paint the relevent ar... |
4,257,239 | 4,257,496 | Pass member function pointer in C++ | I am trying to pass a function pointer (of type QScriptEngine::FunctionSignature (= QScriptValue (QScriptContext *, QScriptEngine *))) to an other function. But the function I need to pass is a member function of a class.
I use it like this:
class MyClass
{
SomeVarType someVarINeedAccessTo;
QScriptValue print(... | That doesn't work because a function is not a method and so the signature are different. As opposed to other language, in C++ a method is not bound to an object, so it as the signature of a method and need to be applied on a object.
What you should do is wrap a proper function which (or a static one) with the good sign... |
4,257,355 | 4,269,759 | One source with multiple objects | One source with multiple objects
I am using MSVS 2010 and I have a C++ source-file which must compile into 2 object-files.
The diiference between those compilations is a "#define UNICODE" for one of them but not for the other.
I can't (and don't want to) use templates for a this.
Currently ,I use 3 source files for th... | If i correctly understand what you want to do, this is possible.
I have MS Visual Studio 2005 Standard Edition; here is how i can do this (you might have to adjust this if you have a different version, or possibly it might even not work in your version; i hope your computer doesn't explode :) ).
The first step requires... |
4,257,763 | 4,257,790 | Unresolved reference when using inheritance | How can I get the template definition into a seperate header files?
My code compiles when it is included in a single main.cpp.
maip.cpp
#include <windows.h>
#include <tchar.h>
template<class T1, class T2>
class Base {
public:
virtual ~Base() {}
virtual T1 f1();
virtual T2 f2();
};
template<class T1, class... | You didn't provide an implementation for Base's constructor. Try adding
template<class T1, class T2>
Base<T1, T2>::Base () { }
Alternatively, you can remove its declaration from your second code snippet. (It is also not present in your first code example).
Your linker basically says that Derived::Derived () tries to c... |
4,257,864 | 4,257,980 | How can I programmatically detect if MSMQ has been installed on the current system? | How can I programatically detect if MSMQ has been installed on the current system?
I am using C++, but answers in other laguages could still be helpful.
(VS2008, WinXP and up)
| You can simply ask COM to create an instance of the MSMQQueueInfo object. If it succeeds you know that MSMQ is installed.
#include <atlbase.h>
#include <mqoai.h>
#include <iostream>
using namespace std;
int main()
{
auto error = CoInitializeEx(0, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
if (FAILED(err... |
4,257,922 | 10,918,336 | QGraphicsView and custom Cursors | I am trying to make use of a mix of custom cursors and preset cursors for my QGraphicsView.
In my implementation we have created a notion of "modes" for the view. Meaning that depending on what "mode" the user is in, different things will happen on the left-click, or left-click drag. Anyway, none of that is the problem... | I added a museReleaseEvent to solve a similar problem...
void mouseReleaseEvent(QMouseEvent *event) {
QGraphicsView::mouseReleaseEvent(event);
viewport()->setCursor(Qt::CrossCursor);
}
This will reset the cursor after the drag event is complete, during the drag the hand will be visible which makes sense.
|
4,258,283 | 4,265,282 | Waiting win32 threads | I have a totally thread-safe FIFO structure( TaskList ) to store task classes, multiple number of threads, some of which creates and stores task and the others processes the tasks. TaskList class has a pop_front() method which returns the first task if there is at least one. Otherwise it returns NULL.
Here is an exampl... | Assuming you are developing this in DevStudio, you can get the control you want using [IO Completion Ports]. Scary name, for a simple tool.
First, create an IOCompletion Port: CreateIOCompletionPort
Create your pool of worker threads using _beginthreadex / CreateThread
In each worker thread, implement a loop that call... |
4,258,571 | 4,258,626 | Resetting socket connection | My application connects as a client across an ethernet to a server process.
As the server is well known and will not change, UDP and TCP are both setup using
socket();
setsockopt(SO_REUSEADDR);
bind();
connect();
The connection protocol includes heartbeats sent both ways.
When I detect an error with the connectio... | You have to close(2) the socket and re-do everything again. Why do you bind(2) on the client?
|
4,258,860 | 4,260,009 | Is it possible to pass a variable out of a class without creating a new object in C++ | I have a variable, which is a member of one of my classes, that another is in need of, but I'm not sure how to effectively pass the value between them without using a global variable, which is something I'd like to avoid if at all possible. I know I could create an object, but that would invoke the constructor of the o... | Okay, from what I understand:
You don't want to have a global
You don't want to have a static
You don't want to introduce a dependency between Device and Initialise
There is one other option, assuming something owns Device and Initialise, move the no_of_existing_devices up to there, then construct both Device and Ini... |
4,258,873 | 4,258,958 | Parsing String to Array of Integers | I'm looking for a way to convert a string with specified dividers (such as slashes or spaces) into an array of the integers those dividers separate.
For example, if the user inputs 12/3/875/256, I need to retrieve the array {12, 3, 875, 256}. Ideally, it would be able to handle an arbitrary length.
I tried sweeping th... | You can set '/' to a delimiter and read using getline? then you'd have to put each one into a variable, and you'd need to know the size--maybe you can pass over the array and count the slashes? then you'd know that and can set up the array first. You might need to parse each string segment into an int, which may or may... |
4,258,883 | 4,259,179 | Is it possible to compile ffmpeg in visual studio 2010? | Is it possible to compile the sourcecode from ffmpeg in visual studio 2010? Is it difficult?
Just looking for some advice (and instructions) if possible. :-)
Cheers,
Pete
| It is not possible because ffmpeg makes extensive use of C99 features (with good reason), and MSVC doesn't support nearly enough nook and crannies of the standard.
You can however, use the C library built by MinGW for use with Visual Studio projects. See the following links for all the information you need:
Informati... |
4,258,887 | 4,258,924 | Semantics of flags on basic_ios | I find myself repeatedly baffled by the rdstate() flags - good(), bad(), eof(), fail() - and how they are expressed in basic_ios::operator!, operator bool and operator void*.
Could somebody put me out of my misery and explain this so I never have to think twice again?
| There are three flags that indicate error state:
badbit means something has gone very wrong with the stream. It might be a buffer error or an error in whatever is feeding data to the stream. If this flag is set, it's likely that you aren't going to be using the stream anymore.
failbit means that an extraction or a r... |
4,258,949 | 4,258,988 | Tools for analyzing C++ codebase | Which tools would be most useful for analyzing a C++ codebase?
What do they cost?
Can we manage with free and trial software, or are there commercial software that is good and that we really should to pay for?
The main object would be to get an understanding of quality - memory issues etc, also to understand the code ... | The best free tool is your compiler's warning errors, I always use them at maximum level. The first goal should be a clean build without any cheating (eg. disabling or casting away not-understood warnings).
Visual C++ has built in Code Analysis which is good for catching some bugs and Win32 API misuse, but it's not in... |
4,259,108 | 4,261,276 | Qt - remove menu from bottom? | How in the world do I get rid of these buttons?
| Call showFullScreen() on your QMainWindow.
|
4,259,154 | 4,259,260 | Is this container implementation totally sensible? | Would you write the following simple container any other way or it's totally sensible as it is:
template <typename T, bool small_>
struct TransType
{
typedef const T& param_type;
};
template <typename T>
struct TransType<T, true>
{
typedef const T param_type;
};
template <class T>
class Container:public TransTy... | Look into Boost.CallTraits. Namely, boost::call_traits<T>::param_type.
You shouldn't need the client to specify whether the type is small or not, that's the metafunction's job. Nor is there really a need to inherit from anything.
In fact your code right now is ill-formed. Because param_type isn't a dependent type, the ... |
4,259,174 | 4,260,472 | template constant type conversion operator not working under linux (gcc) | Consider the following program:
#include <iostream>
template<int s>
class Pack
{
public:
Pack(){}
char data[s];
template<typename X> operator X&(){ return *reinterpret_cast<X*>(data); }
template<typename X> operator X const&()const{ return *reinterpret_cast<const X*>(data); }
};
int main()
{
const... | According to the C++03 Standard, that code is ill-formed because template argument deduction will not be able to deduce X& or X const& against const double.
C++03 missed to state that the reference is stripped off from the return type of the conversion function prior to deduction, so you can never get a match in your ... |
4,259,763 | 4,259,796 | Manipulatings with istream | I want to make something like history of commands for my console-application. It does only one thing: check for input in infinite cycle (with std::getline(std::cin, ...)). As example, you can look at gdb (console debugger). After running it we can input commands and switch them with keyboard arrows.
The question is how... | If you want this for a private project or a project that will be released under a GNU license you may want to look at the GNU readline library.
|
4,259,805 | 4,259,974 | VS2008 extern templates | Microsoft has an extension whereby one can declare that a template instantiation will be external; consequentially, it does not get implicitly instantiated. At least that's the theory. I tried reproducing that with the code
#include <vector>
class Foo{
int i;
public:
virtual ~Foo();
};
extern template class s... | I think you're being bitten by this note in the docs for the extension:
The extern keyword in the specialization only applies to member functions defined outside of the body of the class. Functions defined inside the class declaration are considered inline functions and are always instantiated.
vector::push_back() (a... |
4,259,994 | 4,260,210 | QFileDialog alternative that uses default file dialog defined by OS? | I tried using a QFileDialog in a program of mine, but I prefer the default file dialog that is used by the host's OS. In my case, since I use Windows 7, it should look like this:
Is there a way to make Qt use the default file dialog that is used by the host's OS?
My code:
QFileDialog saveDialog(this);
saveDialog.setA... | Use the static functions for it and it will work.
QString filename = QFileDialog::getOpenFileName(this, ... vars);
It will use the native dialogs for OSX and Windows, but if you don't use one of the static functions to show it, it will use the QT one.
It was written in the docs for those different static functions.
... |
4,260,100 | 4,260,314 | Does using std::auto_ptr data members invoke UB? | As a followup to Class containing auto_ptr stored in vector, I believe the unstated conclusion there is that it is OK to use classes with an auto_ptr member as container elements, so long as both copy construction and copy assignment are user-defined (so as not to invoke the auto_ptrs copy constructor and copy assignme... | Using auto_ptr when the destructor is out of scope does cause undefined behavior. MSVC warns about it. GCC doesn't.
You can make it work, but only if the destructor is not defined as an inline function.
The unique_ptr and scoped_ptr fix this problem. At least with those you are prevented from writing undefined code by ... |
4,260,182 | 4,260,266 | C++ Inheritance problem | I hope I got the relevant code in here. I have some problem when I want to fetch the menu option that I've added into to menu_1. I have this function on_select(int) that I use to fetch one sub-menu's options, which I do by using the display() function. But when I compile it will say that there are no function named dis... | You can do what you want to do, but it's bad. You have to cast down to sub_menu when you call display() in on_select(). Of course it's not going to work the way you have it, and the compiler is telling you exactly why.
The other option, which is probably better (though without a clear understanding of the problem spa... |
4,260,302 | 4,260,469 | Can Winsock connections randomly fail? | I have a blocking client/server connected locally via Winsock. The client uses firefox to retrieve data from websites, passing certain data along to the server for extra processing. The server always responds, and the processing can take anywhere from 1/10th second to a few minutes. The client has no winsock connection... | Sounds like a firewall at work.
Many firewalls are configured to terminate idle connections (i.e. open TCP sessions on which no data is transferred for awhile). Especially if it's an HTTP connection, which are typically not persistent.
|
4,260,464 | 4,261,074 | Does std::list::remove method call destructor of each removed element? | I have the code:
std::list<Node *> lst;
//....
Node * node = /* get from somewhere pointer on my node */;
lst.remove(node);
Does the std::list::remove method call the destructor (and free memory) of each removed element? If so, how I can avoid it?
| Yes, removing a Foo* from a container destroys the Foo*, but it will not release the Foo. Destroying a raw pointer is always a no-op. It cannot be any other way! Let me give you several reasons why.
Storage class
Deleting a pointer only makes sense if the pointee was actually allocated dynamically, but how could the ru... |
4,260,560 | 4,261,018 | Link Problem DirectX: Linker problem | Ok folks just installed the June DirectX SDK, been reading through the documentation. Set up my visual studio pointing to the correct Lib Include and Executable files using a user variable.
$(DXSDK_DIR) which is set to the SDK file path
I tried a tech demo at random it worked happy days!
Decided to start into the tutor... | Unsure what version of visual studio you are using. Sounds like you forgot to add the d3d10d.lib file to the linker settings. If you're using 2010, try adding d3d10d.lib to Project->Properties->Linker->Input->Additional Dependancies.
The second problem is a misconfiguration with regards to your include paths.
|
4,260,569 | 4,260,970 | How to achieve this? | Simplified: Because the way the problem was presented before was misleading. My mistake. Also not to make peoples' time a complete waste :) :::
Y.h
#ifndef Y_H
#define Y_H
#include <iostream>
class X;
class Y
{
private:
friend class X;
void Print()
{
std::cout << "Y::Print" << ... | It's impossible.
At this point:
pRoot->Evaluate();
The compiler already knows it'll be calling Node::Evaluate, because it's non-virtual. You've said you cannot edit this implementation, so now you know the only path to take is to modify the implementation of Node::Evaluate.
Which you said you also cannot do. So that's... |
4,260,641 | 4,261,416 | How to wake a thread after receiving 2 packets | I'm using libnetfilter_queue for my project. From C app queue is accessible by "queue file descriptor". I have 5 queues and 5 threads to handle them. What I want to achieve is to wake thread when there is exactly 2 packets in queue. I came up with idea to use select function and array of ints indicating how many packe... | As recommended by Tobu, epoll is a better choice and it performs better than select.
However, most of these polling functions will indicate there is an event (data available) unless someone reads.
If possible use the following model:
Use epoll/select to watch for the incoming data wake up the worker thread.
Let the wor... |
4,260,674 | 4,261,130 | How to call-by-reference a variable of one class from another in C++ | I have a class, let's call it class A, that is performing a calculation which returns a value of int value, and another class in my system, class B needs to use int value for further calculations. My plan is to use a third class, class C, where the variable will be defined, to pass the variable between A and B, with th... | I believe you're not going in the right direction here. If I rephrase your problem description in pseudo-code, I get something like :
// The second calculation result depends on the result of the first one, so we
// provide it as a parameter.
int firstValue = calculationA();
int secondValue = calculationB(firstValue);
... |
4,260,891 | 4,260,923 | Can I remove elements from std::list, when I'm iterating on it? | Can I remove elements from std::list, when I'm iterating on it? For example so:
std::list<int> lst;
//....
for (std::list<int> itr = lst.begin(); itr != lst.end(); itr++)
{
if (*itr > 10)
lst.remove(*itr);
}
?
And why?
| The correct code is the following:
for (std::list<int>::iterator itr = lst.begin(); itr != lst.end(); /*nothing*/)
{
if (*itr > 10)
itr = lst.erase(itr);
else
++itr;
}
When you delete an item from the list, you may invalidate the iterator (if it points to the item being deleted.) Therefore you ... |
4,260,954 | 4,261,016 | Good place to start for client / server network programming? | I have lots of experience with C++, (native) but I have never really ventured into network programming (example: games, chat software, or software that gets a file from a Web Site. )Where would be a good place to start for this? Preferably tutorials which are cross platform, and possibly some sort of project (not just ... | Boost.Asio is a fantastic cross-platform C++ networking library. The examples and tutorials are straightforward.
There's also plenty of help on stackoverflow in the boost-asio tag
|
4,261,008 | 4,261,025 | What are the dynamics of the C++ delete statement? | This is merely for curiosity sake because I have not used new and delete in c++ except for the most basic uses.
I know that delete releases memory. The thing I'm wondering is how does it handle more complex cases?
For instance, if I have a user-defined class like this:
class MyClass
{
public:
MyClass();
~MyClas... | Given a pointer (p) to a dynamically allocated object, delete does two things:
It calls the destructor of the dynamically allocated object. Note that when ~MyClass() completes, the destructors for any member variables of class type are called.
It frees the memory occupied by the dynamically allocated object.
It does... |
4,261,227 | 4,261,402 | Prevent repainting of window in C++ | I am writing a global hook DLL that needs to do some drawing using GDI+ on a window in response to an event. My problem is that the window that is being drawn keeps repainting itself, so what I draw gets erased before I want it to. Is there any way I can prevent the window from painting anything for as long as I need t... | I would suggest putting your graphics in a layered window overlapping the target window. That seems to be the cleanest way. After all, at some level of conception, this is the purpose of the window manager :)
|
4,261,292 | 4,261,398 | OpenCV how to put jpeg image buffer to cvShowImage | I have a JPG image in buffer and I would try to show it with cvShowImage. This is not working, however:
// buff is a JPEG image with 640*480 dimensions
IplImage* fIplImageHeader;
fIplImageHeader = cvCreateImageHeader(cvSize(640, 480), 8, 1);
fIplImageHeader->imageData = (char *)buff;
cvShowImage("Window 1", fIplImage... | Looks like you forgot to set widthStep
|-- int widthStep; // size of aligned image row in bytes
|-- int imageSize; // image data size in bytes = height*widthStep
|
4,261,369 | 4,274,461 | OpenSSL Verify Peer (Client) Certificate in C++ | I have a working application that establishes an SSL connection to a server. The server uses a self-signed certificate and the client loads a certificate authority chain to tell it that the server is OK to trust. I did that with code like this on the client:
SSL_METHOD* method = TLSv1_client_method();
_ctx = SSL_CTX_... | On the server, you must also call SSL_CTX_load_verify_locations(). This function tells the server what certificates to use for certificate verification; the SSL_CTX_set_client_CA_list() function sets the list of allowed CAs that are sent to the client in the handshake. Both are required.
(You also need a SSL_CTX_use_... |
4,261,418 | 4,270,547 | Is there a better way to declare a char-type appropriate instance of a CStringT<> than | What I am trying to get at is a function that generates an instance of a CStringT<> that is appropriate for a given type of character (char or wchar_t).
Here's a contrived example:
#include <atlstr.h>
template <typename CHAR_T>
inline
CStringT< CHAR_T, ATL::StrTraitATL< CHAR_T, ATL::ChTraitsCRT< CHAR_T > > >
AsCStrin... | Thank You, everyone who helped out with this.
Here is the answer that most completely answers my needs:
// generates the correct CString type based on char_T
template <typename charT>
struct cstring_type
{
// compile time error if no matching CStringT<> for charT
};
template <>
struct cstring_type<char>
{
type... |
4,261,589 | 4,261,638 | How do I split an int into its digits? | How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.
| Given the number 12345 :
5 is 12345 % 10
4 is 12345 / 10 % 10
3 is 12345 / 100 % 10
2 is 12345 / 1000 % 10
1 is 12345 / 10000 % 10
I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.
|
4,261,708 | 4,261,742 | ++i or i++ in for loops ?? |
Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
Is there a reason some programmers write ++i in a normal for loop instead of writing i++?
| For integers, there is no difference between pre- and post-increment.
If i is an object of a non-trivial class, then ++i is generally preferred, because the object is modified and then evaluated, whereas i++ modifies after evaluation, so requires a copy to be made.
|
4,261,730 | 4,261,845 | C++ implementation of a C preprocessor | Does anyone know of a good C++ implementation of a standard C preprocessor?
I'm working on a C++ project which involves parsing C code, and I'd like to support macros etc but am not interested in implementing a C preprocessor myself.
Ideally, the preprocessor would take in the filename of the main C file, and would ret... | GNU cpp, part of GCC, is very flexible and very good at parsing and preprocessing C code, although it's written in C instead of C++.
|
4,261,861 | 4,262,069 | JPG image goes from 30KB to 300KB after cvCreateImageHeader | This is part of my program:
// let's get jpg image from socket
int iRcvdBytes=recvfrom(iSockFd, buff, bufferSize, 0,
(struct sockaddr*)&cliAddr, (socklen_t*)&cliAddrLen);
// buff now contains 30KB jpg image
// let's load the jpg image to IplImage
IplImage* fIplImageHeader;
fIplImageHeader = cvCreateImageHeader(cvSiz... | You are comparing the lenght of the compressed jpeg image data to the uncompressed pixel data.
In particular, given:
fIplImageHeader = cvCreateImageHeader(cvSize(width, height), depth, channels)
It will always be the case that fIplImageHeader->imageSize == width * height * (depth/8) * channels
Assigning the bytes re... |
4,261,919 | 4,261,932 | How can I pass an array by reference to a function in C++? | I have the following program where two variables are to be passed by reference to a function where their values will be determined based on external factors before being returned to main() so that they can be used by other functions. The first variable I am trying to pass is an int, and that goes fine, but the other is... | A reference to an array looks like:
void f(std::string (&a)[N]) { }
where a is the name of the parameter and N is the number of elements in the array.
However, usually in C++ you don't pass an array by reference (you can; it's just not common). Other options include:
Pass a pointer to the initial element of the arr... |
4,261,963 | 4,266,399 | Writing Garbage on free / delete | One of the issues with dynamic memory allocation is that one may delete/free a block of memory and still have pointers pointing into it. When one dereferences one of these pointers, chances are that things may "work" but leave one vulnerable to memory corruptions etc.
In order to help with these issues some platforms m... | The following code does exactly what I want:
#include <malloc.h>
typedef void (*free_hook_t)(void*, const void*);
static free_hook_t system_free_hook;
static void my_free_hook (void *ptr, const void *caller)
{
__free_hook = system_free_hook;
int size = malloc_usable_size(ptr);
memset(ptr,0x... |
4,261,985 | 4,265,125 | What exactly does U+ stand for and why can't I create a table of Unicode intermediate strings in my C++ application? | I'm trying to convert an application from Java + Swing to C++ + Qt. At one point I had to deal with some Unicode intermediates. In Java, this was fairly easy:
private static String[] hiraganaTable = {
"\u3042", "\u3044", "\u3046", "\u3048", "\u304a",
"\u304b", "\u304d", "\u304f", "\u3051", "\u3053",
...
}... | The problem is that C++ is based on C, which dates back to the ASCII age. The "default" C strings "abc" are 8 bits. Your Visual C++ compiler has 16 bits Unicode (UTF-16) literals, though, with a slightly different syntax: L"abc\u3042". The type of such literals is wchar_t[N] instead of char[N], you can store them in a ... |
4,262,158 | 4,262,171 | Int or Unsigned Int to float without getting a warning | Sometimes I have to convert from an unsigned integer value to a float. For example, my graphics engine takes in a SetScale(float x, float y, float z) with floats and I have an object that has a certain size as an unsigned int. I want to convert the unsigned int to a float to properly scale an entity (the example is ver... | There is an implicit conversion from unsigned int to float, so the cast is strictly unnecessary.
If your compiler issues a warning, then there isn't really anything wrong with using a cast to silence the warning. Just be aware that if size is very large it may not be representable exactly by a float.
|
4,262,551 | 4,262,719 | Unresolved external error | I've written this beauty:
#include <iostream>
struct something {
static const char ref[];
};
const char something::ref[] = "";
template<int N, const char(&t_ref)[N], typename to> struct to_literal {
private:
static to hidden[N];
public:
to_literal()
: ref(hidden) {
for(int i = 0; i < N; i++)... | The issue is that is that to_literal::hidden is declared but never defined. Take another look:
struct something {
static const char ref[]; // declaration of something::ref
};
const char something::ref[] = ""; // definition of something::ref
template<int N, const char(&t_ref)[N], typename to> struct to_literal ... |
4,262,555 | 5,395,940 | questions about my first program using Boost libraries (exceptions, long path) | I am trying to write my first program in C++, and I need to use Boost library. I am trying to write a program which recursively goes through a directory tree and returns the date of the newest and the oldest file.
This is where I'm now:
#define BOOST_FILESYSTEM_VERSION 3
#include "boost/filesystem.hpp"
#include <iostr... | It turned out it is a bug in boost. I've found a bug support ticket for it and contributed to it.
|
4,262,624 | 4,262,768 | How come the bounding box isn't being set properly in this mesh? | I have some Irrlicht code that generates a rectangular mesh given a width and height. Here is the code that generates the vertices and indices:
int iNumVertices = (width + 1) * (height + 1);
S3DVertex * vertices = new S3DVertex[iNumVertices];
memset(vertices,0,sizeof(S3DVertex) * iNumVertices);
for(int i=0;i<=height;+... | Turns out that the problem was that I was calling recalculateBoundingBox() on the buffer instead of the mesh.
|
4,262,750 | 4,262,758 | Calling the base class's implementation from the derived? | I want to do what the base does, but then I want to add some derived stuff.
I tried the following but it did not work: (this function is virtual in AguiWidget)
void AguiLabel::onSizeChanged( const AguiSize &size )
{
AguiWidget.onSizeChanged(size);
updateLabel();
}
Thanks
| Change AguiWidget.onSizeChanged(size); to AguiWidget::onSizeChanged(size);.
|
4,262,914 | 4,263,000 | Set default value of dynamic array | This code will create an array of 100 elements and set the value of each to false.
bool boolArray[100] = false;
How can I set the default value of a dynamic array?
void Foo(int size)
{
bool boolArray = new bool[size];
//Now what?
}
| In standard C++ you can default-initialize just about anything, including that array:
bool* boolArray = new bool[size](); // Zero-initialized
Complete program that also checks the result, and deallocates the array:
bool foo( int size )
{
bool* boolArray = new bool[size](); // Zero-initialized
// Check... |
4,263,131 | 4,266,929 | LibCurl FTP directory list of a subdirectory | I'm new to this libcurl stuff and struggling trying to get directory content of a sub-folder from the site I connect to.
I can successfully provide user and password to an .
Once connected, I want to get a list of files in a folder "subfolder1". No matter what I'm trying, I am only getting the directory content of the... |
UPDATE...
Although it doesn't make sense that I can't issue my own FTP commands to force changing to a directory, THEN get the directory list, by adding
curl_easy_setopt(myCurl, CURLOPT_URL, FullURLToSubFolder );
appears to force it and I get proper directory listing.
|
4,263,154 | 4,263,231 | My for loop is executing more times than is expected | I have the following for loop executing within my program and I can't see how it's design correlates with the output I'm receiving.
cout << no_of_lines << endl;
for (int count = 0; count < no_of_lines + 1; count ++)
{
getline(Device, line, '=');
cout << line << endl;
}
This is the output:
3
DeviceName
GPU
Manu... | This http://www.cplusplus.com/reference/string/getline/ is your friend here. The documentation says that when delem character is passed to getline, it reads up to delem char is found or end of file is reached. '\n' is not treated differently. Once it find delem char it discards it and fills line whatever it read until ... |
4,263,198 | 4,263,228 | Visual C++ 2010 std::set find broken | I'm changing over from Visual Studio 2008 -> 2010 and I've come across a weird bug in my code when evaluating a find on a std::set of pointers.
I know that this version brings about a change where set::iterator has the same type as set::const_iterator to bring about some compatability with the standard. But I can't fig... | The only thing I can think of is that you have multiple threads, and m_mustfindStops is in fact a member or global variable and not a local to this function. There is no way the code above can cause problems, if correct and taken in isolation.
If you have multiple threads, then read access concurrent with write access... |
4,263,303 | 5,650,592 | Creating tweening functions using C++? | How should one create an interface for tweening something using C++? For instance, I want to fade a picture in over a duration of five seconds using a static function call like:
Graphics::FadeSurface( Surface mySurface, int FrameHeight, int NumOfFrames,
int FadeDirection, double Duration )
I have a hard-coded setup... | I built a Tween engine for java that is generic enough to be used to tween any attribute of any object. The generic part is done through the definition of a "Tweenable" interface that users need to implement to tween their objects.
I greatly encourage you to use it as inspiration to build your engine, or directly port ... |
4,263,343 | 4,263,420 | GetProcessAffinityMask gives wrong value | I am using WIN API method GetProcessAffinityMask to retrieve process and the system affinity mask for the system. The method executes without any error but the lpProcessAffinityMask and lpSystemAffinityMask have value -1 which is wrong.
My Machine is AMD Opteron 6174 4 Physical, and 12 core each so in total system have... | Seeing that no information was given on the app that the OP was running, I'm making an educated guess that the app is running under WOW64 - hence limited to 32 processors (lpProcessAffinityMask is a pointer to DWORD). Therefore, the OP is seeing a result of 0xFFFFFFFF. See: http://msdn.microsoft.com/en-us/library/aa384... |
4,263,456 | 4,263,463 | Why does division(?) yield this number? | Rephrasing question :
The following code (Not C++ - written in an in-house scripting language)
if(A*B != 0.0)
{
D = (C/(A*B))*100.0;
}
else
{
D = 0.0;
}
yields a value of
9098937368185393993044965939819019600760531271904582913710297643664139878286276833532045404188178456502298966805671516948029453339416044287... | The number you divided by was not in fact 0, just very, very close.
|
4,263,640 | 4,263,652 | Find mapped value of map | Is there a way in C++ to search for the mapped value (instead of the key) of a map, and then return the key? Usually, I do someMap.find(someKey)->second to get the value, but here I want to do the opposite and obtain the key (the values and keys are all unique).
| Because of how a map is designed, you'll need to do the equivalent of a search on unordered data.
for (auto it = someMap.begin(); it != someMap.end(); ++it)
if (it->second == someValue)
return it->first;
|
4,263,748 | 4,265,666 | Should this be ambiguous or not? (implicit casts) | struct A
{
A(const A& src);
A(const char* src);
};
struct B
{
operator A();
operator char*();
};
void test()
{
B v;
A s(v);
}
EDG/Comeau and MSVC allows the code while GCC 4.4.4, CLANG and BCC
reject it as ambiguous.
A C++ committee member replied with this (initially):
It's... | Yes, the expected result is Ambiguity to the best of my interpretation of Clause 13.3.3.2
Matching argument 'v' of type 'B' to the parameters of either of the overloaded constructors of 'A' requires a user defined conversion. There both the sequences are of CONVERSION rank.
My interpretation is that the following quot... |
4,263,779 | 4,263,885 | C++ why bitvec[0].flip() works | Based on C++ Primer 4th edition (i.e. pp 105),
bitset<32> bitvec;
bitvec[0].flip(); // reverses the first bit.
My question is why the second line works? Based on
http://www.cplusplus.com/reference/stl/bitset/operator[]/
bool operator[] ( size_t pos ) const;
reference operator[] ( size_t pos );
How can bitset:... | "reference" returned by operator[] is not a C++ reference, it is a special proxy class that has flip() method.
Pseudo code:
class bitset
{
class reference
{
public:
reference& flip()
{
bitset_.flip(pos_);
return *this;
}
reference(bitset& obj)
: bitset_(obj), po... |
4,263,796 | 4,263,882 | Pointer dereference operator ( (*) vs -> ) | Is there a general difference between doing
(*ptr).method()
vs
ptr->method()
I saw this question in a comment on another question and thought I would ask it here. Although I just remembered that pretty much every operator in C++ can be overloaded, so I guess the answer will depend. But in general, is there a differe... | As "jamesdlin" already noted, the * and -> operators can be overloaded for class types.
And then the two expressions (*ptr).method() and ptr->method() can have different effect.
However, for the built-in operators the two expressions are equivalent.
The -> operator is more convenient when you're following a chain of po... |
4,263,904 | 4,263,938 | C++ pod initialization via default c'tor | Consider this POD:
struct T
{
int i;
char c;
};
In which C++ standard was the requirement of POD members be initialized to zero via default c'tor introduced (or was it in the standards from the beginning)?
Yes, that means without user specified c'tor, 'i' and 'c' will both be initialized to 0.
See http://msdn.mi... | I don't know if I have understood your question properly or not.
that means without user specified c'tor, 'i' and 'c' will both be initialized to 0.
Not necessarily.
For example:
T x; // `i` and `c` are uninitialized
T *ptr = new T; // `i` and `c` are uninitialized
T *pptr = new T(); //`i` and `c` are zero initializ... |
4,263,991 | 4,264,020 | Reusing the same string before inserting to a list seems to pass by value? | list<string> l;
string s;
getline(cin, s);
l.push_back(s);
getline(cin, s);
l.push_back(s);
Using input
123
test
Printing the list 'l' results:
123
test
Shouldn't this print:
test
test
I'm a little confused as to why the string is being passed by value.
| push_back copies the string object s passed into it. So wahetever modification you do to s is not affecting the pushed back value.
|
4,264,231 | 4,264,303 | Parsing C/C++ source: How are token boundaries/interactions specified in lex/yacc? | I want to parse some C++ code, and as a guide I've been looking at the C lex/yacc definitions here: http://www.lysator.liu.se/c/ANSI-C-grammar-l.html and http://www.lysator.liu.se/c/ANSI-C-grammar-y.html
I understand the specifications of the tokens themselves, but not how they interact. eg. it's OK to have an operato... | The lexer converts a character stream into a token stream (I think that's what you mean by token specification). The grammar specifies what sequences of tokens are acceptable. Hence, you won't see that something is not allowed; you only see what is allowed. Does that make sense?
EDIT
If the point is to get the lexer t... |
4,264,304 | 4,264,314 | How to return an array from a function? | How can I return an array from a method, and how must I declare it?
int[] test(void); // ??
| int* test();
but it would be "more C++" to use vectors:
std::vector< int > test();
EDIT
I'll clarify some point. Since you mentioned C++, I'll go with new[] and delete[] operators, but it's the same with malloc/free.
In the first case, you'll write something like:
int* test() {
return new int[size_needed];
}
but i... |
4,264,601 | 4,279,226 | Qt programming: How to extend Javascript API in webkit | I am new to Qt and what I am trying to do is:
Create a Linux app using the Qt framework.
This app displays some web pages from the Internet.
I want to extend the JavaScript API to access some device and device based data, which means some devices can be controlled using JavaScript in Webkit.
But how do I add some cus... | Fortunately, there exists some documentation on this, finally: http://doc.qt.io/qt-4.8/qtwebkit-bridge.html
|
4,264,614 | 4,264,689 | C++ Object - Private int Returns Strange Values | I've been teaching myself C++ and started creating a list organizer to work on the concept of pointers.
I've defined a class called List which has three properties:
int itemTotal;
Item* firstItem;
Item* lastItem;
The constructor sets their values as:
itemTotal = 0;
firstItem = NULL;
lastItem = NULL;
I've built a fun... | Haaa! You are initializing a local variable in the constructor not the member!! Instead of int itemTotal = 0; write this->itemTotal = 0; or just itemTotal = 0 or even use constructor initialization list like this
List::list()
:itemTotal(0),
firstNode(NULL),
lastNode(NULL)
{
cout << "List ctor Called"
}... |
4,264,709 | 4,264,782 | Problem with std::vector | Good day people,
I'm stuck with a silly C++ problem.
Let's say I have an iterator called it1 that goes through the values of a vector containing pointers to a class, we'll call it C:
std::vector<C*>::iterator it1;
But C is not alone: it has many subclasses, which share the same attributes and methods I'm looking for ... | I think I know what you mean. C is your base class and, say A and B derive from C. But there are functions is A and/or B which aren't there in C, is that what you mean? In this case I you'll have to downcast *it to A* or B*. If this should be done in exceptional cases then OK, otherwise you should redesign...
|
4,264,797 | 4,264,818 | Can you write UTF-8, UTF-16 and std::wstring representation of "U+9FA5 (龥)" and "U+0041 (A)" unicode characters? | Please specify if there is a difference in representation between Windows and Linux machines (like std::wstring consuming 4 bytes in Linux and 2 bytes in Windows).
And please also specify endianness if necessary.
| No, I can't. But this site can.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.