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,941,201
4,941,296
How do I use the windows network API in Qt?
I am going to put an network status icon in my GUI application. To get the network status notification, I am trying to use the Windows API. For this I am thinking to use NetworkAvailabilityChangedEventHandler in my application. I am very new to programming with the Windows API and framework. Can anybody help me in the ...
Where did you get the idea to use the NetworkAvailabilityChangedEventHandler delegate? That is explicitly not part of the Windows API, but rather a delegate function used by the .NET Framework in conjunction with the NetworkChange.NetworkAvailabilityChanged event. That explains why all the examples on MSDN are in C#—be...
4,941,228
4,941,246
How to detect no-return statement from a function
I have a function which returns non-void. On the caller side, I want to detect whether a return statement was called in original function or not. I know, that it is not allowed to have non-void function return nothing and it would throw up a warning in gcc. But I want to print a runtime error based on whether return wa...
You can't determine how a function returns from the caller (other than whether it throws an exception or what it returns). The only thing you can do is prevent the function from returning explicitly using that compiler warning or put a run-time error call at the end of the function that you don't want to have control ...
4,941,531
4,941,568
When a boost::shared_ptr might not be freed?
Afer reading this topic C++ interview preparation (Matt's answer) I've got a question about boost::shared_ptr. Is it really possible for shared_ptr to leak memory? How?
shared_ptr uses reference counts, and that means circular references can cause leaks. Concretely: struct A { shared_ptr<A> other; }; shared_ptr<A> foo() { shared_ptr<A> one(new A); shared_ptr<A> two(new A); one->other = two; two->other = one; return one; } the data structure returned by foo w...
4,941,629
4,941,666
why can't we declare object of a class inside the same class?
class A { A a;//why can't we do this };
You can do class A { A* a; } because it doesn't require knowing the size of A.
4,941,793
4,941,850
new operator for memory allocation on heap
I was looking at the signature of new operator. Which is: void* operator new (std::size_t size) throw (std::bad_alloc); But when we use this operator, we never use a cast. i.e int *arr = new int; So, how does C++ convert a pointer of type void* to int* in this case. Because, even malloc returns a void* and we need t...
There is a very subtle difference in C++ between operator new and the new operator. (Read that over again... the ordering is important!) The function operator new is the C++ analog of C's malloc function. It's a raw memory allocator whose responsibility is solely to produce a block of memory on which to construct obj...
4,941,884
4,941,909
C++ friend operator+ overloading
I'm confused about friend operator overloading. It has no problem if I write the friend operator overloading function within the header file, but it gives me the following errors once I moved the function to class file. I googled some samples and they all written the function in the header file. What did I do wrong? T...
From the error message you're getting: ISO C++ forbids declaration of ‘statisticain’ with no type I think that you misspelled "statistician" by reversing the last two letters (note that you have "statisticain" instead of "statistician.") This should have nothing to do with whether operator+ is implemented in the heade...
4,941,906
4,941,944
C++ Subclassing, Inheritance and Casting
This specific conundrum is hard for me to explain so I'll try as best I can. In the Qt framework, there are 2 classes: QTreeWidget and QTreeWidgetitem. I have subclassed a QTreeWidgetitem: class MyQTreeWidgetitem : public QObject, public QTreeWidgetitem { ... public: int myCustomVariable; } I add this to a QTreeW...
I don't know Qq, but you could try doing a proper dynamic_cast<> which will verify whether the object is actually a MyQTreeWidgetItem* (otherwise returns 0), as well as performing the pointer conversion properly (I'm not sure if the C-style cast is returning the address of the QObject). You can print out the pointers ...
4,942,088
5,242,739
Matlab plots directly inside c++ GUI
I'm using matlab compiler to generate c++ shared library from my m files. Is it possible to display matlab plots directly inside c++ GUI (not in a separate window) ?
I found easy solution. If you are using windows you could just setparent to matlab window. something like this. HWND h = FindWindow(L"SunAwtFrame", L"Figure 1"); void MatlabViewerHack::EmbedMatlabPlot(HWND h) { SetWindowPos(h,NULL,rect.left(), rect.top(), rect.width(), rect.height(),0); SetWindowLong(h, GWL_ST...
4,942,188
4,942,334
getting started with making event-driven applications in Dev C++
I am a newb developing a windows C/C++ program in Dev C++ that logs system activity when the link is down. I want to get acquainted with developing event-driven applications. To learn, I am making a simpler program that 1-- does a ping_a_server() periodically and thus knows the state of the link 2--a do nothing in t...
You should probably start with the resources listed on this Wiki: http://en.wikipedia.org/wiki/Event-driven_programming
4,942,703
4,942,746
Why do I get an error trying to call a template member function with an explicit type parameter?
I don't get it, it seems to me that the call to f is completely unambiguous, but it fails to compile with expected primary-expression before ‘int’. If I comment out the line with the call to f, it compiles fine. template<typename T> struct A { template<typename S> void f() { } }; template<typename T> struct B ...
This is due to a really obscure provision of the standard in which if you have a template that tries to access a template function in an object whose type depends on a template argument, you have to use the template keyword in a weird way: this->template f<int>(); This is similar to the weirdness with typename that co...
4,942,965
4,943,649
The correct decision of storing objects in memory (composite pattern)
I have already object of CCompositePrimitive class in Main.cpp int main() { ... CCompositePrimitive DrawObjects; ... } The CCompositePrimitive class has field: private: list<CDrawObject*> m_Objects; and method: public: Add(...); void CCompositePrimitive::Add() { Objects.push_back(new Rectangle(...)) ...
Depends on how the class where CCompositePrimitive m_DrawOjects; is stored in gets created. (I assume it's stored inside a class because of the m_) If your class is created on the stack, then m_DrawObjects will be too. If your class is created on the heap, so will be m_DrawObjects. But indifferent of wether m_DrawObjec...
4,942,984
4,943,279
Convert variables from c# to c++
c# public sealed class RC5 { private readonly uint[] _bufKey = new uint[4]; private readonly uint[] _bufSub = new uint[26]; }; c++(errors) class RC5 { protected: unsigned __int32[] _bufKey = new unsigned __int32[4]; unsigned __int32[] _bufSub = new unsigned __int32[26]; }; Of cours...
In C++ the array "marker" must follow the variable name, not the type name. You have two ways in C++ to instantiate the array: a) Make it a fix array: class RC5 { protected: unsigned __int32 _bufKey[4]; unsigned __int32 _bufSub[26]; }; b) Allocate it on the heap: class RC5 { public: RC5() : _bu...
4,943,484
4,943,517
When does it make sense to typedef basic data types?
A company's internal c++ coding standards document states that even for basic data types like int, char, etc. one should define own typedefs like "typedef int Int". This is justified by advantage of portability of the code. However are there general considerations/ advice about when (in means for which types of project...
Typedefing int to Int offers almost no advantage at all (it provides no semantic benefit, and leads to absurdities like typedef long Int on other platforms to remain compatible). However, typedefing int to e.g. int32_t (along with long to int64_t, etc.) does offer an advantage, because you are now free to choose the da...
4,943,498
4,943,559
send over IP immediately on different thread
This is probably impossible, but i'm going to ask anyways. I have a multi-threaded program (server) that receives a request on a thread dedicated to IP communications and then passes it on to worker threads to do work, then I have to send a reply back with answers to the client and send it when it is actually finished...
If you need it sent immediately, your best bet is to bite the bullet and start sharing the connection object. Lock it before accessing it, of course, and be sure to think about what you'll do if the send buffer is already full (the connection thread will need to deal with sending the portion of the message that didn't ...
4,943,607
4,943,655
expression must have pointer-to-object type,subscript requires array or pointer type
class RC5 { public: RC5() : _bufKey(new unsigned __int32[4]), _bufSub(new unsigned __int32[26]) { } unsigned __int8 Test(unsigned __int8 data); virtual ~RC5() { delete [] _bufKey; delete [] _bufSub; } private: unsigne...
It looks like the problem is that in your Test function you're passing in the data as an unsigned __int8 rather than as an array of these values. The subscripting with square brackets is what's causing the error. Changing the function to take it's value by array should fix this.
4,943,770
4,943,907
Case insensitive string::find
Is there exist a case-insensitive find() method for std::string?
You could upper-case both strings and use the regular find. (Note: this approach may not be correct if you have Unicode string.) In Boost there's also ifind_first for case-insensitive search. (note that it returns a range instead of a size_t). #include <string> #include <boost/algorithm/string/find.hpp> #include <cstdi...
4,943,913
4,943,952
How do I start creating Firefox plugins?
hi I want to create firefox plugin with the help of c++. I am using Unix.
See this reference from Mozilla.
4,943,958
4,944,131
Conditions for automatic generation of default/copy/move ctor and copy/move assignment operator?
I want to refresh my memory on the conditions under which a compiler typically auto generates a default constructor, copy constructor and assignment operator. I recollect there were some rules, but I don't remember, and also can't find a reputable resource online. Can anyone help?
In the following, "auto-generated" means "implicitly declared as defaulted, but not defined as deleted". There are situations where the special member functions are declared, but defined as deleted. The default constructor is auto-generated if there is no user-declared constructor (§12.1/5). The copy constructor is au...
4,944,070
4,950,560
Oracle OCCI - get column by name instead of index
Using oracle OCCI is it possible instead of supplying an index for the column when requesting data from a query resultset, to actually pass the column name and get the data? So instead of doing: (pseudocode) std::string query = "SELECT NAME FROM CUSTOMERS;"; std::string myresult = oracle.getString(1); // name column i...
I just read the documentation. It says ResultSet has a method getColumnListMetaData(), which produces a vector of MetaData. Most probably you can then use MetaData::getString to find the name of column. And if so then you can use a std::map<string, int> to map the column names back to indices. And with that name → inde...
4,944,092
4,945,567
How can I correctly convert these to c#, marshall so I can pass these struct to DLL (c++)?
C++ #define FIELD_SIZE_MSGID 24 #define FIELD_SIZE_TIME 12 #define FIELD_SIZE_ADMIN 256 typedef struct { char MsgId[FIELD_SIZE_MSGID+1]; char SendTime[FIELD_SIZE_TIME+1]; char ReceiptTime[FIELD_SIZE_TIME+1]; } AdminDataM0; typedef struct { int Type; union ...
In stead of MarshalAs[UnmanagedType.ByValArray], you should use MashalAs[UnmanagedType.ByValTStr] inside the declaration of your struct: as in: ... public struct AdminDataM0 { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = FIELD_SIZE_MSGID + 1)] public string MsgId; [MarshalAs(UnmanagedType.ByValTStr, Siz...
4,944,156
4,951,057
Partial specialization of double-templated method fails
There is the template class List. template <typename Point> class List { public: template <const unsigned short N> void load ( const char *file); ... }; template <typename Point> template <const unsigned short N> void List <Point>::load ( const char *file) } How to specialize metho...
It turns out that there's a provision in the C++ spec that explicitly disallows specializing a template class or function nested inside of a template class unless you also explicitly specialize the outer template as well. Visual Studio doesn't enforce this rule, hence the confusion with the previous example, but g++ c...
4,944,159
4,944,209
Get std::list by reference
I have a Poly3D class in C++, which has a sole member: list<Point_3> using namespace std; struct Poly3D { public: Poly3D(const list<Point_3> &ptList); private: list<Point_3> ptList; }; My question is, how to GET ( in the sense of C#) by reference, so that the same copy with be returned every time I access ...
#include <list> using namespace std; struct Point_3{ }; struct Poly3D { public: Poly3D(const list<Point_3> &ptList); list<Point_3>& GetPointList(); private: list<Point_3> ptList; }; list<Point_3>& Poly3D::GetPointList(){ return ptList; } int main(void){ list<Point_3> myList; Poly3D myPoly...
4,944,413
4,944,455
Vector of custom objects : Assign compilation failure
I am creating a vector of custom objects and calling assign as follows: class myClass { public: myClass() { cout<<"MyClass def const"<<endl; } myClass(const myClass &mclass) {cout<<"Default const"<<endl;} myClass& operator=(myClass &mclass) { cout<<"called overloa...
The argument for the assignment operator must be const, e.g. myClass& operator=(const myClass &mclass)
4,944,621
4,957,386
Create an On-screen Keyboard
I use PostMessage to simulate keystrokes in a program that is in the background. It work fine except for characters that need shift on the physical keyboard. How do I simulate shift? " The code I use is roughly: VK vk = VkKeyScanEx (c, GetKeyboardLayout (0)); AttachThreadInput (_attachedThredId, _attachedProcessId, ...
You must compromise: If you want to simulate keyboard input, then you must use SendInput, which means being at the mercy of which window currently has focus. SendInput is like hitting the keys on your physical keyboard. The only way you can send your keystrokes to a specific window using your keyboard is to ALT+TAB to ...
4,944,652
4,944,676
maximum and minimum value?
I have made a matrix using vector and iterator, how can I find maximum and minimum value from it. It is something like: vector<int> > matrixes(10); typedef std::vector<std::vector<int> >::iterator it; it rows = matrixes.begin(); if (rows->size() == 10) ++rows; rows->push_back(res); } for(size_t q=0; q < matrixes....
Just add two variables to hold the maximum and minimum value. Update the portion where you display it. vector<int> > matrixes(10); typedef std::vector<std::vector<int> >::iterator it; it rows = matrixes.begin(); int maxVal,minVal; if ( matrixes.size() > 0 && matrixes[0].size() > 0 ) maxVal = minVal = matrixes[0][0...
4,944,749
4,944,805
Why is a default ctor needed for this inner (nested) struct?
I am trying to compile code similar to the snippet below: class System { private: struct Configuration { Configuration(/*params*/); Configuration(const Configuration&); Configuration& operator=(const Configuration&); ~Configuration(); /* member variables */ } m_config; explic...
m_config is first default constructed and then assigned. Use the member list to set its value directly. System::System() : m_config(/*default params*/) {}
4,944,771
4,945,701
std::atomic | compare_exchange_weak vs. compare_exchange_strong
I'm unsure if it's me not understanding or the documentation isn't clearly formulated. The following excerpt has been taken from the newest draft (N3126, section 29.6): bool atomic_compare_exchange_weak(volatile A* object, C * expected, C desired); bool atomic_compare_exchange_weak(A* object, C * expected, C desired); ...
It has to do with the shared memory consistency model that the hardware implements. For those hardware architectures that implement some kind of relaxed consistency model (e.g. release semantics), the strong operations you refer to above can have a high overhead, and thus experts can use the weaker forms to implement a...
4,944,826
4,945,376
including class as member in struct
I have to add a class object as member within a c struct. Is there any prohibition doing this. Regards, iSight
You CAN have a C++ class member in C, but it needs to be seen as a void* in the C point of view, so as the C can handle it fine. This technique is called Opaque Pointer.
4,944,899
4,949,968
Does boost test have support for wide strings?
I'm just using BOOST_TEST_MESSAGE(L"blah") and the only thing that is printed out is an hex value such as 0x12345678. Am I missing some configuration? I'm using boost 1.44.
If you take a look at boost/test/unit_test_log.h, you can see that the class unit_test_log_t is using a std::ostream for streaming the logs. So, you will probably have to implement your own logger.
4,944,930
4,946,121
Is there something like boost::asio for .NET (Mono)?
I need the functionality of boost::asio::io_service in a .NET (C#) program. Is there a library (Microsoft or 3rd-party) that has a similar functionality? What I need is a class/mechanism like boost::asio::io_service that lets me asynchronously invoke handlers. With io_service I can "post" handlers from outside the thre...
I'm not familiar with boost:asio, but you get asynchronous I/O in .NET via the BeginXXX/EndXXX pattern. For example, see Stream.BeginRead and Stream.EndRead.
4,945,128
4,945,152
What is a good example of recursion other than generating a Fibonacci sequence?
Possible Duplicates: Real-world examples of recursion Examples of Recursive functions I see that most programming language tutorial teach recursion by using a simple example which is how to generate fibonacci sequence, my question is, is there another good example other than generating fibonacci sequence to explain ...
The classic is the binary tree search: def findval (node,val): if node == null: return null if node.val = val: return node if node.val > val: return findval (node.left,val) return findval (node.right,val) findval (root,thing_to_find) That may be a little more complex than a sim...
4,945,389
4,945,515
Why is it not possible to define a fully-qualified function within a foreign namespace? May I know what the standard says?
Is this is wrong? Why? May I know what the standard says? namespace N{ namespace N1{ namespace N2{ struct A{ struct B{ void fun(); };//B }; //A } //n2 }//n1 namespace N3{ void N1::N2::A::B::fun(){} //error }//n3 }//n int main() { return 0; } May I know why...
This is invalid due to §9.3/2: A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition. The scope of the namespace N3 does not enclose the definition of the class B
4,945,435
4,992,503
How can i jump to a webpages anchor <a> tag using ShellExecute in C++?
I'm currently opening a webpage succesfully in this manner, for example ShellExecute(NULL, "open", "http://www.google.com", NULL, NULL, SW_SHOWNORMAL); However what I really need to do is be able to jump to an anchor tag, like 'mypage.html#middle'. When I just append it to the end of the URL string, the webpage only o...
Okay, so I've managed to achieve this using a slightly different technique. However when using this method you have to define which browser to open it with, which might be considered an issue for those concerned about deploying it to a large number of users (fortunately, in my case this isn't true). ShellExecute(NULL, ...
4,945,450
6,397,615
Apache qpid setDelay
Does Apache qpid-cpp messaging api support delayed delivery of message as in ActiveMQ? TextMessage message = session.createTextMessage("test msg"); long time = 60 * 1000; message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
No, this is not currently supported (current version is 0.10). If you'd like to see this included in a future version, I would recommend creating a feature request in the Qpid JIRA if one doesn't exist yet.
4,945,586
8,410,044
How to make Valgrind debugger step through a program
Good morning, I am trying to use the Valgrind debugger to step through a program. My valgrind command line is valgrind -tool memcheck --leak-check=full --db-enable=yes ./MatchUpAcurate.exe. I am using valgrind-3.5.0 on Centos Linux release 5.5 with gdb version 7,0.1-23.el5_5.2. I enter Yes when valgrind asks the ques...
You can also get vgdb in the 3.7.0 release. From the release notes: GDB server: Valgrind now has an embedded GDB server. That means it is possible to control a Valgrind run from GDB, doing all the usual things that GDB can do (single stepping, breakpoints, examining data, etc). Tool-specific functionality is also av...
4,945,681
4,945,748
Help Displaying a Vector In int main()
The program I've written creates a deck of card that can be shuffled and player that takes four cards and puts them into for corresponding columns. I can display a single card by doing this: int main() { Card card; cout << card << endl; } The problem is, I want to display my player class, which is made up of ...
cout << player; This would not work, because you've not overloaded operator<< for type Player. Please first implement this: ostream & operator<<(ostream &out, const Player & player) { //your implementation } If it needs to access private members, then make this friend of Player. I just noticed that your class Pl...
4,945,698
4,945,833
Is the value of RAND_MAX always (2^n)-1?
I'm interested for C++, though I suspect that simply imports the C standard definition. I believe the answer is no for what the standard says, but I'm most interested in the in-practice answer. If RAND_MAX is always (2^n)-1 (where n is some natural number - in effect the number of random binary digits in a random numbe...
I don't know what the guarantees on RAND_MAX are, but you'd better avoid it if possible because of the number of broken implementations around and because it starts cycling quite quickly in today's applications. Getting a uniform distribution is described here. I recommend Boost.Random instead. The Mersenne twister gen...
4,946,033
5,080,550
How read Linux or Mac created file in Windows via C FILE*?
As all we know in windows EOL is CRLF and in linux LF and CR in Mac. (more_info) I want to write a program which reads as linux and Mac as well Win files line by line in Windows. To open file I would use fopen in "rt" mode, but I don't know how read lines. fgets reads until CRLF and LF under Windows but I want it to wo...
So I couldn't find nothing good for me and decided to write my own my_fgets function which uses fgetc in body.
4,946,191
4,946,230
What does '&' mean in C++?
What does '&' mean in C++? As within the function void Read_wav::read_wav(const string &filename) { } And what is its equivalent in C? If I want to transform the above C++ function into a C function, how would I do it?
In that context, the & makes the variable a reference. Usually, when you pass an variable to a function, the variable is copied and the function works on the copy. When the function returns, your original variable is unchanged. When you pass a reference, no copy is made and changes made by the function show up even aft...
4,946,424
4,946,484
creating a map from two vectors
If I have two stl vectors vect1, vect2 and I want to produce from them a map, so first element from vect1 will correspond to first element in vect2 and so on. How can I do that in the most simple way?
std::vector<int> a, b; // fill vectors here... std::map<int, int> m; assert(a.size() == b.size()); for (size_t i = 0; i < a.size(); ++i) m[a[i]] = b[i];
4,946,837
4,959,254
Create and access frozenset with Boost Python
I have some C++ methods that have std::set<std::string> as argument or return value. I would like to map this to a Python frozenset (or regular set) but there does not seem to be a straightforward way to do this. Does anyone know how one may accomplish this task.
Unfortunately, the standard indexing_suite from Boost.Python does not support std::set. There is a indexing_suite v2, that works on all stl containers. (http://mail.python.org/pipermail/cplusplus-sig/2009-July/014704.html) It may not have made it to the official distribution, but you can find it by asking around. (htt...
4,946,846
4,947,330
use file or class for documenting classes in doxygen?
This surely is a noob question, but I can't find an answer in Doxygen documentation. I'm not sure whether using: @file or @class when documenting my header files. The reason is that if I put file, then all the comments appear in the Files tab only, but not in the Classes tab (per each). For cpp it's ok, I just use fi...
I usually use neither, unless I want to specify an alternate include path or something like that. Normally it looks like this: /// Tunables loader. /** This class contains a set of functions for loading tunables from * file. Usually you only need one QuaTunablesLoader object in your * program. Once its work is done, ...
4,947,043
4,947,174
Running a c++ console app inside a C# console app
I have a c++ console app which runs in visual studio. This collects data and displays it in the console with all the raw data. Another app (C#) is used to collect this information and present it to the UI. Is it possible to combine the two by putting the C++ one inside the C# one so that both run at the same time as on...
A very quick example I have to do something like I said earlier is this: private void executeCommand(string programFilePath, string commandLineArgs, string workingDirectory) { Process myProcess = new Process(); myProcess.StartInfo.WorkingDirectory = workingDirectory; myProcess.StartInfo.Fil...
4,947,124
4,947,165
Braces After Initialization Lists
class Foo { Foo(double InitValue): StoredDouble(InitValue) { } double StoredDouble; } Is there a syntax that will allow me to skip out on the curly braces after the initialization list? I know it's a minor thing, but I'd like to be as concise as possible in my code.
No, because Foo( double InitValue ) is actually a method and all methods must have opening and closing braces.
4,947,149
4,947,389
C++ Class, Assigning values during Constructor initialization
I have a 2D array which I declared part of the classes private members. When I call the constructor, I start assigning values to the 2D array. But every time I do so, I'm hit with an error C2059. To make sure nothing else was causing that error I commented out that line and the compiler finished putting together a bina...
Unfortunately, we can't yet properly initialize arrays that are members of classes. I don't know exactly how yours is declared, but here's an example of what to do: class X { int Variable[3][4]; public: X() { const int temp[][4] = { { 1, 2, 3, 4}, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; const...
4,947,294
4,947,328
Implicit Template Parameters
The following code generates a compile error in Xcode: template <typename T> struct Foo { Foo(T Value) { } }; int main() { Foo MyFoo(123); return 0; } error: missing template arguments before 'MyFoo' Changing Foo MyFoo(123); to Foo<int> MyFoo(123); fixes the issue, but shouldn't the compiler be a...
The constructor could in theory infer the type of the object it is constructing, but the statement: Foo MyFoo(123); Is allocating temporary space for MyFoo and must know the fully-qualified type of MyFoo in order to know how much space is needed. If you want to avoid typing (i.e. with fingers) the name of a particular...
4,947,300
4,947,478
Retrieve value of QTableWidget cells which are QLineEdit widgets
I create a QLineEdit,set a validator and put it on the table with this code: ui->moneyTableWidget->setCellWidget(rowsNum, 1, newQLineEdit); Then I've got another class for manipulating the table's data doing the sum of every value of a column. Here's the code: int Calculator::calculatePricesSum(QTableWidget &moneyTabl...
When you declare your tmpLineEdit, you should be declaring it as a QLineEdit* instead of a QWidget*. Your loop grabs the widget, casts it to a QLineEdit* and then tries to put it back into a QWidget*. Also, I'd recommend using qobject_cast<QLineEdit*> (or dynamic_cast) so that you can ensure the cast succeeded. int Cal...
4,947,308
4,947,399
How to workaround warning C4333 ('>>' : right shift by too large amount, data loss)
I have the following function to convert an integer of arbitrary size to a buffer: template<typename T> std::string build_data_from(T val) { std::string result; for (int i = 0; i < sizeof(val); i++) { result.insert(0, 1, char(val)); val = val >> 8; } return result; }; However, invoking the template...
Pretty simple: overloading build_data_from for unsigned char (and char). This can be done either by a plain overload or using std::enable_if, I'd advise a plain overload as it'll be easier: std::string build_data_from(char val) { std::string result; result += val; return result; } std::string build_data_from(unsigne...
4,947,438
4,947,460
referencing a vector
I have this code void split(vector<float> &fvec, string str) { int place = 0; for(int i=0; i<str.length(); i++) { if(str.at(i) == ' ') { fvec.push_back(atoi(str.substr(place,i-place).c_str())); place=i+1; } } fvec.pu...
It is indeed possible. You're just using the wrong syntax. The correct way to do it is : split(fvec, str); What you're doing is wrong because it passes the address of the vector as the intended reference.
4,947,618
4,947,668
Failing the template function lookup
Consider following example. #include <iostream> #include <boost/optional.hpp> template < typename A > int boo( const boost::optional< A > &a ); template < typename A > int foo( const A &a ) { return boo( a ); } template < typename A > int boo( const boost::optional< A > & ) { return 3; } int main() { s...
return boo( a ); Here type of a is int, and there is no function with name boo which accepts argument of type int. Hence you see this error: dfg.cpp:25: error: no matching function for call to ‘boo(int)’ Even if int can be implicitly converted into boost::optional<int>, the compiler cannot deduce the template argu...
4,947,832
4,949,376
Forward stdout to file in Qt Application
I have a Qt application that starts several QProcess children and then calls QProcess::setChannelMode(QProcess::ForwardedChannels). I would like to then forward stdout of this application (now containing the stdout of its children) to a log file, the location of which is determined by the application, which means I can...
Okay. As a non-Qt solution, it looks like freopen will do what I need it to: #include <cstdio> ... QString logFile; ... freopen(logFile.toLocal8Bit().data(), "w", stdout);
4,947,929
4,947,963
C++: is malloc equivalent to new?
Possible Duplicate: What is the difference between new/delete and malloc/free? I am a noob in c++, want to know whether memblock = (char *)malloc( currentByteLength); is equivalent to memblock = new char[currentByteLength] in c++?
memblock = (char *)malloc( currentByteLength); memblock = new char[currentByteLength]; No difference now. But if you replace char with int, then yes, there would be difference, because in that case, malloc would allocate memory of size currentByteLength, while new would allocate memory of size size(int) * currentByt...
4,948,115
4,948,195
How do I parse a txt file which erases all the lines except what I need?
I want to parse a text file to get what I want and create another txt file in c++. I have a text file which looks something like this. User : Group : Comment1 : Comment2 : *** Label *** ID : Nick PASS : sky123 Number ID : 9402 *** End of Label *** ###################################### And goes on. I basical...
I have not tested this, but you get the idea. void foo(ifstream& ifs, ofstream& ofs) { while ( !ifs.eof() ) { string line; getline(ifs, line); if (line.find(":") != string::npos) ofs << line; } }
4,948,241
4,948,392
Good practice for referencing objects
I'm working on a project where several different object are semantically linked together and I'm now looking for a good way to let the objects refer to each other. Usually I would put pointers in each object and link them together. In this special case there are no heap objects (at least I do not create any while writi...
Is this good pratice? In my experience, no. Any sort of unique ID crap is just one more thing that has to be managed, and managed correctly or you'll get all kinds of weird bullshit spraying all over. I worked on a product once that used this idea and a good portion of our bugs, and even more maintenance problems, wa...
4,948,342
4,948,444
while accepting socket connection
unsigned __int8 Decrypt(unsigned __int8 data[]); for(;;) { if((sConnect=accept(sListen,(SOCKADDR*)&addr,&addrlen)) != INVALID_SOCKET) { Print("Socket Connected Successfully!"); char buf[4095]; recv(sListen,buf,sizeof(buf),0); Decrypt(buf); // Error:In...
Cast buf to unsigned __int8 when you call Decrypt. Decrypt((unsigned __int8*)buf);
4,948,381
4,948,438
Why does g++ store class names in the compiled binary?
I noticed that If I run strings on my program which was compiled by g++ the output contains the names of various classes that it uses. The program was compiled with -O3 and without -g or -p, and the class names are still present when I strip the binary. I was wondering why it is necessary for g++ to store this informa...
This might have something to do with RTTI, specifically, RTTI allows you to query the name of the class of a given variable. See the typeid keyword. If this is the case then it would explain why it happens only with classes which have virtual functions - RTTI works only for classes with virtual functions. Edit: As @xen...
4,948,525
4,950,037
histogram function in OpenCV
I am seeking a way to compare 2 images and get the most matching image as output. Using histogram function in OpenCV can I do this? Can anyone please help me? But I dont know how to do it since I am not very much familiar with OpenCV. Thank you.
The histogram will just ensure that the two images have similar color distributions. The color distributions could be similar in very different images. As an example, imagine a black and white 8x8 checkboard and an image whose left side is all black and the ride side pure white. These images have the same histogram.
4,948,556
4,948,917
Don't understand why I can't call setCentralWidget in QMainWindow subclass
//clposter.h class CLPoster : public QMainWindow { Q_OBJECT public: CLPoster(); private slots: QWidget createCentralWidget(); void createActions(); void createMenu(); void createStatusBar(); void loadSavedPosts(); }; //clposter.cpp CLPoster::CLPoster() { setWindowTitle("Craigslist Pos...
All QWidget items must be allocated in the free-store (new) since they all have to have "parents". In Qt a parent will delete its children (with delete). This is why any function returning, accepting, whatever a widget is going to do so on a pointer to a widget, not the widget itself; you need to do the same.
4,948,780
4,948,967
Magic number in boost::hash_combine
The boost::hash_combine template function takes a reference to a hash (called seed) and an object v. According to the docs, it combines seed with the hash of v by seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); I can see that this is deterministic. I see why a XOR is used. I bet the addition helps in m...
The magic number is supposed to be 32 random bits, where each is equally likely to be 0 or 1, and with no simple correlation between the bits. A common way to find a string of such bits is to use the binary expansion of an irrational number; in this case, that number is the reciprocal of the golden ratio: phi = (1 + sq...
4,948,986
4,949,097
ICU Currency Locale Get Denomination
Is there a way to probe an ICU Currency Locale for it's minimal denomination? For example US's would be $0.01, Korea (ko_KR) would be ₩1. I thought calling getRoundingIncrement() on the DecimalFormat object may give it to me but that returns 0 for both en_US and ko_KR.
You need to take a look on: getMinimumFractionDigits() function: #include <unicode/numfmt.h> #include <unicode/ustream.h> #include <unicode/ustring.h> #include <iostream> int main() { UErrorCode e=U_ZERO_ERROR; icu::NumberFormat *fmt = icu::NumberFormat::createCurrencyInstance(e); std::cout << ...
4,949,084
4,949,802
how Marshal.FreeHGlobal() works?
I have a C# based UI which uses C++ based DLL. My requirement was to pass a big chunk of memory from C# to DLL. DLL will write into this memory buffer and pass it back to C#. I have used IntPtr & global memory functions to do this. Everything works fine. The question is, How to verify if the Marshal.FreeHGlobal() has c...
If you pass a valid handle to Marshal.FreeHGlobal, it will be freed. But since the method doesn't return a value, you can't say for sure whether it was cleaned up. If you have some doubt as to whether you're passing the right thing to FreeHGlobal, then I suggest that your code probably isn't as clean as it should be. ...
4,949,144
5,068,148
How to byteswap a double?
I'm trying to write a byteswap routine for a C++ program running on Win XP. I'm compiling with Visual Studio 2008. This is what I've come up with: int byteswap(int v) // This is good { return _byteswap_ulong(v); } double byteswap(double v) // This doesn't work for some values { union { // This trick is first u...
Try 3 Okay, found out there's a better way. The other way you have to worry about the order you pack/unpack stuff. This way you don't: // int and float static void swap4(void *v) { char in[4], out[4]; memcpy(in, v, 4); out[0] = in[3]; out[1] = in[2]; out[2] = in[1]; out[3] = in[0]; memcpy...
4,949,254
4,949,283
`const char * const` versus `const char *`?
I'm running through some example programs to refamiliarize myself with C++ and I have run into the following question. First, here is the example code: void print_string(const char * the_string) { cout << the_string << endl; } int main () { print_string("What's up?"); } In the above code, the parameter to pr...
The latter prevents you from modifying the_string inside print_string. It would actually be appropriate here, but perhaps the verbosity put off the developer. char* the_string : I can change which char the_string points to, and I can modify the char to which it points. const char* the_string : I can change which char t...
4,949,304
4,949,793
Quick question about glColorMask and its work
I want to render depth buffer to do some nice shadow mapping. My drawing code though, consists of many shader switches. If I set glColorMask(0,0,0,0) and leave all shader programs, textures and others as they are, and just render the depth buffer, will it be 'OK' ? I mean, if glColorMask disables the "write of color c...
For rendering a shadow map, you will normally want to bind a depth texture (preferrably square and power of two, because stereo drivers take this as hint!) to a FBO and use exactly one shader (as simple as possible) for everything. You do not want to attach a color buffer, because you are not interested in color at all...
4,949,505
4,949,969
How to select the right overloaded function template at compile-time?
I'm trying to understand how to select the right overloaded function template at compile-time, but the compiler is giving me a hard time. I can make it work, but I don't understand what is going on. Let me explain. I have two structs A and B like below. One has a special function and the other a normal. struct A { ...
This here will work. It sort-of assumes that the two functions normal and special are mutually exclusive (i.e. a class that has one of them doesn't have the other). I'm sure you can adapt it to your purpose. This uses boost::enable_if, of course. #include <iostream> #include <boost/utility/enable_if.hpp> struct A { ...
4,949,587
4,949,659
How to make policy dictate a member variable type?
While trying to apply policy-based design, I got stuck on this one (simplified): template <class TPrintPolicy, typename T> struct A : private TPrintPolicy { using TPrintPolicy::Print; T t; void Foo() { Print(t); } }; struct IntPolicy { void Print(int n) { std::cout << n << std::endl...
Make a typedef within each policy that gives the policy's data type. template <class TPrintPolicy> struct A : private TPrintPolicy { using TPrintPolicy::Print; typename TPrintPolicy::data_type t; void Foo() { Print(t); } }; struct IntPolicy { typedef int data_type; void Print(int n) { ...
4,949,846
4,949,869
What is this odd thing after the colon in a C++constructor definition?
Possible Duplicate: What is this weird colon-member syntax in the constructor? I need to know what this code means: Cman::Cman() : m_pThread (NULL) //m_pThread is pointer to other class { } I don't really understand this code. What does this NULL mean ? Can I use it as a regular constructor ?
It says to initialize m_pThread to NULL before the code inside the constructor is executed.
4,949,984
4,950,028
Pointer Initialization in Classes
Is the following code valid? class Foo() { int* Bar; public: Foo() { *Bar = 123; } } In other words, will Bar actually point to real memory space before a value is assigned to that space in the constructor? Or do I have do do something like this: class Foo() { int* Bar; public: ...
You need to assign memory as you did in the second example. If you try to run the code in the first example, it will most likely crash with an access violation error since you are trying to write the integer 123 in whatever part of memory the value of the uninitialized Bar pointer is pointing to.
4,949,998
4,950,090
Qt 4 C++ Getting an error when using 3 classes that use each other, error: field `m_Employer' has incomplete type
I'm in desperate need of help and direction. Been trying to get this to compile, but battling due to the fact that there are 3 classes and not hundreds on how the includes/forward declarations should work here. The error is marked in person.h. In addition to the error, there is a warning I've marked in main.cpp. This ...
The Person class needs to know all about Employer and so needs Employer.h included in it rather than the class forward declaration. In this case the person needs to know the size of the Employee class as you have an Employee stored inside the class. If you wanted to decouple the classes and just use a forward declarati...
4,950,070
4,950,110
Is opIndexAssign possible in C++?
The D Programming Language Version 2 has a nifty method to overload an expression like this: classInstance[someName] = someValue; Or as D Function defined in this little example: ref Map opIndexAssign(ref const(ValueT) value, ref const(NameT) name) { this.insert(name, value); return this; } Is this possible i...
Normally, you would use a proxy object as the return type of operator[]; that object will have a custom operator= defined. The vector<bool> specialization in the C++ Standard Library uses a proxy to get the behavior you are looking for. The proxy-based solution isn't as transparent as the D version, though. The code...
4,950,071
4,950,153
How to pass string between applications using SendMessage in C++
Is it possible to pass char* between 2 applications using a custom message in SendMessage? I know it is possible using WM_COPYDATA, but I want to know if I can send this using custom message(WM_USER + ..) Thank you!
WM_COPYDATA has been specifically invented because what you ask is not feasible directly. This because different applications live in different address spaces, so a pointer passed from an application has no meaning in another one. WM_COPYDATA deals with the problem by using some IPC mechanism under the hood, which is w...
4,950,084
4,950,290
How to reconcile the C++ idiom of separating header/source with templates?
I'm wondering a bit about this templating business. In C and C++ it is very common to put declarations in header files and definitions in source files, and keep the two completely separate. However, this doesn't even seem to be possible (in any great way) when it comes to templates, and as we all know, templates are a...
Instantiating a template is costly at compile time but virtualy free at runtime. Basically, everytime you use a new template type, the compiler has to generate the code for that new type, that's why the code is in a header, so that the compiler have access to the code later. Putting all your code in a .cpp lets the com...
4,950,125
4,950,186
Behavior of calling operator [] when no mapped value is assigned to the key
I have something like this: #include <iostream> #include <map> int main() { std::map<int, int*> mapaString; int* teste = mapaString[0]; std::cout << teste << std::endl; if(!teste) mapaString[0] = new int(0); std::cout << mapaString[0] << std::endl; std::cout << mapaString[1] << std::e...
The "default constructors" of primitive types (including pointers) produce 0-filled memory, much like global variables. Here is the relevant standard language (from dcl.init): To default-initialize an object of type T means: --if T is a non-POD class type (class), the default constructor for T is called (an...
4,950,265
4,950,306
How to link jsoncpp?
How can I link jsoncpp with a C++ program using g++? I tried: g++ -o program program.cpp -L/path/to/library/files -ljsoncpp, -ljson, -llibjsoncpp but g++ keeps saying: /usr/bin/ld: cannot find -lsomething
Look in /path/to/library/files to see what your *.a file is really named. On my system, I link with: -ljson_linux-gcc-4.4.3_libmt Some libraries will create a link from lib<name>.a to lib<name>-<version>.a for you, but I don't think that jsoncpp does this automatically. Therefore, you need to specify the complete na...
4,950,355
4,950,562
How do you clone() in linux inside a class and namespace?
I'm taking an intro to operating systems course and we're to use the clone() call in linux to create threads and then do some stuff with them. I seem to be having trouble just using clone() at all. I've structured my code into a single class (called Homework) which is in the namespace for the class (Course). This may b...
Define your catch function as a static class function. static int threadCatch(void *); Also (and you probably don't need this, but just in case, I'll say it here) you might also need to use the scope resolution operators to send it to clone(). I don't think so, since you're using it inside of the Homework class alrea...
4,950,411
4,950,671
Problems trying to assign **varname to *varname[]. c++
In my .h, I have a variable, Texture ** skyboxTextures. I assign some texture pointers in one method, and use them right away: Texture *skt[] = { tleft, tright, tfront, tback, tup, tdown }; skyboxTextures = skt; for(int i = 0; i < 6; i++) { skyboxTextures[i]->load(); } Then later in anoth...
Then later in another method I try to use the textures again. You cannot do that. Converting an array into a pointer to it's first element is a one way process. While the array is still an array the compiler has information like the size of the array available at compile time. Once it's a pointer, the compiler no lon...
4,950,447
4,950,528
When and how is DragDetect useful?
Basically I need something to determine if the user in the process of a drag and drop action to determine when to suppress over zealous default behavior of the CTreeCtrl label editing in an extended multi-select tree control. CWnd::DragDetect returns true when the user has moved the mouse outside of a defined rect with...
The intent is to call DragDetect from your WM_LBUTTONDOWN handler to see if the user is trying to drag something from your application. If it returns true, this is the start of a drag operation; if it's false, then not. After a return of true you start tracking the mouse and doing hit tests to provide feedback, if any;...
4,950,473
4,950,496
std::vector not retaining data?
I have this code: void BaseOBJ::update(BaseOBJ* surround[3][3]) { forces[0]->Apply(); //in place of for loop cout << forces[0]->GetStrength() << endl; //forces is an std::vector of Force* } void BaseOBJ::AddForce(float str, int newdir, int lifet, float lifelength) { Force newforce; newforce.Init(draw, str, n...
You are storing a pointer to force in your vector but the force is function local. You must use new to create in on the heap. Force* f = new Force; forces.push_back(f);
4,950,652
4,950,769
Multithreading and operator++ on primitive types
So I've read a bunch of articles, both here on SO, and elsewhere, on the topic of shared variables, multiple threads and volatile. If you consider the following code: class C { int x; public: C() : x(0) { } void Operation() { AcquireMutex(); ++x; ReleaseMutex(); } }; Now, if I...
volatile says nothing about atomicity. Its purpose is to prevent caching of memory locations that should not be cached (e.g., hardware device DMA ports.) (EDIT: This wording was in reference to "caching" by the generated code. For example, a non-volatile variable might be read from memory, then kept in a register indef...
4,950,794
4,951,297
Array of Pointer and call-by-reference
I have a little problem with a few simple lines of code. Following lines I used to call my method: char** paras = new char*; inputLength = charUtils::readParameterFromConsole(paras, paraCount, stringBeginningIndex); The method looks like following: int charUtils::readParameterFromConsole(char** &inputs, int &paraCount...
Your code as I'm writing this: int charUtils::readParameterFromConsole(char** &inputs, int &paraCount, int &stringBeginningIndex) { char input[BUFFER_STRING_LENGTH]; cin.getline(input, BUFFER_STRING_LENGTH); if(strlen(input) > 0) { bool stringBeginning = false; char* part = ""; ...
4,951,089
4,951,155
How to use MS code coverage tool in command line?
I have the following C++ code. #include <iostream> using namespace std; int testfunction(int input) { if (input > 0) { return 1; } else { return 0; } } int main() { testfunction(-1); testfunction(1); } I compiled it to get the execution cl /Zi hello.cpp -link /Profile Then, I...
You need to run your program after the monitor starts: > vsinstr /coverage hello.exe > start vsperfmon /coverage /output:mytestrun.coverage > hello.exe > vsperfcmd /shutdown When you run step 3, you should see some notification in vsperfmon.exe that hello.exe has started. If you plan on doing multiple test runs, you ...
4,951,194
4,951,264
Cannot find hash_map header under Mac OSX
#include <iostream> #include <vector> #include <list> #ifdef __GNUC__ #include <ext/hash_map> #else #include <hash_map> #endif The compiler says " hash_map: No such file or directory " Need help. thank you.
On MacOSX the correct header is at <ext/hash_map> not <hash_map>. Here worked fine: #if defined __GNUC__ || defined __APPLE__ #include <ext/hash_map> #else #include <hash_map> #endif int main() { using namespace __gnu_cxx; hash_map<int, int> map; } By the way, I prefer to use <tr1/unordered_map>.
4,951,340
4,951,439
Execute class method or function(static method) on main thread from another thread C/C++
Is it possible to create some of equivalent in iOS objective-c "performSelectorOnMainThread" functionality on C/C++ for Windows and UNIX, not iOS. Many thanks.
No, you'll have to roll your own. One way to do this would be to keep a global function pointer that your main thread checks each iteration of the main loop. For example: // Global variables pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER; void (*gFuncPtr)(void*); void *gFuncArg; // Your program's main loop in th...
4,951,425
4,951,453
Write CSV file into vectors
I have 8x14800 matrix that has been extracted from matlab as CSV file ("moves.mo"). I need to read this file into 14800 vectors with 8 values each. Can you please navigate me here? So far, I am here: std::fstream inputfile; inputfile.open("moves.mo"); std::vector< std::vector<int>* > vectorsmovesList; while (!input...
see Split a string in C++?
4,951,593
4,951,771
C++ streams question (explanation of comment in code)
I am playing around with the fastCGI application found here. The following comment is in the code: if (content) delete []content; // If the output streambufs had non-zero bufsizes and // were constructed outside of the accept loop (i.e. // their destructor won't be called here), they would // have ...
which streambufs are being referred to in the comment? It's referring to request.out, which is part of the reassigned cout: FCGX_Request request; ... fcgi_streambuf cout_fcgi_streambuf(request.out); ... cout = &cout_fcgi_streambuf; This reassignment means that the user can call cout << "Content-type: tex...
4,951,596
4,951,787
Installation independent visual-C++ project properties
Is there a way to adjust visual-C++ (MS VS 2010 EE) project properties in such a way, that the same .sln files can be built just in one click among different computers (on Windows, of course)? - so it will be possibly to upload visual-C++ projects to SVN server. Project uses some libraries (header and .lib files) with ...
You can use environment variables in your project settings by enclosing them in $(). e.g. if your environment defines BOOST_INCLUDE: set BOOST_INCLUDE=C:\boost\include\boost-1_45 then you can use $(BOOST_INCLUDE) in your settings to refer to the Boost include directory.
4,951,598
4,951,689
Limitation on usages of global variables in DLL (for Windows)
First of all, I know global variables are evil :) However, there is legit case why I need to use one. I know that there are very strict limitation on what can be executed in DllMain (no LoadLibraries, no COM initialization and so on). And I know that global variables are initialized just prior DllMain DLL_PROCESS_ATTAC...
As explained in this answer of mine, the real dll entrypoint (i.e. the real DllMain) is taken by the CRT, that, on DLL_PROCESS_ATTACH, initializes its stuff, calls the constructors of the globals and then call the "fake" DllMain (i.e. what you as a programmer see as DllMain). The MSDN documentation calls DllMain the re...
4,951,802
4,954,437
C++ MySQL++ Delete query statement brain killer question
I'm relatively new to the MySQL++ connector in C++, and have an really annoying issue with it already! I've managed to get stored procedures working, however i'm having issues with the delete statements. I've looked high and low and have found no documentation with examples. First I thought maybe the code needs to fre...
MySQL++ doesn't have a free_result method... or does it? It doesn't need one. When the result object goes out of scope at the end of GetQueue(), all memory associated with it is automatically freed. this->_con = Connection(false); Three problems here: When you create the RepositoryChecker object, you already have c...
4,951,952
4,951,965
integer arguments for c++
I have a sort of calculator in C++ that should accept arguments when executed. However, when I enter 7 as an argument, it might come out to be 10354 when put into a variable. Here is my code: #include "stdafx.h" #include <iostream> int main(int argc, int argv[]) { using namespace std; int a; int b; if(...
Wherever did you get int argv[]? The second argument to main is char* argv[]. You can convert these command line arguments from string to integer using strtol or to floating-point using strtod. For example: a=strtol(argv[1], nullptr, 0); b=strtol(argv[2], nullptr, 0); But you can't just change the parameter t...
4,952,323
4,952,349
Why isnt the >> working properly C++?
std::wifstream theFileHandle; std::wstring theData; theFileHandle.open( theFile.Name() ); theFileHandle >> theData; theFileHandle.close(); Could anyone tell me why my string (theData) is only getting the first word from the file (theFile) ??? I would like the string to contain all of the text from the file including w...
The reason you're only getting the first word is that this is precisely how the >> operator works when applied to strings - it just gets the first whitespace-delimited token from whatever stream you're reading from, after skipping any leading whitespace. If you want to read the entire contents of the file, you can use ...
4,952,403
4,957,530
link static lib in eclipse cdt
I am sorry! I have googled this a lot and cannot find an answer! It's dumb I know. I cannot link in static libraries(*.a) in eclipse cdt. I listed them all in Project->Settings-> GCC C++ linker -> Libraries. I used the absolute path to make sure I had the lib correct... and i get: cannot find -l/usr/local/lib/libbo...
I remember having a similar issue way back when I was compiling our code under linux (coming from a windows background) and if I recall correctly specifying the absolute path to the static lib also didn't work. Are you aware that to link to "libboost_date_time.a", you need to specify "boost_date_time" without the "lib...
4,952,433
4,952,566
C++ Templates + Shared Library => ambiguous call
I am writing a shared library. The idea is as follows: Shared function inside the library will be called with either int or double parameter. It must accept both. At one point in the function there is a call to a "private" function that does something with the parameter depending on whether it is an int or double. I de...
Your use of the anonymous namespace is incorrect. You're declaring printNumber() in an anonymous namespace, but then defining it in the global scope; this leads to ambiguity because you have two printNumber(int) and two printNumber(double) functions. Try this: library.hpp: #ifndef LIBRARY #define LIBRARY namespace lib...
4,952,523
4,952,567
What data structure can you use to store elements dynamically and access them efficiently?
What data structure can you use to store elements dynamically and access them efficiently?This is an interview question. Should I answer std::list (I mean in C++)? or others? As a follow-up question, what is the complexity of finding any element in a linked list in the worst case? Thank you for all your opinions.
First question I would say hash table. Putting and getting elements using hash table is O(1) in average case. Linked list have worse case of storing in O(n) and worse case of access in O(n). Array has worse case of storing O(1) and worse case of access in O(1). Linked List can grow dynamically very fast, where as array...
4,952,785
4,952,844
My program is not outputting anything from the file :/
I am doing the following exercise: My code: #include <string> #include <fstream> #include <iostream> #include <iomanip> using namespace std; int main() { ifstream inFile; ofstream outFile; double currentSalary, increaseRate, updatedSalary; string firstName, lastName; inFile.open ("Data.txt"); ...
Well, given that you don't output anything to the screen, I'm not at all surprised that's all you see. If I were you, I'd have a look at the Output.dat file to see if it's writing anything. If you're seeing nothing in that file, then it's probably because you don't have your Data.txt file in the directory where you're ...
4,952,851
4,952,863
Array subscript operator overloading
I am having trouble understanding the difference between Array obj; and Array* obj = new Array; while overloading the array index operator []. When I have a pointer to the object, I get these error messages on VS 2010. error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or ther...
In case of Array *obj, obj[i] is the equivalent of *(obj+i), so it evaluates into an Array object. You would have to do int main() { Array* obj = new Array; for( int i=0; i<10; ++i ) (*obj)[i] = i; getchar(); return 0; }
4,952,916
4,952,951
C++ unexplained variations in template function matching with enums
I have the following code containing a template function. When I am calling this function with second parameter being an enum: in some cases it finds the template specialization and in some cases it does not. I had verified that enums are the same enums in both cases (e.g there are no redefinitions) and that other par...
For starters, typically, it's inadvisable to use template specialization as a way of overloading a template function. Template specializations interact poorly with function overloading and have some pretty arcane rules dictating when they're chosen, and in general it's considered better to just provide a regular funct...
4,953,121
16,491,573
c++ SSE SIMD framework
Does anyone know an open-source C++ x86 SIMD intrinsics library? Intel supplies exactly what I need in their integrated performance primitives library, but I can't use that because of the copyrights all over the place. EDIT I already know the intrinsics provided by the compilers. What I need is a convenient interface ...
Take a look at libsimdpp header-only C++ SIMD wrapper library. The library supports several instruction sets via single interface: SSE2, SSE3, SSSE3, SSE4.1, AVX, AVX2, AVX512F, XOP, FMA3/4, NEON, NEONv2, Altivec. All of Clang, GCC, MSVC and ICC are suported. Any differences between instruction sets are resolved by im...
4,953,150
4,953,514
Convert Lat/Longs to X/Y Co-ordinates
I have the Lat/Long value of an small area in Melbourne; -37.803134,145.132377 and also a flat image of that,that I exported from openstreet map( Osmarender Image ). Image width : 1018 and Height:916 I would like to be able to convert, using C++, the Lat/Long to an X,Y coordinate where the point would reflect the locat...
You need more information than just a single lat/lon pair to be able to do this. At this stage, the information you have provided is missing two things: how large an area does your image cover (in terms of lat/lon)? Based on what you've provided, I don't know if the image shows an area a metre wide or a kilometre wide...
4,953,204
4,953,303
Multiple Inheritance and Duplicate Function Calls
I have a situation similar to Multiple inheritance + virtual function mess. I've replicated the code in a less complex environment to demonstrate what I'm confused about. I want to know how C is executing (but not acessing) both B1::method and B2::method, which then in turn executes the inherited methods. The only way ...
I think that the reason for this is that C inherits two copies of A, one from B1 and one from B2. The inheritance diagram looks like this: A A | | B1 B2 \ / \ / C When you create C, it initializes both the B1 and B2 base classes, both of which recursively initialize their A base class. Thi...
4,953,258
4,953,324
How to calculates the average of elements in an unsigned char array?
I've got a quick and I am assuming question but I have not been able to find anything online. How to calculates the average of elements in an unsigned char array? Or more like it, perform operations on an unsigned char?
Arithmetic operations work just fine on unsigned char, although you may occasionally be surprised by the fact that arithmetic in C always promotes to int. In C++'s Standard Template Library, #include <numeric> template<class InputIterator, class T> T accumulate(InputIterator first, InputIterator last, T init); To calc...