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
2,211,733
2,211,993
iPhone Quartz 2d development using C++?
Could I write c++ code that interacts with the iPhone Quartz 2D framework, or can I only using objective-c? Thanks
Yes. Quartz is a C framework. You can use C++ code that uses Quartz. You will need some Objective-C to launch your application and get a graphics context for a view to draw into.
2,211,755
2,211,866
Covert String to LPVOID and LPCWSTR in C++
I’m working with the winHTTP API in c++ and I have started to write a wrapper class for my application. For simplicity I have a number of functions that can take string parameters and use them in the winHTTP calls. However many of these require the data to be LPVOID or LPCWSTR. I can make it all work by making my wrapper functions take LPVOID or LPCWSTR parameters, but I would prefer string parameters. So is there any way to covert from sting to LPVOID/ LPCWSTR? My attempts (below) just produced jibberish bool httpWrapper::setPostData(const string &postData){ _postData = (LPVOID)postData.c_str(); _postData_len = 47; return false; } Any help would be much appreciated Thanks
Use this: bool httpWrapper::setPostData(const string &postData){ _postData = (LPWSTR)postData.c_str(); _postData_len = 47; // Something else, actually. return false; } LPWSTR _postData; You can pass a LPWSTR to methods which expect a LPCWSTR. So you can work with strings. btw, did you just try passing the string itself? I would expect that to work too and is better than getting a LPWSTR out. So, in that case it would look like: bool httpWrapper::setPostData(const string &postData){ _postData = postData; _postData_len = 47; // Whatever. return false; } string _postData;
2,211,801
2,212,300
Generic member function pointer help
Hey, I've got a question about general member function pointers. I'm trying to achieve something similar to the following question How to define a general member function pointer Essentially what I want to be able to do is to register a member function pointer that accepts a generic Event object as its argument with a specific event type (for example, a KeyboardEvent). Then, in my input management class, what I want to be able to do is whenever the user hits a key, I can create a KeyboardEvent object that contains some data about the keypress, and call all of those member function pointers that I registered with the KeyboardEvent type with my KeyboardEvent object as their parameter. I've been playing around with boost bind and boost function and they seem to enable me to do 95% of what I want to do, the only problem I am trying to store all of the member function pointers in a vector, but they're all of different types so I can't do that. So I bind them into a function object when I first register the method with my event handling system, which expects me to specify all of the arguments at this point in the execution. I don't have to objects at this point though as the objects are generated by some unknown event in the future. Sorry if none of this makes any sense.
(Here's a more direct answer to your boost::function/bind problem, without all the Boost.Signals2 stuff.) It seems you're not using the _1, _2, etc. placeholders when using boost::bind. This example illustrates how you should use them: struct KeyboardEvent { char key; }; typedef boost::function<void (KeyboardEvent)> KeyboardHandler; struct Handler { void onKey(KeyboardEvent event) {std::cout << event.key;} }; int main() { Handler handler1, handler2; std::vector<KeyboardHandler> handlers; handlers.push_back(boost::bind(&Handler::onKey, &handler1, _1)); handlers.push_back(boost::bind(&Handler::onKey, &handler2, _1)); KeyboardEvent event; event.key = 'z'; handlers[0](event); handlers[1](event); }
2,211,867
2,211,959
How do I call C++/CLI from C#?
I have a class implemented in C++ that's responsible for the arithmetic computation of the program, and an interface using WPF. I process the input with C# but then how can I use my C++ class? I've seen some comments about making a managed C++ wrapper class to interact with it, but I don't know where to start. Nor do I know how I'd go to compile it along with all the other code. I can't really find a tutorial on this, and the stuff google shows on managed C++ doesn't really seem helpful. Anything out there to help me out? This doesn't seem unreasonable to me. EDIT Tried m3rLinEz solution but it's giving me a BadImageFormatException, I think it's because the DLL isn't generated. I did everything as told, I don't know what happened. Any ideas?
Have you take a look at C++/CLI? Let me give a very short example. Here is the source file from a Visual C++ -> CLR -> Class Library project. It basically get Windows username and return it. Please note that, in order to get this compiled, you have to go into project settings and mark "Additional Dependencies" as "Inherit from parent" because we are using those Windows libs (kernel32.lib, user32.lib, ..) // CSCPP.h #pragma once #include "windows.h" using namespace System; namespace CSCPP { public ref class Class1 { // TODO: Add your methods for this class here. public: String^ GetText(){ WCHAR acUserName[100]; DWORD nUserName = sizeof(acUserName); if (GetUserName(acUserName, &nUserName)) { String^ name = gcnew String(acUserName); return String::Format("Hello {0} !", name); }else{ return gcnew String("Error!"); } } }; } Now created a new C# project and add reference to our first C++/CLI Class Library project. And then call the instance method. namespace CSTester { class Program { static void Main(string[] args) { CSCPP.Class1 instance = new CSCPP.Class1(); Console.WriteLine(instance.GetText()); } } } This gave the following result on my machine: Hello m3rlinez ! C++/CLI is basically a managed extension over C++ standard. It allows you to utilize CLR classes and data types in your C++/CLI project and also expose this to managed language. You can created a managed wrapper for your old C++ library using this. There are some weird syntaxes such as String^ to define reference type to CLR String. I find "Quick C++/CLI - Learn C++/CLI in less than 10 minutes" to be useful here.
2,211,915
2,212,063
Library function for Permutation and Combination in C++
What's the most widely used existing library in C++ to give all the combination and permutation of k elements out of n elements? I am not asking the algorithm but the existing library or methods. Thanks.
Combinations: from Mark Nelson's article on the same topic we have next_combination Permutations: From STL we have std::next_permutation template <typename Iterator> inline bool next_combination(const Iterator first, Iterator k, const Iterator last) { if ((first == last) || (first == k) || (last == k)) return false; Iterator itr1 = first; Iterator itr2 = last; ++itr1; if (last == itr1) return false; itr1 = last; --itr1; itr1 = k; --itr2; while (first != itr1) { if (*--itr1 < *itr2) { Iterator j = k; while (!(*itr1 < *j)) ++j; std::iter_swap(itr1,j); ++itr1; ++j; itr2 = k; std::rotate(itr1,j,last); while (last != j) { ++j; ++itr2; } std::rotate(k,itr2,last); return true; } } std::rotate(first,k,last); return false; }
2,211,933
2,260,791
How to call a function automatically?
I have rewrited a simple MFC application in MS Visual Studio 2008, and now it is working how i wanted. My only problem is, that i have to press a button, and i don't want. It should work automatically. I also noticed that the function are somehow called automatically. These function are called each after: CGetFileListDlg::CGetFileListDlg(CWnd* pParent /*=NULL*/) void CGetFileListDlg::DoDataExchange(CDataExchange* pDX) BEGIN_MESSAGE_MAP(CGetFileListDlg, CDialog) BOOL CGetFileListDlg::OnInitDialog() void CGetFileListDlg::OnPaint() My function, which i want called automatically is : void GetFileListDlg::OnBnClickedButtonGetFileList(). If i call my function from OnPaint (which is last called), my application is working, but i can't see nothing, untill the functions have ended. OnPaint is called more than 20 times (i don't know why). So what should i do(if it is possible somehow), that after OnPaint my void CGetFileListDlg::OnBnClickedButtonGetFileList() function should automaticall be called? Thanks in advance! kampi EDIT: What my CGetFileListDlg::OnBnClickedButtonGetFileList() function does is this: It queries for two given path for the filelist and then compares them. OnPaint is called more than 20 time, and that's the reason why this isn't good for me, because when i call this function there, it will be called more than 20 times, and why it is being called the OnPaint function, doesn't ends, and that's why i can't see the data. If i call my function in OnInintDialog, then it works, almost fine, but then it ends before, i can see the window.
PostMessage(WM_COMMAND, MAKEWPARAM(IDC_BUTTON_GET_FILE_LIST, BN_CLICKED), 0); This is the command what i needed. This command will manipulate my button like it has been clicked. Thanks for your help anyway. kampi
2,212,089
2,215,637
Thread limit in Unix before affecting performance
I have some questions regarding threads: What is the maximum number of threads allowed for a process before it decreases the performance of the application? If there's a limit, how can this be changed? Is there an ideal number of threads that should be running in a multi-threaded application? If it depends on what the application is doing, can you cite an example? What are the factors to consider that affects these performance/thread limit?
This is actually a hard set of questions to which there are no absolute answers, but the following should serve as decent approximations: It is a function of your application behavior and your runtime environment, and can only be deduced by experimentation. There is usually a threshold after which your performance actually degrades as you increase the number of threads. Usually, after you find your limits, you have to figure out how to redesign your application such that the cost-per-thread is not as high. (Note that for some domains, you can get better performance by redesigning your algorithm and reducing the number of threads.) There is no general "ideal" number of threads, but you can sometimes find the optimal number of threads for an application on a specific runtime environment. This is usually done by experimentation, and graphing the results of benchmarks while varying the following: Number of threads. Buffer sizes (if the data is not in RAM) incrementing at some reasonable value (e.g., block size, packet size, cache size, etc.) Varying chunk sizes (if you can process the data incrementally). Various tuning knobs for the OS or language runtime. Pinning threads to CPUs to improve locality. There are many factors that affect thread limits, but the most common ones are: Per-thread memory usage (the more memory each thread uses, the fewer threads you can spawn) Context-switching cost (the more threads you use, the more CPU-time is spent switching). Lock contention (if you rely on a lot of coarse grained locking, the increasing the number of threads simply increases the contention.) The threading model of the OS (How does it manage the threads? What are the per-thread costs?) The threading model of the language runtime. (Coroutines, green-threads, OS threads, sparks, etc.) The hardware. (How many CPUs/cores? Is it hyperthreaded? Does the OS loadbalance the threads appropriately, etc.) Etc. (there are many more, but the above are the most important ones.)
2,212,582
2,220,582
Using a QNetworkAccessManager.get, how can I decide to abort?
I am attempting to use the QT QNetworkAccessManager class to manage some downloads in a multi-threaded C++/QT application. On worker thread (edit: the thread is seperate for other reasons aside from doing the download), I'm would like to do a get to an external server and be ready to receive the results with the code: ... m_nam = new QNetworkAccessManager(this); QNetworkReply *reply = m_nam->get(request); connect(m_nam, SIGNAL(finished(QNetworkReply *)), this, SIGNAL(finished(QNetworkReply *))); ... But I might decide, before the download is finished, that I'm not interested in the result. So I'd like to set up a way to disconnect the connection from another thread by emitting a signal do_abort(). What suggests itself is: connect(this, SIGNAL(do_abort()), reply, SLOT(abort())); But I don't think that will work because abort is not slot of QNetworkReply. So how can I set a mechanism where I can stop this download from another thread? I could subclass QNetworkReply and give that class the appropriate slot. But I'd like to understand the situation also.
You do not need a worker thread for using QNetworkAccessManager. It is asynchronous, so it is OK to use it from your main thread. In the QThread you implement a abortTheReply() slot and inside that you do m_reply->abort(). Then you connect your do_abort() signal to the abortTheReply().
2,212,607
2,428,783
RapidXML, reading and saving values
I've worked myself through the rapidXML sources and managed to read some values. Now I want to change them and save them to my XML file: Parsing file and set a pointer void SettingsHandler::getConfigFile() { pcSourceConfig = parsing->readFileInChar(CONF); cfg.parse<0>(pcSourceConfig); } Reading values from XML void SettingsHandler::getDefinitions() { SettingsHandler::getConfigFile(); stGeneral = cfg.first_node("settings")->value(); /* stGeneral = 60 */ } Changing values and saving to file void SettingsHandler::setDefinitions() { SettingsHandler::getConfigFile(); stGeneral = "10"; cfg.first_node("settings")->value(stGeneral.c_str()); std::stringstream sStream; sStream << *cfg.first_node(); std::ofstream ofFileToWrite; ofFileToWrite.open(CONF, std::ios::trunc); ofFileToWrite << "<?xml version=\"1.0\"?>\n" << sStream.str() << '\0'; ofFileToWrite.close(); } Reading file into buffer char* Parser::readFileInChar(const char* p_pccFile) { char* cpBuffer; size_t sSize; std::ifstream ifFileToRead; ifFileToRead.open(p_pccFile, std::ios::binary); sSize = Parser::getFileLength(&ifFileToRead); cpBuffer = new char[sSize]; ifFileToRead.read( cpBuffer, sSize); ifFileToRead.close(); return cpBuffer; } However, it's not possible to save the new value. My code is just saving the original file with a value of "60" where it should be "10". Rgds Layne
I think this is a RapidXML Gotcha Try adding the parse_no_data_nodes flag to cfg.parse<0>(pcSourceConfig)
2,212,661
2,212,685
C/C++ cool macro definitions?
Besides __LINE__ and __FILE__, are there other useful pre-defined macros, like __FUNCTION_NAME__? If not, but you know of other cool/useful defined macros (especially for debugging purposes), I'd love to hear about them. Some have asked about platform: I'm using gcc/g++ on MacOSX.
I can find the following (descriptions from C99 draft, but they are available in C89 too I think): __DATE__: The date of translation of the preprocessing translation unit: a character string literal of the form "Mmm dd yyyy", where the names of the months are the same as those generated by the asctime function, and the first character of dd is a space character if the value is less than 10. If the date of translation is not available, an implementation-defined valid date shall be supplied. __TIME__: The time of translation of the preprocessing translation unit: a character string literal of the form "hh:mm:ss" as in the time generated by the asctime function. If the time of translation is not available, an implementation-defined valid time shall be supplied. For the current function name, C99 defines __func__, but __FUNCTION_NAME__ is not a standard macro. In addition, __func__ is not a macro, it's a reserved identifier (6.4.2.2p1): The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration static const char __func__[] = "function-name"; appeared, where function-name is the name of the lexically-enclosing function. If you're looking for something that's platform-specific: here's a list of gcc's common predefined macros. I like __COUNTER__, which is a unique, sequential integer starting at 0. I think __INCLUDE_LEVEL__ is cool too, but not sure if I can think of a use for it yet :-).
2,212,776
2,212,940
Overload handling of std::endl?
I want to define a class MyStream so that: MyStream myStream; myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl; gives output [blah]123 [blah]56 [blah]78 Basically, I want a "[blah]" inserted at the front, then inserted after every non terminating std::endl? The difficulty here is NOT the logic management, but detecting and overloading the handling of std::endl. Is there an elegant way to do this? Thanks! EDIT: I don't need advice on logic management. I need to know how to detect/overload printing of std::endl.
What you need to do is write your own stream buffer: When the stream buffer is flushed you output you prefix characters and the content of the stream. The following works because std::endl causes the following. Add '\n' to the stream. Calls flush() on the stream This calls pubsync() on the stream buffer. This calls the virtual method sync() Override this virtual method to do the work you want. #include <iostream> #include <sstream> class MyStream: public std::ostream { // Write a stream buffer that prefixes each line with Plop class MyStreamBuf: public std::stringbuf { std::ostream& output; public: MyStreamBuf(std::ostream& str) :output(str) {} ~MyStreamBuf() { if (pbase() != pptr()) { putOutput(); } } // When we sync the stream with the output. // 1) Output Plop then the buffer // 2) Reset the buffer // 3) flush the actual output stream we are using. virtual int sync() { putOutput(); return 0; } void putOutput() { // Called by destructor. // destructor can not call virtual methods. output << "[blah]" << str(); str(""); output.flush(); } }; // My Stream just uses a version of my special buffer MyStreamBuf buffer; public: MyStream(std::ostream& str) :std::ostream(&buffer) ,buffer(str) { } }; int main() { MyStream myStream(std::cout); myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl; } > ./a.out [blah]123 [blah]56 [blah]78 >
2,212,847
2,212,953
Can I delete OpenGL vertex arrays after calling glDrawArrays?
I am generating the vertex arrays on the fly on each render and I want to delete the arrays afterwards. Does glDrawArrays immediately copy the vertex arrays to the server? Hence is it safe to delete the vertex arrays after calling glDrawArrays? float * vp = GetVertices(); // Regenerated on each render glVertexPointer(3, GL_FLOAT, 3 * sizeof(float), vp); glDrawArrays(GL_TRIANGLES, 0, nVertices); delete[] vp; // Can I do this? Otherwise, how can I determine when it is safe to delete the vertex arrays?
Yes, it is copied immediately, so once you've done the call you can do whatever you like with the array. Also, as dirkgently pointed out, you need to use delete[] vp to delete an array.
2,213,319
2,217,356
How to build C++ for OSX 10.4, 10.5 and 10.6 in Xcode with dynamic libraries
I'm building a C++ command line tool in Xcode. The project contains dylibs for curl, boost and log4cpp. Ideally id like to build an i386 universal binary that supports 10.4 through to 10.6. I cant seem to get Xcode to compile, when I target 10.4 it says things like no such file or directory. When i target 10.6 x_64 it builds ok, but 10.5 i386 complains about my dylibs not being the correct architecture for 10.5? What version of GCC should i be using? Also, When i create an install package with PackageMaker, where should the installer place the dylibs that the tool requires? Many thanks in advance, Toby.
The 3rd party libraries were built for 10.6 x_64, I needed to rebuild them for 10.4. I installed the 10.4u sdk by downloading xcode 3.2 and choosing 'install 10.4 support' during the installation process. After rebuilding each library with GCC 4.0 against the 10.4u sdk, my project compiled successfully. I also used static libraries so I don't need to include them in the installer.
2,213,342
2,213,380
Modify malloc strategy for 2D Array so malloc succeeds
We recently received a report that our application will occasionally fail to run. I tracked down the problem code to this: struct ARRAY2D { long[] col; } int numRows = 800000; int numCols = 300; array = (ARRAY2D*) malloc(numRows * numCols * sizeof(long)) This allocation of 800 Mb can fail if the user doesn't have a large enough free block. What is the best way to change how I allocate the memory? Keep in mind that I have a large amount of code that accesses this object like this: array[row].col[colNum], so I need something that requires minor or primarily find & replace editing of the array access code.
You can allocate smaller chunks of memory separately, instead of one huge block. long** array = NULL; array = (long**) malloc(numCols * sizeof(long*)); for (int i = 0; i < numCols; i++) array[i] = (long*) malloc(numRows * sizeof(long)); Generally, memory allocation may fail, every allocation. However, let's say statistically, due to memory fragmentation, allocating a single large block of memory has higher chance to fail more often than allocating N number of smaller blocks. Although, also the solution above may cause problems as it is a bit like a double-bladed sword because it may lead to further memory fragmentation. In other words, there is no generally perfect answer and solution depends on details of a system and application. As from the comments it seems C++ library is a possibility, then solution based on std::vector (i.e. generic vector of vectors in C++) or using Boost.MultiArray
2,213,664
2,213,750
In the generic programming/TMP world what exactly is a model / a policy and a "concept"?
I'd like to know the precise yet succinct definitions of these three concepts in one place. The quality of the answer should depend on the following two points. Show a simple code snippet to show how and what the concept/technique is used for. Be simple enough to understand so that a programmer without any exposure to this area can grasp it. Note: There are probably many correct answers since each concept has many different facets. If there are a lot of good answers I will eventually turn the question into CW and aggregate the answers. -- Post Accept Edit -- Boost has a nice article on generic programming concepts
A concept is a set of requirements on a type. For example, you could have a concept called "RandomAccessible", which places the requirement on a type that it implements operator[](int) in O(1) time. As concepts were dropped from the upcoming C++ standard, they only exist intangibly in C++ as documentation. As an example, you could read SGI's description of the Container concept. When a type meets all the requirements of a concept, you call it a model of that concept. For example, std::vector is a model of the Container concept (or, equivalently, std::vector "models" Container). Finally, a policy is a unit of behaviour, which can be combined with other units of behaviour to build complex classes. For example, say you wanted to build two classes: a fixed-size array, and a dynamically-resizable array. Both these classes have a lot of shared functionality, but just differ in their storage mechanisms, and some of their functionality (e.g. you can't call push_back on a fixed-size array). template <class T, class StoragePolicy> class array : public StoragePolicy { public: T& operator[](int i) { return data[i]; } }; template <class T, int N> class fixed_storage { T data[N]; }; template <class T> class dynamic_storage { T* data; public: void push_back(const T& value) { // Code for dynamic array insertion } }; Usage would be as follows: int main() { array<int, fixed_storage<int, 10> > fixed_array; array<int, dynamic_storage<int> > dynamic_array; dynamic_array.push_back(1); fixed_array[9] = dynamic_array[0]; } Obviously this is a very crude and incomplete example, but I hope it illuminates the concept behind a policy. Note that in the example, we could say that fixed_storage and dynamic_storage are "models" of the StoragePolicy concept. Of course, we would need to formally define exactly what the StoragePolicy concepts requires of its models. In this case, it would simply be to define an indexable data member variable.
2,213,673
2,213,861
How to build boost library and others against OS X 10.4u SDK on OS X 10.6?
I'm trying to build the boost libraries and others against the os x 10.4u.sdk so I can include them in a project targeting 10.4 upwards. I'm not entirely sure what to do, am I aiming to put the .dylibs in 10.4.sdk/usr/local/.. or in my default 10.6 /usr/local/.. with support for 10.4? Any help much appreciated. Toby.
You need to distribute your libraries to the users, so it doesn't help installing them into your machiine's /usr/local. It's better to just set the linker search path to whatever directory you have the library. When you distribute an app, you're supposed to put every libraries you use inside the .app bundle (unless you're making a series of apps which share a lot of codes) so that users don't need any installer. So, there's not much to be gained by using the dynamically linked libraries, especially for non-GUI ones like boost. So I would recommend you to make a static library .a and statically link against it. If you're curious, you can find how to include frameworks in your app here in the SO question.
2,213,690
2,213,712
How to get the program path i am executing with "open with" method?
I have the problem that i am using relative paths for my files, so when i use "open with" method for opening a file into my program, all my paths are screwed (it will create my files in the folder where i used this "open with" method.) How i can retrieve the full path to the .exe file that im using to open the file with "open with" method? Edit: my main function: int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State {
#include <windows.h> #include <string> #include <iostream> using namespace std;; string ExePath() { char buffer[MAX_PATH]; GetModuleFileName( NULL, buffer, MAX_PATH ); string::size_type pos = string( buffer ).find_last_of( "\\/" ); if ( pos == string::npos ) { return ""; else { return string( buffer ).substr( 0, pos); } } int main() { cout << "executable path is " << ExePath() << "\n"; }
2,213,753
2,213,765
Added benefit of a pointer, when to use one and why
I'm learning C++ at the moment and though I grasp the concept of pointers and references for the better part, some things are unclear. Say I have the following code (assume Rectangle is valid, the actual code is not important): #include <iostream> #include "Rectangle.h" void changestuff(Rectangle& rec); int main() { Rectangle rect; rect.set_x(50); rect.set_y(75); std::cout << "x,y: " << rect.get_x() << rect.get_y() << sizeof(rect) << std::endl; changestuff(rect); std::cout << "x,y: " << rect.get_x() << rect.get_y() << std::endl; Rectangle* rectTwo = new Rectangle(); rectTwo->set_x(15); rectTwo->set_y(30); std::cout << "x,y: " << rect.get_x() << rect.get_y() << std::endl; changestuff(*rectTwo); std::cout << "x,y: " << rect.get_x() << rect.get_y() << std::endl; std::cout << rectTwo << std::endl; } void changestuff(Rectangle& rec) { rec.set_x(10); rec.set_y(11); } Now, the actual Rectangle object isn't passed, merely a reference to it; it's address. Why should I use the 2nd method over the first one? Why can't I pass rectTwo to changestuff, but *rectTwo? In what way does rectTwo differ from rect?
There really isn't any reason you can't. In C, you only had pointers. C++ introduces references and it is usually the preferred way in C++ is to pass by reference. It produces cleaner code that is syntactically simpler. Let's take your code and add a new function to it: #include <iostream> #include "Rectangle.h" void changestuff(Rectangle& rec); void changestuffbyPtr(Rectangle* rec); int main() { Rectangle rect; rect.set_x(50); rect.set_y(75); std::cout << "x,y: " << rect.get_x() << rect.get_y() << sizeof(rect) << std::endl; changestuff(rect); std::cout << "x,y: " << rect.get_x() << rect.get_y() << std::endl; changestuffbyPtr(&rect); std::cout << "x,y: " << rect.get_x() << rect.get_y() << std::endl; Rectangle* rectTwo = new Rectangle(); rectTwo->set_x(15); rectTwo->set_y(30); std::cout << "x,y: " << rectTwo->get_x() << rectTwo->get_y() << std::endl; changestuff(*rectTwo); std::cout << "x,y: " << rectTwo->get_x() << rectTwo->get_y() << std::endl; changestuffbyPtr(rectTwo); std::cout << "x,y: " << rectTwo->get_x() << rectTwo->get_y() << std::endl; std::cout << rectTwo << std::endl; } void changestuff(Rectangle& rec) { rec.set_x(10); rec.set_y(11); } void changestuffbyPtr(Rectangle* rec) { rec->set_x(10); rec->set_y(11); } Difference between using the stack and heap: #include <iostream> #include "Rectangle.h" Rectangle* createARect1(); Rectangle* createARect2(); int main() { // this is being created on the stack which because it is being created in main, // belongs to the stack for main. This object will be automatically destroyed // when main exits, because the stack that main uses will be destroyed. Rectangle rect; // rectTwo is being created on the heap. The memory here will *not* be released // after main exits (well technically it will be by the operating system) Rectangle* rectTwo = new Rectangle(); // this is going to create a memory leak unless we explicitly call delete on r1. Rectangle* r1 = createARectangle(); // this should cause a compiler warning: Rectangle* r2 = createARectangle(); } Rectangle* createARect1() { // this will be creating a memory leak unless we remember to explicitly delete it: Rectangle* r = new Rectangl; return r; } Rectangle* createARect2() { // this is not allowed, since when the function returns the rect will no longer // exist since its stack was destroyed after the function returns: Rectangle r; return &r; } It should also be worth mentioning that a huge difference between pointers and references is that you can not create a reference that is uninitialized. So this perfectly legal: int *b; while this is not: int& b; A reference has to refer to something. This makes references basically unusable for polymorphic situations, in which you may not know what the pointer is initialized to. For instance: // let's assume A is some interface: class A { public: void doSomething() = 0; } class B : public A { public: void doSomething() {} } class C : public A { public: void doSomething() {} } int main() { // since A contains a pure virtual function, we can't instantiate it. But we can // instantiate B and C B* b = new B; C* c = new C; // or A* ab = new B; A* ac = new C; // but what if we didn't know at compile time which one to create? B or C? // we have to use pointers here, since a reference can't point to null or // be uninitialized A* a1 = 0; if (decideWhatToCreate() == CREATE_B) a1 = new B; else a1 = new C; }
2,213,894
2,213,898
Can I call a copy constructor explicitly?
I'm a little confused as to the mechanics of the copy constructor. Correct me if I'm wrong: If a method takes a reference to an object as a parameter, and the class defines a copy construtor, then the class uses the constructor to create a copy of itself and that gets passed to the function instead of a reference to the original object? Furthermore, one can call Object * obj = new Object(&anotherObject); to create a copy of anotherObject?
No, if a function take a reference: void f1( Object & o ); // call by reference then no copy is made. If a function takes a value: void f2( Object o ); // call by value then a copy is created by the compiler using the copy constructor. And yes, when you say: Object * obj = new Object(anotherObject); // not &anotherObject the copy constructor is used explicitly (assuming anotherObject is of type Object.) There is nothing magic about the use of new here, however - in this case: Object obj2(anotherObject); the copy constructor is also used.
2,213,957
2,214,217
Member Function Pointer with base class argument accepting derived class argument
So I'm working on this event management class. I'm storing a list of pointers to member functions of the signature void (Event*) where Event is just a struct that stores some random data at the moment. typedef boost::function<void(Event*)> Callback; typedef vector<Callback> CallbackList; class EventManager { public: template<typename T> void RegisterEventHandler(const std::string& type, void (T::*handler)(Event*), T* obj) { mCallbackList[type].push_back(boost::bind(handler, obj, _1)); } void DispatchEvent(const std::string& type, Event* evt) { for(CallbackList::iterator it = mCallbackList[type].begin(); it != mCallbackList[type].end(); ++it) { Callback callback = (*it); callback(evt); } } private: hash_map<std::string, CallbackList> mCallbackList; }; I'm wondering, if it's possible for me to derive different versions of Event, and pass pointers to those member functions into this class? Currently I'm trying this. class MouseEvent : public Event { public: int testMouseData1; int testMouseData2; int testMouseData3; }; class HelloWorld { public: void Display(MouseEvent* evt) { cout << "Hello, world!" << endl; } }; int main(void) { MouseEvent* evt = new MouseEvent(); HelloWorld* world = new HelloWorld(); eventManager->RegisterEventHandler("testType", &HelloWorld::Display, world); return 0; } This gives me the following error in XCode. error: no matching function for call to 'EventManager::RegisterEventHandler(const char [9], void (HelloWorld::*)(MouseEvent*), HelloWorld*&)' Do you know how I can safely pass in a pointer that's expecting a derived class in its function signature? Thanks.
So I found a solution that seems to be working for me, but I'm not sure if it's entirely safe to do. I changed the RegisterEventHandler method to cast all of the function pointers that I send in to the same type... template<typename T1, typename T2> void RegisterEventHandler(const String& type, T1 handler, T2* obj) { void (T2::*evtHandler)(Event*) = (void (T2::*)(Event*)) (handler); mCallbackList[type].push_back(boost::bind(evtHandler, obj, _1)); } now it all seems to just work as I originally intended. But I'm pretty new to all this so I'm not entirely sure if this is a safe thing to do. Any thoughts? Thanks
2,214,053
2,215,085
C++ redirect outgoing connections
Is there any way in C++ on windows to monitor a program and redirect any outgoing requests it makes on a specific port? I have a simple C++ http proxy and want it to be able to automatically redirect all browser requests on port 80 through itself.
The simple way to do it is to create a Windows kernel hook to trap socket requests and reroute them to your proxy. Some useful documentation on this is: http://www.internals.com/articles/apispy/apispy.htm If you're using Windows Vista or better, consider Windows Filtering Platform (WFP): http://www.microsoft.com/whdc/device/network/wfp.mspx Also consider looking at Detours (commercial) and EasyHook (free). They significantly simplify the process of writing hooks and redirecting API calls (both Win32 and Application).
2,214,295
2,214,316
Is it impossible to use an STL map together with a struct as key?
I have the following code: struct Node { int a; int b; }; Node node; node.a = 2; node.b = 3; map<int, int> aa; aa[1]=1; // OK. map<Node, int> bb; bb[node]=1; // Compile error. When I tried to map an instance of my struct Node to an int, I got a compile error. Why?
For a thing to be usable as a key in a map, you have to be able to compare it using operator<(). You need to add such an operator to your node class: struct Node { int a; int b; bool operator<( const Node & n ) const { return this->a < n.a; // for example } }; Of course, what the real operator does depends on what comparison actually means for your struct.
2,214,679
2,215,880
supplying dependency through base class
I have a list of Parts and some of them need a pointer to an Engine, lets call them EngineParts. What I want is to find these EngineParts using RTTI and then give them the Engine. The problem is how to design the EnginePart. I have two options here, described below, and I don't know which one to choose. Option 1 is faster because it does not have a virtual function. Option 2 is easier if I want to Clone() the object because without data it does not need a Clone() function. Any thoughts? Maybe there is a third option? Option 1: class Part; class EnginePart : public Part { protected: Engine *engine public: void SetEngine(Engine *e) {engine = e} }; class Clutch : public EnginePart { // code that uses this->engine } Option 2: class Part; class EnginePart : public Part { public: virtual void SetEngine(Engine *e)=0; }; class Clutch : public EnginePart { private: Engine *engine; public: void SetEngine(Engine *e) { engine = e; } // code that uses this->engine } (Note that the actual situation is a bit more involved, I can't use a simple solution like creating a separate list for EngineParts) Thanks
Too bad that the reply stating that 'a part cannot hold the engine' is deleted because that was actually the solution. Since not the complete Engine is needed, I found a third way: class Part; class EngineSettings { private: Engine *engine friend class Engine; void SetEngine(Engine *e) {engine = e} public: Value* GetSomeValue(params) { return engine->GetSomeValue(params); } }; class Clutch : public Part, public EngineSettings { // code that uses GetSomeValue(params) instead of engine->GetSomeValue(params) } Because GetSomeValue() needs a few params which Engine cannot know, there is no way it could "inject" this value like the engine pointer was injected in option 1 and 2. (Well.. unless I also provide a virtual GetParams()). This hides the engine from the Clutch and gives me pretty much only one way to code it.
2,214,727
2,214,808
Why am I getting Debug assertion failed after strcpy_s?
im just starting to learn about sockets and i have been given this code, and i have to make the port lookup logic work. But the problem is i keep getting this run time error and I dont know why? // portlookup.cpp // Given a service name, this program displays the corresponding port number. #include <iostream> #pragma comment(lib, "ws2_32.lib") #include <winsock2.h> using namespace std; int main (int argc, char **argv) { char service[80]; // This string contains name of desired service struct servent *pse; // pointer to service information entry short port; // Port # (in Network Byte Order) of desired service if (argc < 2) { cout << "Please specify a service." << endl; } strcpy_s(service, sizeof(service), argv[1]); WORD wVersion = 0x0202; WSADATA wsaData; int iResult = WSAStartup(wVersion, &wsaData); // Returns zero if successful if (iResult != 0) { cout << "Insufficient resources to startup WINSOCK." << endl; return 0; } port = htons( (u_short) atoi(service)); // 1st try to convert string to integer if (port == 0) { // if that doesn't work, call service function pse = getservbyname(service,NULL); if (pse) { port = pse->s_port; } else { cout << "Invalid service request." << endl; return INVALID_SOCKET; } } cout << "Service: " << service << endl; cout << "Port: " << htons(port) << endl; }
Your problem appears to be that you aren't passing a command line, you check argc < 2, but when it is < 2 you execute the strcpy_s anyway. In Visual Studio, Got to the Project Properties dialog, from there go to the Debugging page and add the service name to Command Arguments And fix your argument checking code if (argc < 2) { //cout << "Please specify a service." << endl; cerr << "error: no service specified." << endl; return EXIT_FAILURE; // return some non-zero value to indicate failure. }
2,214,805
2,214,832
How do you use a bubble sort with pointers in c++?
So here's what I have so far: void sortArray(int amountOfScores, int* testScores) { for(int i = 0; i < amountOfScores; i++) { for(int j = 0; j < amountOfScores-1; j++) { if(*(testScores+i) > *(testScores+j+1)) { int temp = *(testScores+j); *(testScores+j) = *(testScores+j+1); *(testScores+j+1) = temp; } } } for(int i = 0; i < amountOfScores; i++) { cout << *(testScores+i) << endl; } } Basically I'm trying to read in however many numbers the user wants to input, then sort them in ascending order. Catch is I have to use pointers and I've never really understood them. This code above works for 3 numbers, however, adding any more causes it to not sort them...I've tried trouble shooting as best I could but without any knowledge in pointers I don't know what I'm looking for. Thanks for the help!
You problem might be here: if(*(testScores+i) > *(testScores+j+1)) Did you mean: if(*(testScores+j) > *(testScores+j+1)) (Note i replaced by j). btw, in Bubble sort, if there are no swaps, you should break. This will cause a speed up in some cases.
2,214,812
2,214,831
How to provide many constructors, but without too many dependencies?
This is a pretty basic C++ design question: I have a class that contains some data which is read-only, once the object is constructed: class Foo { private: class Impl; Impl* impl_; public: int get(int i); // access internal data elements }; Now, I'd like to implement several ways to construct a Foo object and fill it with data: from std::istream, from an iterator, a vector, etc. What's the best way to implement that? I could just add all those constructors directly in Foo, but I don't really want the Foo user to have to include std::istream etc. I'm also worried about classes containing too much code. What is the most idiomatic way to do this? I guess, add some private addElement function, and then define friend factory functions that create Foo objects by reading data, calling addElement and return the constructed object? Any other options?
If you want to construct something from a range, perhaps: class X { public: template <class InputIterator> X(InputIterator first, InputIterator last); }; Usage: //from array X a(array, array + array_size); //from vector X b(vec.begin(), vec.end()); //from stream X c((std::istream_iterator<Y>(std::cin)), std::istream_iterator<Y>());
2,214,965
2,215,038
Cross platform Networking API
I was wondering if there was an API to do networking that would work on Windows, Mac and Linux. I would like to make a card game that 2 people can play through a TCP connection.
There are a few options for this, some easier to use than others: APR (Apache Portable Runtime) - Very popular. Quite easy to use. Includes lots of additional features handy for network programming (threads, mutexes, etc.) ACE - Popular among the embedded space. Personally, I found it quite a complicated API, and not very straightforward to use. Boost - If you have a decent level of sophistication with C++ (templates, metaprogramming, etc.), then Boost libraries are generally very good. I'm not sure how popular the Boost asynchronous networking libraries are in the real world. QT - Popular as a UI toolkit, but has a great set of threading, event management, networking libraries. IMO, this is by far the easiest to use. It's important to stay away from using the berkeley sockets library, as the implementations across operating systems vary wildly, and you'll lose a fair bit of time to tuning them as you port your software across OSs. My personal preference: APR.
2,214,977
2,215,016
Compiling command line Linux program on Windows
I need to write a relatively simple command line C++ program to be run a Linux environment. However, I would like to code as well as compile this on Windows. The reason I don't want to port it to Linux is because it requires MySQL interactions, and that would require some messy porting (IMO). It does not have to run on Windows; I just want to compile it on Windows because I want to use my preferred IDE's. I've looked up on Cygwin for this task, but I haven't been able to find any documentation to do what I'm trying to do.
(I'm assuming "..don't want to port it to Linux.." is a typo for "..from Linux" and that you want the code to run in Linux as you said in your first sentence. This means cygwin or mingw would only be used as cross compilers and aren't going to be very useful.) This program already builds and works (or mostly works) on Linux, right? No reason to change that. Use your preferred editor (probably the one in your IDE) to edit the files and then just run the build system (probably make) in a Linux system (possibly in a VM). Export the files using a samba share (especially easy from a VM) so you can edit and automatically save remotely. Note that you seem fine ditching every other feature of your IDE (debugger and compiler, mainly) and just using the editor part anyway. Ah, are you not starting from any existing project and want to write this from scratch? If so, porting doesn't make any sense. You want to write cross-platform code. (Cross-platform or "portable code" being related to, but different than, the act of "porting code" from one platform to another.) The code is then both "Windows code" and "Linux code" at the same time, and you can use any compiler on Windows that can accept the code. Usually this happens by you sticking to standard libraries and other portable libraries, or writing shims for non-portable libraries to give them a portable interface, with the compiler supporting the C++ Standard. You can use your preferred IDE's compiler and debugger in this case, and don't need cygwin or mingw. (Unless they're used by your preferred IDE. :P)
2,215,033
2,215,111
MinGW vs Visual Studio 2008 output code quality
A few days ago I was told that recent versions of g++ produce "better" x86 code than MSVC 2008. Basically GCC with full optimization produces faster applications than MSVC with full optimizations. While it's certainly correct to state that this, if true, depends a great deal on the application and the C++ code used (and I'm in the process of evaluating this claim for my application), I'm wondering what do others think. In essence, what have been your personal experiences when comparing the output of these two compilers? I'm asking about MinGW, but if your experience with vanilla GCC is somehow valid here, feel free to share that too.
My experience is compiling my C++ JPEG-LS image compression project. http://charls.codeplex.com For me, Visual C++ was significantly faster. I compiled it mostly with G++ on linux. After a lot of tuning, the G++ version was still about 10-15% slower on the same hardware (the same physical machine, dual booted as linux). That was after many hours of searching for G++ optimization options that actually helped. Just compiling with default optimizations G++ was 60% slower than Visual C++. My project is perhaps somewhat a-typical because it is not C, but C++ and requires the compiler to do a lot of inlining. On both compilers, I enforce inlining to happen. Also, it was offered to me as an explanation that the x86 has very few registers, and G++ was not good at allocating them. Update: For a more thorough comparison of microsoft and gnu compilers, go to this C compiler benchmark. According to how I read these figures, the difference between Microsoft and GCC for 32 bit are on par with each other, although GCC is tested with profile guided optimization(PGO) and Microsoft isn't (there's no PGO in VS Express). Without PGO, Microsoft is faster on 32 bit. On 64 bit, GCC is faster. Intel is still faster than either on either platform.
2,215,040
2,215,225
operator overloading c++
When overloading operators, is it necessary to overload >= <= and !=? It seems like it would be smart for c++ to call !operator= for !=, !> for operator<= and !< for operator>=. Is that the case, or is it necessary to overload every function?
Yes, it is necessary, if you want all of them to work the way you want them to work. C++ does not force any specific semantics on most of the overloadable operators. The only thing that is fixed is the general syntax for the operator (including being unary or binary and things like precedence and associativity). This immediately means that the actual functionality that you implement in your overload can be absolutely arbitrary. In general case there might not be any meaningful connection between what operator == does and what operator != does. Operator == might write data to a file, while operator != might sort an array. While overloading operators in such an arbitrary fashion is certainly not a good programming practice, the C++ language cannot assume anything. So, no, it cannot and will not automatically use ! == combination in place of !=, or ! > combination in place of <=.
2,215,132
2,215,266
Selecting nodes with probability proportional to trust
Does anyone know of an algorithm or data structure relating to selecting items, with a probability of them being selected proportional to some attached value? In other words: http://en.wikipedia.org/wiki/Sampling_%28statistics%29#Probability_proportional_to_size_sampling The context here is a decentralized reputation system and the attached value is therefore the value of trust one user has in another. In this system all nodes either start as friends which are completely trusted or unknowns which are completely untrusted. This isn't useful by itself in a large P2P network because there will be many more nodes than you have friends and you need to know who to trust in the large group of users that aren't your direct friends, so I've implemented a dynamic trust system in which unknowns can gain trust via friend-of-a-friend relationships. Every so often each user will select a fixed number (for the sake of speed and bandwidth) of target nodes to recalculate their trust based on how much another selected fixed number of intermediate nodes trust them. The probability of selecting a target node for recalculation will be inversely proportional to its current trust so that unknowns have a good chance of becoming better known. The intermediate nodes will be selected in the same way, except that the probability of selection of an intermediary is proportional to its current trust. I've written up a simple solution myself but it is rather slow and I'd like to find a C++ library to handle this aspect for me. I have of course done my own search and I managed to find TRSL which I'm digging through right now. Since it seems like a fairly simple and perhaps common problem, I would expect there to be many more C++ libraries I could use for this, so I'm asking this question in the hope that someone here can shed some light on this.
This is what I'd do: int select(double *weights, int n) { // This step only necessary if weights can be arbitrary // (we know total = 1.0 for probabilities) double total = 0; for (int i = 0; i < n; ++i) { total += weights[i]; } // Cast RAND_MAX to avoid overflow double r = (double) rand() * total / ((double) RAND_MAX + 1); total = 0; for (int i = 0; i < n; ++i) { // Guaranteed to fire before loop exit if (total <= r && total + weights[i] > r) { return i; } total += weights[i]; } } You can of course repeat the second loop as many times as you want, choosing a new r each time, to generate multiple samples.
2,215,250
2,215,398
C++ Error: explicit qualification
What do these errors mean? Vector.cpp:13: error: ISO C++ forbids declaration of ‘Vector’ with no type Vector.cpp:13: error: explicit qualification in declaration of ‘void Vector::Vector(double, double, double)’ The C++ (Line 13 is the Vector::Vector( ...): #include <iostream> using namespace std; namespace Vector { Vector::Vector( double x, double y, double z) { a = x; b = y; c = z; } /* double Vector::dot(const Vector &v) const { return (a*v.a)+(b*v.b)+(c*v.c); } */ Vector Vector::operator+(const Vector &v) const { Vector v1( a + v.a, b + v.b, c + v.c ); return v1; } Vector Vector::operator-(const Vector &v) const { Vector v1( a - v.a, b - v.b, c - v.c ); return v1; } bool Vector::operator==(const Vector &v) const { if( (a == v.a) && (b == v.b) && (c == v.c) ) { return true; } else { return false; } } Vector Vector::operator*(const Vector &v) const { Vector v1( b*v.c - c*v.b, c*v.a - a*v.c, a*v.b - b*v.a ); return v1; } ostream& operator<<(ostream &out, const Vector &v) { out << "<" << v.a << ", " << v.b << ", " << v.c << ">"; return out; } istream& operator>>(istream &in, Vector &v) { in >> v.a; in >> v.b; in >> v.c; return in; } /* double length( Vector v ) { return sqrt( (v.a*v.a)+(v.b*v.b)+(v.c*v.c) ); } */ } // end namespace Vector The header file: #ifndef _VECTOR_H #define _VECTOR_H #include <cstdlib> #include <iostream> using namespace std; namespace Vector { class Vector { private: double a; double b; double c; public: Vector( double x=0.0, double y=0.0, double z=0.0); double dot(const Vector &v) const; Vector operator+(const Vector &v) const; Vector operator-(const Vector &v) const; bool operator==(const Vector &v) const; Vector operator*(const Vector &v) const; friend ostream& operator<<(ostream &out, const Vector &v); friend istream& operator>>(istream &in, Vector &v); }; // end Vector class double length(Vector v); } //end namespace Vector #endif /* _VECTOR_H */
Looks like the major problem is that your cpp files didn't include your header file.
2,215,339
2,215,415
Can competing atomic operations starve one another?
Imagine a program with two threads. They are running the following code (CAS refers to Compare and Swap): // Visible to both threads static int test; // Run by thread A void foo() { // Check if value is 'test' and swap in 0xdeadbeef while(!CAS(&test, test, 0xdeadbeef)) {} } // Run by thread B void bar() { while(1) { // Perpetually atomically write rand() into the test variable atomic_write(&test, rand()); } } Is it possible for thread B to perpetually cause thread A's CAS to fail such that 0xdeadbeef is never written to 'test'? Or does natural scheduling jitter mean that in practice this never happens? What if some work was done inside thread A's while loop?
As a theoretical matter, yes. If you could manage somehow to get the two threads running in lockstep like this time thread A thread B ---- -------- -------- || CAS || atomic_write || CAS \/ atomic_write Then CAS would never return true. In practice this will never happen when threads share a CPU/Core, and is unlikely to happen when threads are running on different CPUs or Cores. In practice it's incredibly unlikely to happen for more than few cycles, and astronomically unlikely to happen for more than a scheduler quantum. And that's if this code void foo() { // Check if value is 'test' and swap in 0xdeadbeef while(!CAS(&test, test, 0xdeadbeef)) {} } does what it appears to do, which is to fetch the current value of test, and compare it to test to see if it has changed. In the real world iterations of CAS would be separated by code that did actual work. The volatile keyword would be needed to insure that the compiler fetched test before calling CAS rather than assuming that a copy it might still have in a register would still be valid. Or the value that you would be testing against wouldn't be the current value of test, but rather some sort of last known value. In other words, this code example is a test of the theory, but you wouldn't use CAS like this in practice, so even if you could get this to fail, it doesn't necessarily tell you how it could fail when used in real world algorithms.
2,215,365
2,215,418
partial specialization of function template
Can anybody explain why partial specialization is not valid for function template but it's fine for class template. I understand partial specialization might make the compiler get confused with function overloading, but I still need more information to make me totally understand. Can anybody offer me some neat examples?
Getting confused is enough of a reason, in this case. And there's an existing alternative solution: overloading. The committee spent a lot of effort (it seems to me, I wasn't there) getting function overload resolution working for templates, and surely part of the reason for that included not having to solve the less-general, hard problem of function template partial specialization.
2,215,441
2,215,506
With my global hook installed, how do I know when a window begins to move and when it stops moving?
Is there an easy way to figure this out? I guess I can use WM_MOVE to tell me when it begins by keeping a timer. If the window has not received a WM_MOVE message within the last 2 seconds, then I know that it has just begun to move. Then I set another timer and wait for their not to be a message within a period of time (2 seconds). If nothing is received, then I can be confident that the window move has finished. Is this the right way to go about this?
If you are in a position to see WM_MOVE messages, then you are also in a position to see WM_ENTERSIZEMOVE and WM_EXITSIZEMOVE messages.
2,215,549
2,215,660
How to use/link gdLibrary (libgd) with MS Visual C++ (e.g. 2008 Express Edition)? Getting LNK2019 errors
I have to use the gdLibrary (http://www.libgd.org) in a C++ App on MS Windows XP Prof. SP3 32bit - and I'm trying and googleing for two days now without success. Does anyone of you use libgd with MS VC++ 200x EE? My problem: It has to to compile with MS Visual C++ (e.g. the 2008 Express Edition - fixed 3rd party condition)... but currently the linker crashes, with 11 of the following LNK2019 errors: Linking... codereate.obj : error LNK2019: An undefined external symbol "_gdImageDestroy" was found in "public: virtual __thiscall CodeCreate::~CodeCreate(void)" The other smybols are _gdImageColorExact, _gdImageCopyResized and some other gd-functions. It seems that the VC++ linker does not work correctly with the bgd.lib provided by the package I downloaded from http://www.libgd.org/releases/gd-latest-win32.zip. What I did/tried: Extracted gd-latest-win32.zip to c:\users\johndoe\cpp\libgd. Defined c:\users\johndoe\cpp\libgd\lib als additional library dir (global VC++ setting) Defined c:\users\johndoe\cpp\libgd\include as additional includes dir (global VC++ setting) Defined c:\users\johndoe\cpp\libgd\include\lib\bgd.lib as additional linker\input dependency (project setting) I even added #pragma comment(lib, "libgd.lib") into my codecreate.h to be on the save side. Any suggestions? What am I doing wrong (e.g. have I forget to install something)? Is there any "trick" to get a VC++ 2008 compatible bgd.lib? Additional notes: Running on Linux/g++, everything works fine, no warnings with -pedantic -ansi -wAll. The program does its job an generates some barcodes. It works when using DevC++ for Win32. Therefore it is no Windows issue, "just" a VC++ issue. For DevC++ I did: I just downloaded http://www.libgd.org/releases/gd-latest-win32.zip, extracted it to c:\users\johndoe\cpp\libgd added c:\users\johndoe\cpp\libgd\lib\bgd.lib as additional obbject in the linker-projects settings. defined c:\users\johndoe\cpp\libgd\lib als additional library dir, defined c:\users\johndoe\cpp\libgd\include as additional includes dir happy about some barcode stuff If I can't get It working, I'm really in trouble... becoming really desperate right now :-(
Did you put NODLL definition in your project? If you did that, you should use bgd_a.lib instead. And you also need to make sure you have defined WIN32. I tried to create a simple project with latest release and it does linked success. If I add NODLL without changing tot bgd_a then I get the same error message.
2,215,609
2,217,731
Problem in luabind with default_converter and tables
===Edit=== The problem is actually much simpler than this, any wrapped function that takes a table is causing the problem. If I wrap a function that takes luabind::object, and call that function with a table argument, then the gc causes an invalid free(). I'm starting to think that this may be some kind of crazy compilation/linking problem, as my compiled luabind dylib has lua symbols in it (resulting in two copies of those symbols, one in that library and one in my binary). Maybe I have duplicates of some lua static variables or something? I might just be grasping at straws here. ===Edit=== Using luabind 0.9 and gcc 4.2.1 on mac os x 10.6 I'm seeing what could (maybe?) be a problem with using a default_converter from lua tables. I'm trying to define converters for various list-like types in my code, specifically std::vector. When I pass a table to a c++ method with such a default_converter, lua crashes with free() on an invalid pointer as soon as the garbage collector is called. I'm probably missing something simple here, but I can't figure it out. Thanks! * Lua Code * function first () -- Doesn't crash -- t = TestClass(1, 3) -- Crashes t = TestClass({1, 2, 3}) print(t:get(0)) print(t:get(1)) print(t:get(2)) end function second () print("About to call collectgarbage...") collectgarbage() print("Done calling collectgarbage!") end function test () first() second() end * C++ Code * #include <iostream> #include <lua.hpp> #include <luabind/luabind.hpp> #include <luabind/operator.hpp> using namespace std; using namespace luabind; namespace luabind { template<typename ListType> struct default_converter<std::vector<ListType> > : native_converter_base<std::vector<ListType> > { static int compute_score(lua_State* L, int index) { return lua_type(L, index) == LUA_TTABLE ? 0 : -1; } std::vector<ListType> from(lua_State* L, int index) { std::vector<ListType> list; for (luabind::iterator i(luabind::object(luabind::from_stack(L, index))), end; i != end; ++i) list.push_back(luabind::object_cast<ListType>(*i)); return list; } void to(lua_State* L, const std::vector<ListType>& l) { luabind::object list = luabind::newtable(L); for (size_t i = 0; i < l.size(); ++i) list[i+1] = l[i]; list.push(L); } }; } class TestClass { public: TestClass(std::vector<int> v) : m_vec(v) {} TestClass(int b, int e) { for (int i = b; i <= e; ++i) m_vec.push_back(i); } int get(size_t i) const { return m_vec[i]; } private: std::vector<int> m_vec; }; int main(int argc, char** argv) { if (argc != 2) { cout << "usage: " << argv[0] << " <scriptname>" << endl; return -1; } std::string scriptName = argv[1]; lua_State* L = (lua_State*) lua_open(); luaL_openlibs(L); open(L); module(L) [ class_<TestClass>("TestClass") .def(constructor<std::vector<int> >()) .def(constructor<int, int>()) .def("get", &TestClass::get) ]; if (luaL_loadfile(L, scriptName.c_str()) || lua_pcall(L, 0, 0, 0)) { cout << "Script error: " << lua_tostring(L, -1) << endl; return -1; } call_function<void>(globals(L)["test"]); lua_close(L); return 0; }
Yeah, I figured it out. Turns out that luabind didn't have any problems at all, except for the way it was built. The jam build system, on mac os x, causes the static lua library to be linked in with the luabind shared library, causing duplicate symbols (and duplicate static variables) when I link my final binary. It didn't have the entire lua library linked in though, so you still have to link liblua.a in again. Take this explanation with a grain of salt, but it's my best guess; I'm not an expert at how the Mac OS X linker works. I do know that when I built luabind statically, everything works fine. So, for anyone building lubabind in mac, build statically. There are also other problems with the jam built shared lib that you'd have to fix, like the fact that @executable_path is wrong. Static build was dead simple.
2,215,846
2,215,858
Values of Argv when something is not entered from command line
Hi I was wondering what values would argv[1] or argv[2] be, if i failed to provide it with command line arguments
It would be garbage NULL. Therefore you should always first test the argc (argument count) before trying to access the command line arguments. See this for more detailed information.
2,215,856
2,215,865
Compiling nonessential object files with GCC
Consider the following example g++ a.o b.o c.o -o prog If it is the case that c.o does not contribute any executable code to prog, nor are there any dependencies on c.o in any of the other files, will GCC yet include the contents of c.o in prog? Said another way, aside from compilation time, what (if any) negative consequences can there be of compiling unnecessary files into an executable? Thanks in advance; Cheers!
There aren't any negative consequences except that your executable might be unnecessarily large. The linker can probably dead strip unused code for you, and that will shrink things back down. You can use some kind of object viewing tool (otool, objdump, nm, etc.) on the output executable to see if your program has extra symbols in it. I'm using a Mac, so there will be some differences if you're using the standard set of gcc tools, but here's an example: $ make gcc -o app main.c file2.c gcc -Wl,-dead_strip -o app_strip main.c file2.c $ ls -l app* -rwxr-xr-x 1 carl staff 8744 Feb 6 20:05 app -rwxr-xr-x 1 carl staff 8704 Feb 6 20:05 app_strip I think in the non-Apple gcc world, you would pass -Wl,--gc-sections instead of the -Wl,-dead_strip in my example. The size difference in the two executables you can see is due to the extra function being stripped: $ nm app | cut -c 20- > app.txt $ nm app_strip | cut -c 20- > app_strip.txt $ diff app.txt app_strip.txt 8d7 < _function2
2,215,930
2,215,970
Where to get simple opensource adpcm C\C++ encoder lib?
Where to get simple opensource pcm to adpcm C\C++ encoder lib?
The sox package can deal with several varieties of ADPCM both as a source and destination format.
2,215,961
2,216,040
Is Communicating Sequential Processes ever used in large multi threaded C++ programs?
I'm currently writing a large multi threaded C++ program (> 50K LOC). As such I've been motivated to read up alot on various techniques for handling multi-threaded code. One theory I've found to be quite cool is: http://en.wikipedia.org/wiki/Communicating_sequential_processes And it's invented by a slightly famous guy, who's made other non-trivial contributions to concurrent programming. However, is CSP used in practice? Can anyone point to any large application written in a CSP style? Thanks!
CSP, as a process calculus, is fundamentally a theoretical thing that enables us to formalize and study some aspects of a parallel program. If you instead want a theory that enables you to build distributed programs, then you should take a look to parallel structured programming. Parallel structural programming is the base of the current HPC (high-performance computing) research and provides to you a methodology about how to approach and design parallel programs (essentially, flowcharts of communicating computing nodes) and runtime systems to implements them. A central idea in parallel structured programming is that of algorithmic skeleton, developed initially by Murray Cole. A skeleton is a thing like a parallel design pattern with a cost model associated and (usually) a run-time system that supports it. A skeleton models, study and supports a class of parallel algorithms that have a certain "shape". As a notable example, mapreduce (made popular by Google) is just a kind of skeleton that address data parallelism, where a computation can be described by a map phase (apply a function f to all elements that compose the input data), and a reduce phase (take all the transformed items and "combine" them using an associative operator +). I found the idea of parallel structured programming both theoretical sound and practical useful, so I'll suggest to give a look to it. A word about multi-threading: since skeletons addresses massive parallelism, usually they are implemented in distributed memory instead of shared. Intel has developed a tool, TBB, which address multi-threading and (partially) follows the parallel structured programming framework. It is a C++ library, so probably you can just start using it in your projects.
2,216,017
2,216,178
dynamical two dimension array according to input
I need to get an input N from the user and generate a N*N matrix. How can I declare the matrix? Generally, the size of the array and matrix should be fixed at the declaration, right? What about vector<vector<int>> ? I never use this before so I need suggestion from veteran.
Boost implements matrices (supporting mathematical operations) in its uBLAS library, and provides usage syntax like the following. #include <boost/numeric/ublas/matrix.hpp> int main(int argc, char* argv[]) { unsigned int N = atoi(argv[1]); boost::matrix<int> myMatrix(N, N); for (unsigned i = 0; i < myMatrix.size1 (); ++i) for (unsigned j = 0; j < myMatrix.size2 (); ++j) myMatrix(i, j) = 3 * i + j; return 0; }
2,216,029
2,216,092
Common pattern for library initialization and shutdown?
Is there a pattern that I may use for calling the required initialization and cleanup routines of an underlying (C) library? In my case, I would like to create the wrapper class so that it can be composed into other objects. The problem is that, when I destroy the wrapper class, the cleanup routines of the underlying library are called. That's fine until I instantiate multiple objects of my wrapper class. My question is what is the best way to really handle this situation? A static reference counter comes to mind, but I wanted to know if there were other potentially better options and the trades involved.
Not everything has to be a class. The Singleton pattern would let you turn this into a class, but it's really not buying you anything over global functions: bool my_library_init(); void my_library_shutdown(); The first call returns true if the library was successfully initialized, the second just quietly does whatever needs to be done and exits. You can add whatever reference counting or thread tracking type stuff behind these interfaces you like. Also, don't neglect the possibility that your library may be able to do all of this transparently. When the first library function is called, could it detect that it is not initialized yet and set everything up before doing the work? For shutdown, just register the resources to be destroyed with a global object, so they are destroyed when the program exits. Doing it this way is certainly trickier, but may be worth the usability benefit to your library's callers.
2,216,041
2,216,114
Prevent unnecessary copies of C++ functor objects
I have a class which accumulates information about a set of objects, and can act as either a functor or an output iterator. This allows me to do things like: std::vector<Foo> v; Foo const x = std::for_each(v.begin(), v.end(), Joiner<Foo>()); and Foo const x = std::copy(v.begin(), v.end(), Joiner<Foo>()); Now, in theory, the compiler should be able to use the copy elision and return-value optimizations so that only a single Joiner object needs to be created. In practice, however, the function makes a copy on which to operate and then copies that back to the result, even in fully-optimized builds. If I create the functor as an lvalue, the compiler creates two extra copies instead of one: Joiner<Foo> joiner; Foo const x = std::copy(v.begin(), v.end(), joiner); If I awkwardly force the template type to a reference it passes in a reference, but then makes a copy of it anyway and returns a dangling reference to the (now-destroyed) temporary copy: x = std::copy<Container::const_iterator, Joiner<Foo>&>(...)); I can make the copies cheap by using a reference to the state rather than the state itself in the functor in the style of std::inserter, leading to something like this: Foo output; std::copy(v.begin(), v.end(), Joiner<Foo>(output)); But this makes it impossible to use the "functional" style of immutable objects, and just generally isn't as nice. Is there some way to encourage the compiler to elide the temporary copies, or make it pass a reference all the way through and return that same reference?
You have stumbled upon an often complained about behavior with <algorithm>. There are no restrictions on what they can do with the functor, so the answer to your question is no: there is no way to encourage the compiler to elide the copies. It's not (always) the compiler, it's the library implementation. They just like to pass around functors by value (think of std::sort doing a qsort, passing in the functor by value to recursive calls, etc). You have also stumbled upon the exact solution everyone uses: have a functor keep a reference to the state, so all copies refer to the same state when this is desired. I found this ironic: But this makes it impossible to use the "functional" style of immutable objects, and just generally isn't as nice. ...since this whole question is predicated on you having a complicated stateful functor, where creating copies is problematic. If you were using "functional" style immutable objects this would be a non-issue - the extra copies wouldn't be a problem, would they?
2,216,143
2,216,149
Comparing chars in a character array with strcmp
I have read an xml file into a char [] and am trying to compare each element in that array with certain chars, such as "<" and ">". The char array "test" is just an array of one element and contains the character to be compared (i had to do it like this or the strcmp method would give me an error about converting char to cons char*). However, something is wrong and I can not figure it out. Here is what I am getting: < is being compared to: < strcmp value: 44 Any idea what is happening? char test[1]; for (int i=0; i<amountRead; ++i) { test[0] = str[i]; if( strcmp(test, "<") == 0) cout<<"They are equal"<<endl; else { cout<<test[0]<< " is being compare to: "<<str[i]<<" strcmp value= "<<strcmp(test, "<") <<endl; } }
you need to 0 terminate your test string. char test[2]; for (int i=0; i<amountRead; ++i) { test[0] = str[i]; test[1] = '\0'; //you could do this before the loop instead. ... But if you always intend to compare one character at a time, then the temp buffer isn't necessary at all. You could do this instead for (int i=0; i<amountRead; ++i) { if (str[i] == "<") cout<<"They are equal"<<endl; else { cout << str[i] << " is being compare to: <" << endl; } }
2,216,160
2,216,168
Splitting the string at Enter key
I'm getting the text from editbox and I'd want to get each name separated by enter key like the character string below with NULL characters. char *names = "Name1\0Name2\0Name3\0Name4\0Name5"; while(*names) { names += strlen(names)+1; } how would you do the same for enter key (i.e separated by /r/n) ? can you do that without using the std::string class?
Use strstr: while (*names) { char *next = strstr(names, "\r\n"); if (next != NULL) { // If you want to use the key, the length is size_t len = next - names; // do something with a string here. The string is not 0 terminated // so you need to use only 'len' bytes. How you do this depends on // your need. // Have names point to the first character after the \r\n names = next + 2; } else { // do something with name here. This version is 0 terminated // so it's easy to use // Have names point to the terminating \0 names += strlen(names); } } One thing to note is that this code also fixes an error in your code. Your string is terminated by a single \0, so the last iteration will have names point to the first byte after your string. To fix your existing code, you need to change the value of names to: // The algorithm needs two \0's at the end (one so the final // strlen will work and the second so that the while loop will // terminate). Add one explicitly and allow the compiler to // add a second one. char *names = "Name1\0Name2\0Name3\0Name4\0Name5\0";
2,216,234
2,216,255
Queue message processing with Multithreading
I have to design multithreaded module for a problem. And problem is, I have queue, there is a one thread which is putting messages in the message queue, and there are two thread say A and B, thread A process the even message (0,2,4..) and thread B processes the odd message(1,3,5..). I came up with two solution, first one is using two events(say X and Y) event X is for thread A and Y is for thread B. I check if the message is at even position, I set the event X for thread A, and Y for thread B otherwise. And the second solution is by having two seperate quest for each thread. A thread will put even position messages to queue of thread A and odd messages to the queue of thread B, with this solution thread A and B can work asynchronously. Am i right, or is there any other elegant solution? Thanks.
Using only one queue and synchronizing A and B in order to ensure a proper fetching sequence is a complete nonsense. Just use two queues, one for A and one for B, and ensure that they are filled correctly (which seems an easier and cleanier problem by far, even from a design PoV.
2,216,280
2,216,289
C++ auto conversions
For two unrelated classes "class A" and "class B" and a function B convert(const A&); Is there a way to tell C++ to automatically, for any function that takes "class B" as argument, to auto convert a "class A". Thanks!
What you would normally do in this case is give B a constructor that takes an A: class B { public: B(const A&); }; And do the conversion there. The compiler will say "How can I make A a B? Oh, I see B can be constructed from an A". Another method is to use a conversion operator: class A { public: operator B(void) const; } And the compiler will say "How can I make A a B? Oh, I see A can be converted to B". Keep in mind these are very easy to abuse. Make sure it really makes sense for these two types to implicitly convert to each other.
2,216,388
2,217,406
How to measure memory used in a block or program with C++
What is the best way to measure the memory used by a C++ program or a block in a C++ program. The measurement code should thereby be part of the code and it should not be measured from outside. I know of the difficulty of that task, so it does not have to be 100% accurate but at least give me a good impression of the memory usage.
Measuring at the block level will be difficult (at best) unless you're willing to explicitly add instrumentation directly to the code under test. I wouldn't start with overloads of new and delete at the class level to try to do this. Instead, I'd use overloads of ::operator new and ::operator delete. That's basically the tip of the funnel (so to speak) -- all the other dynamic memory management eventually comes down to calling those (and most do so fairly directly). As such, they will generally do the most to tell you about dynamic memory usage of the program as a whole. The main time you'd need to deal with overloads of new and delete for an individual class would be if they're already overloaded so they're managing a separate pool, and you care about how much of that pool is in use at a given time. In that case, you'd (just about) need to add instrumentation directly to them, to get something like a high-water mark on their memory usage during a given interval.
2,216,654
2,216,705
Pattern matching style in C++?
I love Haskell style pattern matching. I have my C++ code as follows: ObjectPtr ptr; if(ptr.isType<Foo>()) { // isType returns a bool Ptr<Foo> p = ptr.convertAs<Foo>(); // convertAs returns a Ptr<Foo> ...... } if(ptr.isType<Bar>()) { Ptr<Bar> p = ptr.convertAs<Bar>(); ...... } Now, are there any macros I can do define to simplify this? I have been pondering this for a while, but can't simplify it further. Thanks!
I'm assuming that your Ptr template has the concept of a NULL pointer. ObjectPtr ptr; if(Ptr<Foo> p = ptr.convertAs<Foo>()) { // convertAs returns a NULL pointer if the conversion can't be done. ...... } if(Ptr<Bar> p = ptr.convertAs<Bar>()) { ...... } Though, as others have noted, switching on type is usually a sign you're doing something wrong in C++. You ought to consider using virtual functions instead.
2,216,741
2,216,755
Need help with understanding STL vector (simple code in body of message)
Here is the code: #include <vector> #include <iostream> class A { public: A() { std::cout << __FUNCTION__ << "\n"; } ~A() { std::cout << __FUNCTION__ << "\n"; } A& operator=(const A&) { std::cout << __FUNCTION__ << "\n"; return *this;} }; int main(int argc, char* argv[]) { std::vector<A> as; A a; as.push_back(a); as.push_back(a); return 0; } And here is the output I got: A::A A::~A A::~A A::~A A::~A I understand that the output of the first line is from the call to the c-tor from when 'a' is created. One of the calls to the d-tor's also belongs to a. What about the other three calls to A::~A(), where are they coming from? And why are there more calls to the d-tor than calls to the c-tor? How does the container clone 'a' when it adds copies to its elements? And finally, is the output implementation-defined or are there are other possible outputs?
To understand what happens, you are missing one method in A : A(const A&) { std::cout << __FUNCTION__ << "(const A&)\n"; } Then you see the output: A() A(const A&) A(const A&) A(const A&) ~A ~A ~A ~A What happen is that, for each push_back the vector allocate a new contiguous array, copy the old content, and destroy it. If you count, the first copy constructor is for the first push_back, the second and third for the next push_back. The first destructor is for the second push_back, the two next for the destruction of the vector, the last one for the destruction of the variable a. And by the way, this is completely implementation defined, as it is allowed to allocate by chunk, which would prevent quite a few copy/destruction. You can even so the chunks yourself by using vector::reserve(size_type n).
2,216,889
2,216,906
If a functions return an int, can an int be assigned to it?
If a function returns an int, can it be assigned by an int value? I don't see it makes too much sense to assign a value to a function. int f() {} f() = 1; I noticed that, if the function returns a reference to an int, it is ok. Is it restricted only to int? how about other types? or any other rules? int& f() {} f() = 1;
The first function returns an integer by-value, which is an r-value. You can't assign to an r-value in general. The second f() returns a reference to an integer, which is a l-value - so you can assign to it. int a = 4, b = 5; int& f() {return a;} ... f() = 6; // a is 6 now Note: you don't assign a value to the function, you just assign to its return value. Be careful with the following: int& f() { int a = 4; return a; } You're returning a reference to a temporary, which is no longer valid after the function returns. Accessing the reference invokes undefined behaviour.
2,217,035
2,217,197
Simple cross-platform free audio library for raw PCM?
I'm writing a cross-platform Qt-based program that from time to time needs to play back audio supplied externally (outside my control) as raw PCM. The exact format is 16 bit little-endian PCM at various common sample rates. My first obvious idea was to use Qt's own Phonon for audio playback, but there are two problems with this approach: As far as I can see, Phonon does not support headerless PCM data. I would have to hack around this and fake a WAV header every time playback starts. Not a showstopper, though. More importantly: There doesn't seem to be any way to control how Phonon (and its backends such as xine, PulseAudio, DirectX, whatever) prebuffers. Its default behaviour seems to be something like 5 seconds of prebuffering, which is way too much for me. I'd prefer about 1 second, and I'd definitely like to be able to control this! I'm currently looking at Gstreamer, FFMPEG and libvlc. Any thoughts? Since my audio is in a very simple format and I don't need to do fancy mixing stuff (just volume control), I'd like a simple, free (as in freedom), cross-platform and widely available library.
Qt 4.6 has the new QtMultimedia module. https://doc.qt.io/archives/4.6/qtmultimedia.html The QAudioOutput class would seem to do what you want - it just plays raw PCM data.
2,217,148
2,217,169
Printf - access violation reading location - C++
0xC0000005: Access violation reading location 0xcccccccc. printf is throwing this exception. I don't know why this is happening... There are values in those string variables. Am I using printf wrong? Help! (Please see the switch case) string header; string body; string key; if (!contactList.isEmpty()) { cout << "Enter contact's name: "; getline(cin, key); Contact * tempContact = contactList.get(key); if (tempContact != NULL) { string name = tempContact->getName(); string number = tempContact->getNumber(); string email = tempContact->getEmail(); string address = tempContact->getAddress(); //I've just put this here just to test if the variables are being initialized cout << name + " " + number + " " + email + " " + address << endl; switch (type) { case 1: printf("%-15s %-10s %-15s %-15s\n", "Name", "Number", "Email", "Address"); printf("%-15s %-10s %-15s %-15s\n", name, number, email, address); break; case 2: printf("%-15s %-10s\n", "Name", "Number"); printf("%-15s %-10s\n", name, number); break; case 3: printf("%-15s %-15s\n", "Name", "Email"); printf("%-15s %-15s\n", name, email); break; case 4: printf("%-15s %-15s\n", "Name", "Address"); printf("%-15s %-15s\n", name, address); break; default: printf("%-15s %-10s %-15s %-15s\n", "Name", "Number", "Email", "Address"); printf("%-15s %-10s %-15s %-15s\n", name, number, email, address); } } else { cout << "\"" + key + "\" not found.\n" << endl; wait(); } } else { cout << "Contact list is empty.\n" << endl; wait(); } The first printf is printing fine but the second one will throw the exception, seemingly regardless of how I pass the string value in.
printf's "%s" expects a char* as an argument, not a std::string. So printf will interpret your string objects as pointers and try to access the memory location given by the object's first sizeof(char*) bytes, which leads to an access violation because those bytes aren't really a pointer. Either use the strings' c_str method to get char*s or don't use printf.
2,217,204
2,217,264
180 to -180 motion in opengl c++?
i'm using a glutTimerFunc(...) to achieve motion of robot arm, my problem is left side 0 degree to 90 is easily done, when i try 0 to -90 degree, the arm is not stoping? i tried various methods, but all falied, can you suggest better options? here's my timer function, void myTimerFunc(int var) { switch(var) { case 1: if(shoulder>=90) stop=1; if(!stop) { shoulder = (shoulder + 5); glutPostRedisplay(); glutTimerFunc(100,myTimerFunc,1); break; } if(shoulder<=0) stop1=1; if(!stop1) { shoulder = (shoulder - 5); glutPostRedisplay(); glutTimerFunc(100,myTimerFunc,1); break; } case 2: if(shoulder>=360) stop2=1; if(!stop2) { shoulder = (shoulder - 5); glutPostRedisplay(); glutTimerFunc(100,myTimerFunc,2); break; } // here robot arm is not stopping........... if(shoulder<=270) stop2 = 0; stop3 = 1; if(!stop3) { shoulder = (shoulder + 5); glutPostRedisplay(); glutTimerFunc(100,myTimerFunc,2); break; } default:break; } } i'm calling this from keyboard function....... void keyboard (unsigned char key, int x, int y) { switch (key) { case 's': glutTimerFunc(100,myTimerFunc,1); break; glutTimerFunc(100,myTimerFunc,2); break;
Looks to me like you're confused about how to treat angles. Are you using a [0, 360] scale for a full circle or [-180, +180]? I see a check against 270 in your code, but your prose mentions -90. Yes, they're "the same", but if it's not working perhaps some confusion has crept into your code. If you're going with [-180, +180], with zero degrees as the neutral position for your robot arm, perhaps you can take advantage of symmetry and use the absolute value function. You only have to code it once that way. If it's successful for [0, +90] it'll also work for [-90, 0] as well. It also seems to me that you're not taking advantage of object-oriented thinking. This method has motion and timing and graphical refresh all in the same method. Writing smaller methods and unit testing each one to be sure that it works is a better approach. It's called "decomposition". The moment you say "it's a big method", it suggests to me that perhaps it's too big and needs to be refactored.
2,217,206
2,217,237
Smallest sum of pairs
Given 2N-points in a 2D-plane, you have to group them into N pairs such that the overall sum of distances between the points of all of the pairs is the minimum possible value.The desired output is only the sum. In other words, if a1,a2,..an are the distances between points of first, second...and nth pair respectively, then (a1+a2+...an) should be minimum. Let us consider this test-case, if the 2*5 points are : {20,20}, {40, 20}, {10, 10}, {2, 2}, {240, 6}, {12, 12}, {100, 120}, {6, 48}, {12, 18}, {0, 0} The desired output is 237. This is not my homework,I am inquisitive about different approaches rather than brute-force.
You seem to be looking for Minimum weight perfect matching. There are algorithms to exploit the fact that these are points in a plane. This paper: Mincost Perfect Matching in the Plane has an algorithm and also mentions some previous work on it. As requested, here is a brief description of a "simple" algorithm for minimum weighted perfect matching in a graph. This is a short summary of parts of the chapter on weighted matching in the book Combinatorial Optimization, Algorithms and Complexity by Papadimitriou & Steiglitz. Say you are given a weighted undirected graph G(with an even number of nodes). The graph can be considered a complete weighted graph, by adding the missing edges and assigning them very large weights. Suppose the vertices are labelled 1 to n and the weight of edge between vertices i and j is c(i,j). We have n(n-1)/2 variables x(i,j) which denote a matching of G. x(i,j) = 1 if the edge between i and j is in the matching and x(i,j) = 0 if it isn't. Now the matching problem can be written as the Linear Programming Problem: minimize Sum c(i,j) * x(i,j) subject to the condition that Sum x(1,j) = 1, where j ranges from 1 to n. Sum x(2,j) = 1, where j ranges from 1 to n. . . . Sum x(n,j) = 1, where j ranges from 1 to n. (Sum x(1,j) = 1 basically means that we are selecting exactly one edge incident the vertex labelled 1.) And the final condition that x(i,j) >= 0 (we could have said x(i,j) = 0 or 1, but that would not make this a Linear Programming Problem as the constraints are either linear equations or inequalities) There is a method called the Simplex method which can solve this Linear Programming problem to give an optimal solution in polynomial time in the number of variables. Now, if G were bipartite, it can be shown that we can obtain an optimal solution such that x(i,j) = 0 or 1. Thus by solving this linear programming problem for a bipartite graph, we get a set of assignments to each x(i,j), each being 0 or 1. We can now get a matching by picking those edges (i,j) for which x(i,j) = 1. The constraints guarantee that it will be a matching with smallest weight. Unfortunately, this is not true for general graphs (i.e x(i,j) being 0 or 1). Edmonds figured out that this was because of the presence of odd cycles in the graph. So in addition to the above contraints, Edmonds added the additional constraint that in any subset of vertices of size 2k+1 (i.e of odd size), the number of matched edges is no more than k Enumerate each odd subset of vertices to get a list of sets S(1), S(2), ..., S(2^n - n). Let size of S(r) be 2*s(r) + 1. Then the above constraints are, for each set S(r) Sum x(i,j) + y(r) = s(r), for i, j in S(r). Edmonds then proved that this was enough to guarantee that each x(i,j) is 0 or 1, thus giving us a minimum weight perfect matching. Unfortunately, now the number of variables has become exponential in size. So the simplex algorithm, if just run on this as it is, will lead to an exponential time algorithm. To get past this, Edmonds considers the dual of this linear programming problem (I won't go into details here), and shows that primal-dual algorithm when run on the dual takes only O(n^4) steps to reach a solution, thus giving us a polynomial time algorithm! He shows this by showing that at most O(n) of the y(r) are non-zero at any step of the algorithm (which he calls blossoms). Here is a link which should explain it in a little more detail: http://www.cs.ucl.ac.uk/staff/V.Kolmogorov/papers/blossom5.pdf , Section 2. The book I mentioned before is worth reading (though it can be a bit dry) to get a deeper understanding. Phew. Hope that helps!
2,217,436
2,220,142
Emacs Semantic/ECB namespace-struct C++ confusion
I'm trying to setup ECB to work with C++ sources. seemingly, semantic or ECB has problem determining whenever a function declarant with explicit namespace, namespace:: function , is really in the namespace. instead it parses it as struct member function. Moreover, typedef is parsed as function prototypes. What should I do to fix it? I am using cedet 1 .06pre and ECB 2.40.
It's better to take CEDET from CVS. as i remember were some fixes for such cases
2,217,459
2,217,477
Extension wrapper malloc allocator for C++ STL
Apparently there is a “malloc_allocator” provided with gcc for use with STL. It simply wraps malloc and free. There is also a hook for an out-of-memory handler. Where can I find more about it? Where can I find its header file? I’m using gcc 4.x.
Is this something you want? You will need to include and pass in an object as the STL object's allocator template parameter.
2,217,568
2,217,611
question on stl fill function in C++
Let's say I have an array like this: string x[2][55]; If I want to fill it with "-1", is this the correct way: fill(&x[0][0],&x[2][55],"-1"); That crashed when I tried to run it. If I change x[2][55] to x[1][54] it works but it doesn't init the last element of the array. Here's an example to prove my point: string x[2][55]; x[1][54] = "x"; fill(&x[0][0],&x[1][54],"-1"); cout<<x[1][54]<<endl; // this print's "x"
Because when you have a multi-dimensional array, the address beyond the first element is a little confusing to calculate. The simple answer is you do this: &x[1][55] Let's consider what a 2d array x[N][M] is laid out in memory [0][0] [0][1] ... [0][M-1] [1][0] [1][1] ... [1][M-1] [N-1][0] .. [N-1][M-1] So, the very last element is [N-1][M-1] and the first element beyond is [N-1][M]. If you take the address of [N][M] then you go very far past the end and you overwrite lots of memory. Another way to calculate the first address beyond the end is to use sizeof. &x[0][0] + sizeof(x) / sizeof(std::string);
2,217,628
2,218,034
Multiple definition of inline functions when linking static libs
I have a C++ program that I compile with mingw (gcc for Windows). Using the TDM release of mingw which includes gcc 4.4.1. The executable links to two static library (.a) files: On of them is a third-party library written in C; the other is a C++ library, written by me, that uses the C library provides my own C++ API on top. An (in my view, excessive) portion of the C library's functionality is implemented in inline functions. You can't avoid including the inline functions when you use the C library's API, but when I try to link it all together, I'm getting link errors saying there is a multiple definition of all of the inline functions - both ones I have called in my C++ wrapper library and ones which I have not, basically anything defined inline in the headers has gotten a function created for it in both the C library and the C++ library. It doesn't cause multiple definition errors when the include files are used multiple times in different .c or .cpp files in the same project; the problem is just that it generates one definition per library. How/why is the compiler generating functions and symbols for these inline functions in both libraries? How can I force it to stop generating them in my code? Is there a tool I can run to strip the duplicate functions from the .a file, or a way to make the linker ignore multiple definitions? (FYI, the third party library does include #ifdef __cplusplus and extern "C" guards in all its headers; anyway if that were the problem, it would not cause a multiple definition of symbol, it would cause the opposite problem because the symbol would be undefined or at least different.) Notably, the link errors do NOT occur if I link to the third party C library's DLL; however then I get strange runtime failures that seem to have to do with my code having its own version of functions it should be calling from the DLL. (As if the compiler is creating local versions of functions I didn't ask for.) Similar versions of this question have been asked before, however, I didn't find the answer to my situation in any of these: The answer to this question was that the poster was multiply defining variables, my problem is multiple definition of inline functions: Repeated Multiple Definition Errors from including same header in multiple cpps This was an MSVC program, but I'm using mingw; also, the poster's problem in this question was the definition of a C++ class constructor outside of the class body in a header, while my problem is with C functions that are inline: Static Lib Multiple Definition Problem This fool renamed all his C code as C++ files and his C code wasn't C++-safe: Multiple definition of lots of std:: functions when linking This one was just wanting to know why violating the one definition rule was not an error: unpredictable behavior of Inline functions with different definitions
First you have to understand the C99 inline model - perhaps there is something wrong with your headers. There are two kind of definitions for inline functions with external (non-static) linkage External definition This definition of a function can only appear once in the whole program, in a designated TU. It provides an exported function that can be used from other TUs. Inline definition These appear in every TU where declared as a separate definition. The definitions do not need to be identical to one another or to the external definition. If used internal in a library, they can do omit checking on function arguments that would otherwise be done in the external definition. Each definition of the function has its own local static variables, because their local declarations have no linkage (they are not shared like in C++). A definition of a non-static inline function will be an inline definition if Every function declaration in a TU includes the specifier inline, and No function declaration in a TU includes the specifier extern. Otherwise, the definition that must appear in that TU (because inline functions must be defined in the same TU where declared) is an external definition. In a call to an inline function it's unspecified whether the external or the inline definition is used. However, because the function defined in all cases is still the same (because it has external linkage), the address of it compares equal in all cases, no matter how many inline definitions appear. So if you take the function's address, it's likely the compiler resolves to the external definition (especially if optimizations are disabled). An example that demonstrates a wrong use of inline, because it includes an external definition of a function twice in two TUs, causing a multiple definition error // included into two TUs void f(void); // no inline specifier inline void f(void) { } The following program is dangerous, because the compiler is free to use the external definition, but the program does not provide one // main.c, only TU of the program inline void g(void) { printf("inline definition\n"); } int main(void) { g(); // could use external definition! } I have made some test cases using GCC that demonstrate the mechanism further: main.c #include <stdio.h> inline void f(void); // inline definition of 'f' inline void f(void) { printf("inline def main.c\n"); } // defined in TU of second inline definition void g(void); // defined in TU of external definition void h(void); int main(void) { // unspecified whether external definition is used! f(); g(); h(); // will probably use external definition. But since we won't compare // the address taken, the compiler can still use the inline definition. // To prevent it, i tried and succeeded using "volatile". void (*volatile fp)() = &f; fp(); return 0; } main1.c #include <stdio.h> inline void f(void); // inline definition of 'f' inline void f(void) { printf("inline def main1.c\n"); } void g(void) { f(); } main2.c #include <stdio.h> // external definition! extern inline void f(void); inline void f(void) { printf("external def\n"); } void h(void) { f(); // calls external def } Now, the program outputs what we expected! $ gcc -std=c99 -O2 main.c main1.c main2.c inline def main.c inline def main1.c external def external def Looking at the symbol table, we will see that the symbol of an inline definition is not exported (from main1.o), while an external definition is exported (from main2.o). Now, if your static libraries each have an external definition of their inline functions (as they should), they will naturally conflict with each other. The solution is to make the inline functions static or just to rename them. These will always provide external definitions (so they are full fledged definitions), but they are not exported because they have internal linkage, thus not conflicting static inline void f(void) { printf("i'm unique in every TU\n"); }
2,217,776
2,217,868
Calling a C++ object's method from an Objective-C child object
I have some Objective-C++ code that I'm trying to get events out of an Objective-C object to call a method within a C++ object. I'm very new to Objective-C, so I may be doing this all wrong. Example: @interface KnobClass { } -(void)Event; @end class DoorClass { public: KnobClass * knob; void start() { knob = [[KnobClass allocate] init]; } }; class AlarmClass { public: void Alert(); }; class HouseClass { public: DoorClass door; AlarmClass alarm; }; int main() { //... HouseClass house; house.door.start(); //... return 0; } The method [house.door.knob Event] is generated on an event, and I want it to be able to call house.alarm.Alert(). But I'm confused how to accomplish this in a correct manner. Can someone suggest a way of accomplishing this?
I'm learning Objective-C too. This works in gcc 4.3.3: #import <Foundation/Foundation.h> class AlarmClass { public: void Alert() { printf("Alert!\n"); } }; @interface KnobClass: NSObject { AlarmClass *alarm; } -(void)Event; -(id)initWithAlarm:(AlarmClass*) alarm; @end @implementation KnobClass: NSObject -(id)initWithAlarm:(AlarmClass*) a { self = [super init]; alarm = a; return self; } -(void)Event { alarm->Alert(); } @end class DoorClass { public: KnobClass * knob; void start(AlarmClass *a) { knob = [[KnobClass alloc] initWithAlarm: a]; } void doEvent() { [knob Event]; } }; class HouseClass { public: DoorClass door; AlarmClass alarm; }; int main(int argc, const char *argv[]) { //... HouseClass house; house.door.start(&house.alarm); house.door.doEvent(); //... return 0; }
2,217,825
2,217,902
How can I resolve linker issues when I compile this C++ program that requires GLUT?
I'm trying to compile this C++ program which utilizes the GLUT32 libraries. Right now I'm getting the following errors: Error 1 error LNK2001: unresolved external symbol _gluPerspective@32 Camera.obj soundCube Error 2 error LNK2001: unresolved external symbol _gluLookAt@72 Camera.obj soundCube Error 3 error LNK2001: unresolved external symbol __imp__glMaterialfv@12 GLWindow.obj soundCube Error 4 error LNK2001: unresolved external symbol __imp__glClear@4 GLWindow.obj soundCube Error 5 error LNK2001: unresolved external symbol __imp__glClearColor@16 GLWindow.obj soundCube Error 6 error LNK2001: unresolved external symbol __imp__glMaterialf@12 GLWindow.obj soundCube Error 7 error LNK2001: unresolved external symbol __imp__glEnd@0 GLWindow.obj soundCube Error 8 error LNK2001: unresolved external symbol __imp__glRasterPos2f@8 GLWindow.obj soundCube Error 9 error LNK2001: unresolved external symbol __imp__timeGetTime@0 GLWindow.obj soundCube Error 10 error LNK2001: unresolved external symbol __imp__glDisable@4 GLWindow.obj soundCube Error 11 error LNK2001: unresolved external symbol __imp__glBegin@4 GLWindow.obj soundCube Error 12 error LNK2001: unresolved external symbol __imp__glColor4f@16 GLWindow.obj soundCube Error 13 error LNK2001: unresolved external symbol __imp__glPopMatrix@0 GLWindow.obj soundCube Error 14 error LNK2001: unresolved external symbol __imp__glPushMatrix@0 GLWindow.obj soundCube Error 15 error LNK2001: unresolved external symbol __imp__glRotatef@16 GLWindow.obj soundCube Error 16 error LNK2001: unresolved external symbol __imp__glBlendFunc@8 ... Error 56 fatal error LNK1120: 55 unresolved externals C:\Users\Simucal\Documents\Downloads\SoundCubeSrc soundCube I'm not that experienced in C++ but I've tried to set up GLUT correctly so this project can link against it. I downloaded the GLUT32 library for Nate Robin's page. I then placed the following files in: glut.h - C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\gl glut32.lib - C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib glut.dll - C:\Windows\System32 I also selected the Project -> Properties -> Linker -> Additional Dependencies -> Added "glut32.lib" If anyone wants to see what project I'm working with, it is here. What step am I missing or doing wrong in order to resolve these errors?
The unresolved symbols are from the GL and GLU libraries. You need to add the link libraries for them as well.
2,217,878
2,217,889
C++ std::set update is tedious: I can't change an element in place
I find the update operation on std::set tedious since there's no such an API on cppreference. So what I currently do is something like this: //find element in set by iterator Element copy = *iterator; ... // update member value on copy, varies Set.erase(iterator); Set.insert(copy); Basically the iterator return by Set is a const_iterator and you can't change its value directly. Is there a better way to do this? Or maybe I should override std::set by creating my own (which I don't know exactly how it works..)
set returns const_iterators (the standard says set<T>::iterator is const, and that set<T>::const_iterator and set<T>::iterator may in fact be the same type - see 23.2.4/6 in n3000.pdf) because it is an ordered container. If it returned a regular iterator, you'd be allowed to change the items value out from under the container, potentially altering the ordering. Your solution is the idiomatic way to alter items in a set.
2,217,918
2,217,927
Dynamic memory use in class member
I'm getting some odd behavior in one of my class members and it is truly throwing me for a loop but I'm certainly not seeing the issue (long week!) void MyFakeStringClass::readStream( iostream& nInputStream ) { // Hold the string size UINT32 size = 0; // Read the size from the stream nInputStream.read( reinterpret_cast< char* >( &size ), sizeof( UINT32 ) ); // Create a new buffer char* buffer = new char[ size ]; // Read the stream nInputStream.read( buffer, size ); // Save to class member value = string( buffer ); // Clean up delete[] buffer; buffer = NULL; } This issue arises when I use two or more MyFakeStringClass's. buffer is somehow still containing data from previous calls to MyFakeStringClass::readStream. Say for example I read in two strings 'HelloWorld', 'Test' the resulting MyFakeStringClass objects contain 'HelloWorld', and 'TestoWorld' ( should be 'HelloWorld', 'Test' ). The second time the function is accessed buffer is still containing 'old' memory. How is this possible as it is locally scoped and deleted? I've confirmed that buffer is being somehow shared with a debugger.
You need to create the string using: value = string( buffer, size ); If you do not specify the size, it will assume buffer is a null-terminated string. Since there is no null terminator, it reads past the end of the data, and gives you previous contents of the memory.
2,218,033
2,219,480
Cygwin gcc compiled fails in IDE complaining about 'exit' undeclared
When I compile a program using just gcc code.c There are no messages, and an output file is generated successfully. The outputted file works. However, when I try to the same cygwin installation's gcc compiler in an IDE (I've tried Netbeans and Dev-C++), I get the following errors main.cpp:27: error: `exit' undeclared (first use this function) main.cpp:27: error: (Each undeclared identifier is reported only once for each function it appears in.) main.cpp:77: error: `write' undeclared (first use this function) main.cpp:78: error: `close' undeclared (first use this function) I don't see what's different. Why does it not compile? OK, the issue was that in the IDE, the file had a .cpp extension, whereas when I was compiling from a terminal, it had a .c extension. So, my new question is why does it not compile when it's treated as a c++ file. Isn't C a subset of C++?
C++ is stricter then C. Where C allows you to call a function without a prototype, C++ does not allow this. To solve the problem, you want to add: #include <stdlib.h> Also, when compiling at the command line. Make sure to use the -Wall flag so you'll get important warnings: gcc -Wall code.c
2,218,100
2,233,748
Error avalanche in Boost.Spirit.Qi usage
I'm not being able to figure out what's wrong with my code. Boost's templates are making me go crazy! I can't make heads or tails out of all this, so I just had to ask. What's wrong with this? #include <iostream> #include <boost/lambda/lambda.hpp> #include <boost/spirit/include/qi.hpp> void parsePathTest(const std::string &path) { namespace lambda = boost::lambda; using namespace boost::spirit; const std::string permitted = "._\\-#@a-zA-Z0-9"; const std::string physicalPermitted = permitted + "/\\\\"; const std::string archivedPermitted = permitted + ":{}"; std::string physical,archived; // avoids non-const reference to rvalue std::string::const_iterator begin = path.begin(),end = path.end(); // splits a string like "some/nice-path/while_checking:permitted#symbols.bin" // as physical = "some/nice-path/while_checking" // and archived = "permitted#symbols.bin" (if this portion exists) // I could barely find out the type for this expression auto expr = ( +char_(physicalPermitted) ) [lambda::var(physical) = lambda::_1] >> -( ':' >> ( +char_(archivedPermitted) [lambda::var(archived) = lambda::_1] ) ) ; // the error occurs in a template instantiated from here qi::parse(begin,end,expr); std::cout << physical << '\n' << archived << '\n'; } The number of errors is immense; I would suggest people who want to help compiling this on their on (trust me, pasting here is unpractical). I am using the latest TDM-GCC version (GCC 4.4.1) and Boost version 1.39.00. As a bonus, I would like to ask another two things: whether C++0x's new static_assert functionality will help Boost in this sense, and whether the implementation I've quoted above is a good idea, or if I should use Boost's String Algorithms library. Would the latter likely give a much better performance? Thanks. -- edit The following very minimal sample fails at first with the exact same error as the code above. #include <iostream> #include <boost/spirit/include/qi.hpp> int main() { using namespace boost::spirit; std::string str = "sample"; std::string::const_iterator begin(str.begin()), end(str.end()); auto expr = ( +char_("a-zA-Z") ) ; // the error occurs in a template instantiated from here if (qi::parse(begin,end,expr)) { std::cout << "[+] Parsed!\n"; } else { std::cout << "[-] Parsing failed.\n"; } return 0; } -- edit 2 I still don't know why it didn't work in my old version of Boost (1.39), but upgrading to Boost 1.42 solved the problem. The following code compiles and runs perfectly with Boost 1.42: #include <iostream> #include <boost/spirit/include/qi.hpp> int main() { using namespace boost::spirit; std::string str = "sample"; std::string::const_iterator begin(str.begin()), end(str.end()); auto expr = ( +qi::char_("a-zA-Z") ) // notice this line; char_ is not part of // boost::spirit anymore (or maybe I didn't // include the right headers, but, regardless, // khaiser said I should use qi::char_, so here // it goes) ; // the error occurs in a template instantiated from here if (qi::parse(begin,end,expr)) { std::cout << "[+] Parsed!\n"; } else { std::cout << "[-] Parsing failed.\n"; } return 0; } Thanks for the tips, hkaiser.
Several remarks: a) don't use the Spirit V2 beta version distributed with Boost V1.39 and V1.40. Use at least Spirit V2.1 (as released with Boost V1.41) instead, as it contains a lot of bug fixes and performance enhancements (both, compile time and runtime performance). If you can't switch Boost versions, read here for how to proceed. b) Try to avoid using boost::lambda or boost::bind with Spirit V2.x. Yes, I know, the docs say it works, but you have to know what you're doing. Use boost::phoenix expressions instead. Spirit 'knows' about Phoenix, which makes writing semantic actions easier. If you use Phoenix, your code will look like: #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix.hpp> namespace qi = boost::spirit::qi; namespace phoenix = boost::phoenix; std::string physical, archived; auto expr = ( +char_(physicalPermitted) ) [phoenix::ref(physical) = qi::_1] >> -( ':' >> ( +char_(archivedPermitted) )[phoenix::ref(archived) = qi::_1] ) ; But your overall parser will get even simpler if you utilize Spirit's built-in attribute propagation rules: std::string physical; boost::optional<std::string> archived; qi::parse(begin, end, +qi::char_(physicalPermitted) >> -(':' >> +qi::char_(archivedPermitted)), physical, archived); i.e. no need to have semantic actions at all. If you need more information about the attribute handling, see the article series about the Magic of Attributes on Spirit's web site. Edit: Regarding your static_assert question: yes static_assert, can improve error messages as it can be used to trigger compiler errors as early as possible. In fact, Spirit uses this technique extensively already. But it is not possible to protect the user from getting those huge error messages in all cases, but only for those user errors the programmer did expect. Only concepts (which unfortunately didn't make it into the new C++ Standard) could have been used to generally reduce teh size of the error messages. Regarding your Boost's String Algorithms question: certainly it's possible to utilize this library for simple tasks as yours. You might even be better off using Boost.Tokenizer (if all you need is to split the input string at the ':'). The performance of Spirit should be comparable to the corresponding performance of the string algorithms, but this certainly depends on the code you will write. If you assume that the utilized string algorithm will require one pass over the input string data, then Spirit won't be faster (as it's doing one pass as well). Neither the Boost String algorithms nor the Boost Tokenizer can give you the verification of the characters matched. Your Spirit grammar matches only the characters you specified in the character classes. So if you need this matching/verification, you should use either Spirit or Boost Regex.
2,218,140
2,218,157
What requires me to declare "using namespace std;"?
This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare using namespace std; in C++ programs?
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive. However, using namespace std; is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like using std::string;
2,218,159
2,218,179
How to set c console window title
How to set the console window title in C? printf("%c]0;%s%c", '\033', "My Console Title", '\007'); This works only under linux, not in windows. Does anybody know a "cross-platform" solution? (of course not system ( title=blah ))
windows.h defines SetConsoleTitle(). You could use that everywhere, and declare your own function for linux platforms that does the same thing.
2,218,254
2,218,275
Variable initialization in C++
My understanding is that an int variable will be initialized to 0 automatically; however, it is not. The code below prints a random value. int main () { int a[10]; int i; cout << i << endl; for(int i = 0; i < 10; i++) cout << a[i] << " "; return 0; } What rules, if any, apply to initialization? Specifically, under what conditions are variables initialized automatically?
It will be automatically initialized if it's a class/struct instance in which the default constructor initializes all primitive types; like MyClass instance; you use array initializer syntax, e.g. int a[10] = {} (all zeroed) or int a[10] = {1,2}; (all zeroed except the first two items: a[0] == 1 and a[1] == 2) same applies to non-aggregate classes/structs, e.g. MyClass instance = {}; (more information on this can be found here) it's a global/extern variable the variable is defined static (no matter if inside a function or in global/namespace scope) - thanks Jerry Never trust on a variable of a plain type (int, long, ...) being automatically initialized! It might happen in languages like C#, but not in C & C++.
2,218,303
2,218,317
c++ operator[] overloading problem (works fine but not for pointers, why?)
Problem with operator[] in c++, i have some class: 197 class Permutation{ 198 private: 199 unsigned int* array; 200 unsigned int size; 201 202 void fill(){ 203 for(unsigned int i=0;i<size;i++) 204 array[i]=i; 205 } 206 void init(const unsigned int s){ 207 if(s){ 208 array=new unsigned int[s]; 209 size=s; 210 }else{ 211 size=0; 212 array=0; 213 } 214 } 215 void clear(){ 216 if(array){ 217 delete[]array; 218 array=0; 219 } 220 size=0; 221 } 222 public: 223 Permutation(const unsigned int& s=0):array(0),size(0){ 224 init(s); 225 fill(); 226 } 227 ~Permutation(){ 228 clear(); 229 } 230 unsigned int& operator[](const unsigned int& idx){ 231 assert(idx<size); 232 return array[idx]; 233 } 234 unsigned int& get(const unsigned int& idx) 235 { 236 assert(idx<size); 237 return array[idx]; 238 } 253 Permutation& operator=(const Permutation& p){ 254 clear(); 255 init(p.size); 256 size=p.size; 257 for(unsigned int i=0;i<size;i++) 258 array[i]=p.array[i]; 259 return *this; 260 } 261 262 Permutation(const Permutation&p) 263 { 264 clear(); 265 init(p.size); 266 size=p.size; 267 for(unsigned int i=0;i<size;i++) 268 array[i]=p.array[i]; 269 } }; when I use Permutation x(3); x[0]=1; it works very well, but when I use: Permutation* x=new Permutation(3); x->get(0)=10; // this works fine x[0]=1; in this case, in debugger I see it is called a constructor of new object for Permutation class, what is going on ? and why? I someone know what is going about I would appreciate for information.
First, your code: Permutation* x=new Permutation(3); x->get(0)=10; // this works fine And then you do this: x[0]=1; And what you are doing is treating the pointer x as an array, and initializing it, which is longhand for: x[0] = Permuation(1); // implicit conversion using Permulation(const unsigned long&) What you meant to write was: (*x)[0]=1; // follow x and then invoke the [] operator Or, equivalent: x->operator[](0) = 1;
2,218,339
2,284,642
Cg shaders not being applied after switch to glVertexPointer
My renderer used to render geometry with the old fixed function stuff using glBegin/glEnd. After switching it to use vertex arrays via glVertexPointer et. al., my Cg shaders stopped showing up. If i just do a regular texture binding, it works fine, so the array data is solid. Also if I use the old glBegin/glEnd system, the Cg shaders work fine. Is there some consideration I am missing specific to vertex buffers?
vertex data submission (Begin/End, regular VertexPointer+DrawArrays, VBO+DrawArrays) is supposed to be completely orthogonal to shaders (as long as you provide the data). So you're not really missing anything (especially if it works with VBO). Your problem is likely somewhere that you don't mention.
2,218,435
2,218,475
Why typedef can not be used with static?
Why typedef can not be used with static? For example, the code below is an error typedef static int INT2; What other rules should be follow to use the typedef? What other keywords can not be used with typedef? Thanks so much!
typedef doesn't declare an instance of a variable, it declares a type (type alias actually), static is a qualifier you apply to an instance, not a type, so you can use static when you use the type, but not when you define the type. Like this.. typedef int int32; static int32 foo;
2,218,494
2,218,507
Problem with named constructor with istream as argument
I'm trying to create a named constructor for my class Matrix, with an input as a stream from which I can read the values for the initialization. #include <istream> // ... class Matrix { public: Matrix(int); // some methods static Matrix *newFromStream(istream&); private: int n; std::valarray< Cell > data; }; The method should be implemented more or less like this Matrix *Matrix::newFromStream(istream &ist) { // read first line and determine how many numbers there are string s; getline( ist, s ); ... istringstream iss( s, istringstream::in); int n = 0, k = 0; while ( iss >> k) n++; Matrix *m = new Matrix( n ); // read some more values from ist and initialize return m; } However, while compiling, I get an error in the declaration of the method (line 74 is where the prototype is defined, and 107 where the implementation starts) hitori.h:74: error: expected ‘;’ before ‘(’ token hitori.cpp:107: error: no ‘Matrix* Matrix::newFromStream(std::istream&)’ member function declared in class ‘Matrix’ These errors, however, I do not get when defining and implementing a named constructor with a simple parameter, like an int. What am I missing? Any help would be greatly appreciated.
istream is in the namespace std: static Matrix *newFromStream(std::istream&); The error indicates it's lost once it gets to istream. Change it in both header and source, of course. A couple notes: In your header, use <iosfwd> instead of <istream>, and in your source file use <istream>. This is more "correct" and may speed up compilation. Also, do you really want to return newly allocated memory? This is risky and isn't terribly safe. Stack-allocation would be much easier, and maybe even faster. Lastly, just something to keep in mind: You're very close to having a good operator<<. You can implement it in terms of your current function: std::istream& operator<<(std::istream& pStream, Matrix& pResult) { // ... book keeping for istream pResult = Matrix::from_stream(pStream); // ... more book keeping }
2,218,545
2,218,571
Fast Cross Platform Inter Process Communication in C++
I'm looking for a way to get two programs to efficiently transmit a large amount of data to each other, which needs to work on Linux and Windows, in C++. The context here is a P2P network program that acts as a node on the network and runs continuously, and other applications (which could be games hence the need for a fast solution) will use this to communicate with other nodes in the network. If there's a better solution for this I would be interested.
boost::asio is a cross platform library handling asynchronous io over sockets. You can combine this with using for instance Google Protocol Buffers for your actual messages. Boost also provides you with boost::interprocess for interprocess communication on the same machine, but asio lets you do your communication asynchronously and you can easily have the same handlers for both local and remote connections.
2,218,753
2,218,756
declaring generic istream in c++
I need to write a program that reads in either from ifstream or cin, depending on parameters passed into the program at runtime. I was planning on doing the following: istream in; if(argv[1] == "cin") { in = cin; } else { ifStream inFile; inFile.open(argv[1].c_str()); in = inFile; } However, istream in protected, and I can't declare istream in. Is there a way to declare such a generic in stream?
Try with an istream* instead. Note, however, that you have to change your code slightly. Using pointers you have to preserve the memory area of the object that you're pointing. In other words, the "inFile" variable cannot be declared there, as it won't exist out of the else. The code could be, then: istream* in; ifStream inFile; if(!strcmp(argv[1],"cin")) { in = &cin; } else { inFile.open(argv[1]); in = &inFile; } // use *in (Note also the modifications in the string handling. I modified them as an example.)
2,218,798
2,218,813
What is a good method to have a common interface to code without incurring the cost of dynamic lookup?
I am writing some code for handling data. There are a number of groups of processing functions that can be chosen by the user that are then applied to the dataset. I would like to implement all these groups in separate places, but since they all take the same parameters and all do similar things I would like for them to have a common interface. Being a good little c++ programmer my first thought was to simply use polymorphism. Just create some abstract class with the desired interface and then derive each set of processing objects from that. My hopes were quickly dashed however when I thought of another wrinkle. These datasets are enormous, resulting in the functions in question being called literally billions of times. While dynamic lookup is fairly cheap, as I understand it, it is a good deal slower than a standard function call. My current idea to combat this is to use function pointers, in a manner something like this: void dataProcessFunc1(mpz_class &input){...} void dataProcessFunc2(mpz_class &input){...} ... class DataProcessInterface { ... void (*func1)(mpz_class); void (*func2)(mpz_class); ... } With some sort of constructor or something for setting up the pointers to point at the right things. So I guess my question is this: Is this a good method? Is there another way? Or should I just learn to stop worrying and love the dynamic lookup?
A virtual function call is a function call via a pointer. The overhead is generally about the same as an explicit function call via a pointer. In other words, your idea is likely to gain very little (quite possibly nothing at all). My immediate reaction would be to start with virtual functions, and only worry about something else when/if a profiler shows that the overhead of virtual calls is becoming significant. When/if that occurs, another possibility would be to define the interface in a class template, then put the various implementations of that interface into specializations of the template. This normally eliminate all run-time overhead (though it's often a fair amount of extra work).
2,218,889
2,218,927
C++ functor to output iterator adapter
Given a functor appropriate for use with std::for_each and friends: template <typename T> struct Foo { void operator()(T const& t) { ... } }; std::for_each(v.begin(), v.end(), Foo<Bar>()); Is there some standard way to convert this into an output iterator appropriate for use with std::copy and friends? (or the opposite adaptation) Something like: std::copy(v.begin(), v.end(), functor_output_iterator(Foo<Bar>())); Which would call the functor each time a value is assigned to the iterator: adapter(F f) : functor(f) { } adapter& operator*() { return *this; } operator=(T const& t) { functor(t); } operator++() { } ... Or, alternatively: std::for_each(..., some_adapter(std::ostream_iterator(std::cout))); Background: I have a class that exposes a collection using an output iterator: template <typename It> GetItems(It out) { MutexGuard guard(mutex); std::copy(items.begin(), items.end(), out); } This allows callers to get access to the items without forcing them to use a specific container type and without messing around with locking or other internal details. e.g., to get only unique items: std::set<whatever> set; obj->GetItems(std::inserter(set, set.end())); This beats the hell out of: ObjLock lock = obj->GetLock(); for (int i = 0; i < obj->GetItemCount(); ++i) { Item* item = obj->GetItem(i); ... Now I also want to be able to aggregate these items, rather than copying them. (See this question). Where I would normally do something like: std::for_each(v.begin(), v.end(), Joiner<Foo>()); Now I could make two separate methods for the same data elements, one that calls std::copy and one that calls std::for_each but it would be nice to be able to define just one such method, using an iterator or a functor, and have callers be able to pass either functors or iterators to it, adapting them as necessary to the appropriate type. What I'm doing now is defining the aggregator in such a way that it can be used as either an output iterator or a functor, but this leads to unwanted complexity.
How about boost::function_output_iterator?
2,218,931
2,227,180
Extension of Binary search algo to find the first and last index of the key value to be searched in an array
The problem is to extend the binary search algorithm to find all occurrences of a target value in a sorted array in the most efficient way. Concretely speaking, the input of the algorithm is (1) a sorted array of integers, where some numbers may appear more than once, and (2) a target integer to be searched. The output of the algorithm should be a pair of index values, indicating the first and last occurrence of the integer in the array, if it does occur. The source code could be in c#, c, c++. Also, what is the max and min number of comparisons that we might need to find the indexes?
If you are a little clever you can define two different binary search functions. One will return the index of the first appearance of the searched for value and the other will return the last appearance of the searched for value. From your knowledge of binary search, you should be able to determine the maximum and minimum number of comparisons. Using two binary searches should be the fastest method on average in my opinion. For instance, if you use just one binary search to find the first item and search linearly afterwards the worst case would be if the entire function is the same value. For an array of length 10000, this would give 10013 comparisons in the worst case while using two binary searches would give 28 comparisons in the worst case for the same array. Of course, using the same size of array, the best case for the binary/linear search method would be 14 comparisons while the best case for two binary searches method is 26 comparisons. ** Update Okay, here is a binary search to find the first appearance of an element in an array. I'll give you a recursive function (you can of course make it iterative and optimize this in other ways). This searches for the int val in the array a of ints. Also, I haven't been careful about finding the midpoint (if the array is really large there could be problems). int bs1(int a[], int val, int left, int right) { if(right == left) return left; int mid = (right+left)/2; if(val > a[mid]) return bs1(a, val, mid+1, right); else return bs1(a, val, left, mid); } However, you should check after you are returned an index that it actually refers to the correct value because if val is not in the array, the returned index will to correspond to the next element larger than val. A few minor changes to this will make a function that finds the last element. The keys to doing this are using the comparators correctly and remembering that integer division always truncates.
2,219,146
2,219,159
What should the iterator type be in this C++ template?
While working on some graphics code a while back, I wrote Rect and Region classes using ints as the underlying coordinate holder, and that worked fine. The Region was implemented as a simple class extension to an STL list, and just contains a list of Rects. Now I also need the same kinds of classes using doubles as the underlying coordinate holder, and decided to try my hand at templatizing it. So I basically replaced "int" with "typename T" in an intelligent manner and fixed the problems. But there's one remaining problem that has me stumped. I want to calculate a Region's bounding box by doing a union on all the Rects that comprise it. That works fine when not templatized, but g++ chokes on the list iterator when this is templatized. Here's the relevant code: // Rect class that always remains normalized template <typename T> class KRect { public: // Ctors KRect(void) : _l(0), _t(0), _r(0), _b(0) { } void unionRect(const KRect& r) { ... } private: T _l, _t, _r, _b; }; // Region class - this is very brain-dead template <typename T> class KRegion : public std::list< KRect<T> > { public: ... // Accessors KRect<T> boundingBox(void) { KRect<T> r; iterator i; for (i = this->begin(); i != this->end(); i++) { r.unionRect(*i); } return r; } ... }; When that code isn't part of a template, so that T is definite (e.g. an int), the "iterator i" line works fine. But in what you see above, g++ on Ubuntu emits errors which I don't find very informative: include/KGraphicsUtils.h: In member function ‘KRect<T> KRegion<T>::boundingBox()’: include/KGraphicsUtils.h:196: error: expected ‘;’ before ‘i’ include/KGraphicsUtils.h:197: error: ‘i’ was not declared in this scope include/KGraphicsUtils.h: In member function ‘KRect<T> KRegion<T>::boundingBox() [with T = int]’: --- redacted ---:111: instantiated from here include/KGraphicsUtils.h:196: error: dependent-name ‘std::foo::iterator’ is parsed as a non-type, but instantiation yields a type include/KGraphicsUtils.h:196: note: say ‘typename std::foo::iterator’ if a type is meant My guess is this is a type qualification issue with some template-y spin I'm not familiar with. I've tried all kinds of things like: std::list< KRect<T> >::iterator i; this->iterator i; but nothing seems to work. Any suggestions?
iterator is a dependent type (it depends on a template argument) and needs to be prefixed with typename: typename std::list< KRect<T> >::iterator i; Better style would be to provide a class-wide typedef: template <typename T> class KRegion : public std::list< KRect<T> > { typedef std::list< KRect<T> > base; typedef typename base::iterator iterator; // ... };
2,219,179
2,219,201
C++ Serve PHP documents?
I am writing a small web server, nothing fancy, I basically just want to be able to show some files. I would like to use PHP though, and im wondering if just putting the php code inside of the html will be fine, or if I need to actually use some type of PHP library? http://www.adp-gmbh.ch/win/misc/webserver.html I just downloaded that and I am going to use that to work off of. Basically I am writing a serverside game plugin that will allow game server owners to access a web control panel for their server. Some features would be possible with PHP so this is my goal. Any help would be appreciated, thanks!
PHP needs to be processed by the PHP runtime. I'm assuming the case you're talking about is that you have a C++ server answering HTTP queries, and you want to write PHP code out with the HTML when you respond to clients. I'm not aware of any general-purpose PHP library. The most straightforward solution is probably to use PHP as a CGI program. Here's a link that might be useful for that: http://osdir.com/ml/php-general/2009-06/msg00473.html This method is nice because you don't need to write the HTML+PHP out to a file first; you can stream it to PHP.
2,219,239
2,219,246
Difference between these two statements? - C++
I'm a programming student trying to better understand pointers, one of the things I learned is that you can set a pointer to NULL. My question is, what's the difference between these two statements? When would each of them return true/false? if (some_ptr == NULL) if (*some_ptr == NULL) Thanks!
The first does a comparison against the address of the variable to null, the second dereferences the pointer, getting the value held at it and compares it against null.
2,219,243
2,219,253
Odd duplicate symbols error
For a school project, the class was asked to write a String class to mimic the STL string class. I have all the code written, but the linker seems to be caught up on one of my operators. There are three files, String.h, String.cpp, and test2.cpp My Makefile looks like CC=gcc CXX=g++ CXXFLAGS+=-Wall -Wextra LDLIBS+=-lstdc++ all:test2 test2:test2.o String.o test2.o:test2.cpp String.h String.o:String.cpp String.h make outputs the following: g++ -Wall -Wextra -c -o test2.o test2.cpp g++ -Wall -Wextra -c -o String.o String.cpp g++ test2.o String.o -lstdc++ -o test2 ld: duplicate symbol operator==(String const&, char const*)in String.o and test2.o collect2: ld returned 1 exit status make: *** [test2] Error 1 This is odd, since the only place I define operator == is in String.h: #ifndef MY_STRING_H #define MY_STRING_H #include <ostream> #include <istream> class String { //... }; // ... operators ... bool operator ==(const String& left, const char* right) { return left.compare_to(right)==0; } bool operator ==(const char* left, const String& right) { return right.compare_to(left)==0; } bool operator ==(const String& left, const String& right) { return left.compare_to(right)==0; } // ... other comparison operators ... #endif test2.cpp only has a bare main method: #include "String.h" using namespace std; int main() { } So, if I only define operator ==(const String&, const char*) in one place, why does it say I have a duplicate symbol?
You provided the definitions of the operators in the header file which gets included by both String.cpp and test2.cpp. You should move the definitions into one source file and only provide declarations in the header file. // in String.h: bool operator==(const String& left, const char* right); // in String.cpp: bool operator ==(const String& left, const char* right) { return left.compare_to(right)==0; }
2,219,244
2,219,339
Dealing with Floating Point exceptions
I am not sure how to deal with floating point exceptions in either C or C++. From wiki, there are following types of floating point exceptions: IEEE 754 specifies five arithmetic errors that are to be recorded in "sticky bits" (by default; note that trapping and other alternatives are optional and, if provided, non-default). * inexact, set if the rounded (and returned) value is different from the mathematically exact result of the operation. * underflow, set if the rounded value is tiny (as specified in IEEE 754) and inexact (or maybe limited to if it has denormalisation loss, as per the 1984 version of IEEE 754), returning a subnormal value (including the zeroes). * overflow, set if the absolute value of the rounded value is too large to be represented (an infinity or maximal finite value is returned, depending on which rounding is used). * divide-by-zero, set if the result is infinite given finite operands (returning an infinity, either +∞ or −∞). * invalid, set if a real-valued result cannot be returned (like for sqrt(−1), or 0/0), returning a quiet NaN. Is it that when any type of above exceptions happens, the program will exit abnormally? Or the program will carry this error on without mentioning anything and therefore make the error hard to debug? Is a compiler like gcc able to give warning for some obvious case? What can I do during coding my program to notify where the error happens and what types it is when it happens, so that I can locate the error easily in my code? Please give solutions in both C and C++ case. Thanks and regards!
On Linux you can use the GNU extension feenableexcept (hidden right at the bottom of that page) to turn on trapping on floating point exceptions - if you do this then you'll receive the signal SIGFPE when an exception occurs which you can then catch in your debugger. Watch out though as sometimes the signal gets thrown on the floating point instruction after the one that's actually causing the problem, giving misleading line information in the debugger!
2,219,267
2,219,322
Can I make a binary search tree with this?
I've made BSTs before. Can I use this to make a BST without modifications? template <class Item> class binary_tree_node { public: private: Item data_field; binary_tree_node *left_ptr; binary_tree_node *right_ptr; }; I tried making a BST with this but ran into some problems. For one thing, when I create the root node, I can't access the pointers to its child nodes.
Without modifications, no. But that line 'place public member functions here' is screaming out that you should be modifying it. Since you talk about permission problem, it means you are trying to use free functions. But since the pointers are private, you won't have access to them. What you should be doing is creating member functions. For example: class binary_tree_node { public: binary_tree_node() { } bool is_item_in_tree(const Item &item) { } ... }; Anyway, I'd recommend reviewing your C++ basics around visibility and OOP.
2,219,351
2,219,819
Access Violation With Pointers? - C++
I've written a simple string tokenizing program using pointers for a recent school project. However, I'm having trouble with my StringTokenizer::Next() method, which, when called, is supposed to return a pointer to the first letter of the next word in the char array. I get no compile-time errors, but I get a runtime error which states: Unhandled exception at 0x012c240f in Project 5.exe: 0xC0000005: Access violation reading location 0x002b0000. The program currently tokenizes the char array, but then stops and this error pops up. I have a feeling it has to do with the NULL checking I'm doing in my Next() method. So how can I fix this? Also, if you notice anything I could do more efficiently or with better practice, please let me know. Thanks!! StringTokenizer.h: #pragma once class StringTokenizer { public: StringTokenizer(void); StringTokenizer(char* const, char); char* Next(void); ~StringTokenizer(void); private: char* pStart; char* pNextWord; char delim; }; StringTokenizer.cpp: #include "stringtokenizer.h" #include <iostream> using namespace std; StringTokenizer::StringTokenizer(void) { pStart = NULL; pNextWord = NULL; delim = 'n'; } StringTokenizer::StringTokenizer(char* const pArray, char d) { pStart = pArray; delim = d; } char* StringTokenizer::Next(void) { pNextWord = pStart; if (pStart == NULL) { return NULL; } while (*pStart != delim) // access violation error here { pStart++; } if (pStart == NULL) { return NULL; } *pStart = '\0'; // sometimes the access violation error occurs here pStart++; return pNextWord; } StringTokenizer::~StringTokenizer(void) { delete pStart; delete pNextWord; } Main.cpp: // The PrintHeader function prints out my // student info in header form // Parameters - none // Pre-conditions - none // Post-conditions - none // Returns - void void PrintHeader(); int main ( ) { const int CHAR_ARRAY_CAPACITY = 128; const int CHAR_ARRAY_CAPCITY_MINUS_ONE = 127; // create a place to hold the user's input // and a char pointer to use with the next( ) function char words[CHAR_ARRAY_CAPACITY]; char* nextWord; PrintHeader(); cout << "\nString Tokenizer Project"; cout << "\nyour name\n\n"; cout << "Enter in a short string of words:"; cin.getline ( words, CHAR_ARRAY_CAPCITY_MINUS_ONE ); // create a tokenizer object, pass in the char array // and a space character for the delimiter StringTokenizer tk( words, ' ' ); // this loop will display the tokens while ( ( nextWord = tk.Next ( ) ) != NULL ) { cout << nextWord << endl; } system("PAUSE"); return 0; } EDIT: Okay, I've got the program working fine now, as long as the delimiter is a space. But if I pass it a `/' as a delim, it comes up with the access violation error again. Any ideas? Function that works with spaces: char* StringTokenizer::Next(void) { pNextWord = pStart; if (*pStart == '\0') { return NULL; } while (*pStart != delim) { pStart++; } if (*pStart = '\0') { return NULL; } *pStart = '\0'; pStart++; return pNextWord; }
This answer is provided based on the edited question and various comments/observations in other answers... First, what are the possible states for pStart when Next() is called? pStart is NULL (default constructor or otherwise set to NULL) *pStart is '\0' (empty string at end of string) *pStart is delim (empty string at an adjacent delimiter) *pStart is anything else (non-empty-string token) At this point we only need to worry about the first option. Therefore, I would use the original "if" check here: if (pStart == NULL) { return NULL; } Why don't we need to worry about cases 2 or 3 yet? You probably want to treat adjacent delimiters as having an empty-string token between them, including at the start and end of the string. (If not, adjust to taste.) The while loop will handle that for us, provided you also add the '\0' check (needed regardless): while (*pStart != delim && *pStart != '\0') After the while loop is where you need to be careful. What are the possible states now? *pStart is '\0' (token ends at end of string) *pStart is delim (token ends at next delimiter) Note that pStart itself cannot be NULL here. You need to return pNextWord (current token) for both of these conditions so you don't drop the last token (i.e., when *pStart is '\0'). The code handles case 2 correctly but not case 1 (original code dangerously incremented pStart past '\0', the new code returned NULL). In addition, it is important to reset pStart for case 1 correctly, such that the next call to Next() returns NULL. I'll leave the exact code as an exercise to reader, since it is homework after all ;) It's a good exercise to outline the possible states of data throughout a function in order to determine the correct action for each state, similar to formally defining base cases vs. recursive cases for recursive functions. Finally, I noticed you have delete calls on both pStart and pNextWord in your destructor. First, to delete arrays, you need to use delete [] ptr; (i.e., array delete). Second, you wouldn't delete both pStart and pNextWord because pNextWord points into the pStart array. Third, by the end, pStart no longer points to the start of the memory, so you would need a separate member to store the original start for the delete [] call. Lastly, these arrays are allocated on the stack and not the heap (i.e., using char var[], not char* var = new char[]), and therefore they shouldn't be deleted. Therefore, you should simply use an empty destructor. Another useful tip is to count the number of new and delete calls; there should be the same number of each. In this case, you have zero new calls, and two delete calls, indicating a serious issue. If it was the opposite, it would indicate a memory leak.
2,219,557
2,242,426
Bidimensional Hashmaps in Java (and in general)
which is the best way to write a bidimensional hashmap efficiently in Java? Just to give an example of what I'm talking about: I'm developing some algorithms related to collective intelligence, these algorithms works by calculating correlation between pairs of elements.. Without caching these values, since they are calculated on same pairs multiple times, performance are horrible.. (algorithms can be O(n^2) but maybe O(n^3) so I was thinking about using an HashMap to store values to be used multiple times. Which is the most efficient way to implement such a data structure in Java? It should be possble to cache and remove a value generated by a pair of elements with O(1), but using an explicit class seems too heavy anyway. If Java will turn out to be not enough I'll have to switch to C/C++, so any idea related to these languages are welcome too. Thanks
I partially solved the problem by concatenating hashcodes of both items using something like this: private long computeKey(Object o1, Object o2) { int h1 = o1.hashCode(); int h2 = o2.hashCode(); if (h1 < h2) { int swap = h1; h1 = h2; h2 = swap; } return ((long)h1) << 32 | h2; } I still have to figure out which is the most efficient way to store all the elements already cached with a specified one to remove them when the algorithm don't need the item anymore, just to avoid filling of the HashMap with a waste of item. That's because the kind of algorithm merges two items at every iteration removing them from used ones but adding the new generated item.
2,219,562
2,219,710
getopt fails to detect missing argument for option
I have a program which takes various command line arguments. For the sake of simplification, we will say it takes 3 flags, -a, -b, and -c, and use the following code to parse my arguments: int c; while((c = getopt(argc, argv, ":a:b:c")) != EOF) { switch (c) { case 'a': cout << optarg << endl; break; case 'b': cout << optarg << endl; break; case ':': cerr << "Missing option." << endl; exit(1); break; } } note: a, and b take parameters after the flag. But I run into an issue if I invoke my program say with ./myprog -a -b parameterForB where I forgot parameterForA, the parameterForA (represented by optarg) is returned as -b and parameterForB is considered an option with no parameter and optind is set to the index of parameterForB in argv. The desired behavior in this situation would be that ':' is returned after no argument is found for -a, and Missing option. is printed to standard error. However, that only occurs in the event that -a is the last parameter passed into the program. I guess the question is: is there a way to make getopt() assume that no options will begin with -?
See the POSIX standard definition for getopt. It says that If it [getopt] detects a missing option-argument, it shall return the colon character ( ':' ) if the first character of optstring was a colon, or a question-mark character ( '?' ) otherwise. As for that detection, If the option was the last character in the string pointed to by an element of argv, then optarg shall contain the next element of argv, and optind shall be incremented by 2. If the resulting value of optind is greater than argc, this indicates a missing option-argument, and getopt() shall return an error indication. Otherwise, optarg shall point to the string following the option character in that element of argv, and optind shall be incremented by 1. It looks like getopt is defined not to do what you want, so you have to implement the check yourself. Fortunately, you can do that by inspecting *optarg and changing optind yourself. int c, prev_ind; while(prev_ind = optind, (c = getopt(argc, argv, ":a:b:c")) != EOF) { if ( optind == prev_ind + 2 && *optarg == '-' ) { c = ':'; -- optind; } switch ( …
2,219,600
2,219,629
I can use SetWindowPos to place the window behind another window, but how do I place it in front of a given window?
SetWindowPosition second parameter is hWndInsertAfter which means behind. How do I place a window in front of another (above)?
How about you call SetWindowPos again, swapping the hwnd parameters (so your original window is now the hWndInsertAfter, and the initial hWndInsertAfter is now the hWnd you're moving), and passing in the SWP_NOMOVE flag? Edit: And if the exact position in the Z-order doesn't matter and you just want it in front, don't forget about SetForegroundWindow.
2,219,669
2,219,776
How to I pass a table from Lua into C++?
How would I pass a table of unknown length from Lua into a bound C++ function? I want to be able to call the Lua function like this: call_C_Func({1,1,2,3,5,8,13,21}) And copy the table contents into an array (preferably STL vector)?
If you use LuaBind it's as simple as one registered call. As for rolling up your own, you need to take a look at lua_next function. Basically the code is as follows: lua_pushnil(state); // first key index = lua_gettop(state); while ( lua_next(state,index) ) { // traverse keys something = lua_tosomething(state,-1); // tonumber for example results.push_back(something); lua_pop(state,1); // stack restore }
2,219,690
2,219,730
How can I make this work with every delimiter in C++?
I just wrote a program that tokenizes a char array using pointers. The program only needed to work with a space as the delimiter character. I just turned it in and got full credit, but after turning it in, I realized that this program worked only if the delimiter character was a space. My question is, how could I make this program work with an arbitrary delimiter character? The function I've shown you below returns a pointer to the next word in the char array. This is what I believe I need to change for it to work with any delimiter character. Thanks! Code: char* StringTokenizer::Next(void) { pNextWord = pStart; if (*pStart == '\0') { return NULL; } while (*pStart != delim) { pStart++; } if (*pStart == '\0') { return NULL; } *pStart = '\0'; pStart++; return pNextWord; } The printing loop in main(): while ((nextWord = tk.Next()) != NULL) { cout << nextWord << endl; }
The simpliest way is to change your while (*pStart != delim) to something like while (*pStart != ' ' && *pStart != '\n' && *pStart != '\t') Or, you could make delim a string, and create a function that checks if a char is in the string: bool isDelim(char c, const char *delim) { while (*delim) { if (*delim == c) return true; delim++; } return false; } while ( !isDelim(*pStart, " \n\t") ) Or, perhaps the best solution is to use one of the prebuilt functions for doing all this, such as strtok.
2,219,696
2,219,702
How to know if the user is using multiple monitors
I'm trying to figure out a way to know if the user is using multiple monitors. I would like to know how to do this in native C++ (using the Win32 API) and with managed code (using the .NET Framework). Thanks in advance
I can give you C# .NET: if (Screen.AllScreens.Length > 1) { // Multiple monitors } Edit: A search on Google turned up the following. It mentions 98/ME so it might no be relevant but may point you in the right direction: There are new APIs for handling multiple monitors in Windows 98. The APIs used in the monitors class sample are GetMonitorInfo, MonitorFromWindow and MonitorFromRect. The GetSystemMetrics API has some new constants (see below) that can be used to determine the metrics of a multiple monitor system. The GetSystemMetrics API returns information about the Windows environment. This API can be used to determine how many monitors are on the system, whether they are set at the same display format, and the size of the virtual desktop. http://support.microsoft.com/kb/194578
2,219,719
2,219,778
Are structs necessary in binary search trees
I've looked at some code for BSTs and I can see that each node is a struct. Is this necessary?
int flat_tree[ 1000 ][ 3 ]; // for each tree node, value is stored in element [id][0] // id of left_child stored in element [id][1] // id of right_child stored in element [id][2] … I'm not gonna go any further with this. Generally speaking, structs/classes are used for any kind of linked data structure. Also generally, any feature of the type system may be defeated or ignored and you can do everything (heap allocation, etc) in one array of ints in very painful fashion.
2,219,772
2,219,787
Advantage of STL resize()
The resize() function makes vector contain the required number of elements. If we require less elements than vector already contain, the last ones will be deleted. If we ask vector to grow, it will enlarge its size and fill the newly created elements with zeroes. vector<int> v(20); for(int i = 0; i < 20; i++) { v[i] = i+1; } v.resize(25); for(int i = 20; i < 25; i++) { v[i] = i*2; } But if we use push_back() after resize(), it will add elements AFTER the newly allocated size, but not INTO it. In the example above the size of the resulting vector is 25, while if we use push_back() in a second loop, it would be 30. vector<int> v(20); for(int i = 0; i < 20; i++) { v[i] = i+1; } v.resize(25); for(int i = 20; i < 25; i++) { v.push_back(i*2); // Writes to elements with indices [25..30), not [20..25) ! < } Then where is the advantage of resize() function ? Doesn't it creates a confusion for indexing and accessing elements from the vector ?
It sounds as though you should be using vector::reserve. vector::resize is used to initialize the newly created space with a given value (or just the default.) The second parameter to the function is the initialization value to use.
2,219,872
2,219,929
Is there any way I can access Private member variable of a class?
Is there any way I can access Private member variable of a class? Editing: Not from a member function or friend function but through an instance.
Just cast it around, shift memory and cast back. (didn't compile the code, but you should get the idea). class Bla { public: Bla() : x(15), str("bla") {} private: int x; std::string str; } int main() { Bla bla; int x = *((int*)(&bla)); std::string str = *((std::string*)((int*)(&bla) + 1)); std::cout << x << str; return 0; } Since this is an interview question, I won't go into why you shouldn't do that. :) EDIT: Classes with virtual functions will have virtual table pointer somewhere there as well. I'm not sure if & will give you address of vt or address of first data member. Alignment is 4 by default (right?), so if member you are reading does not align, shift by 2 bytes to get to the next one.
2,219,975
2,220,097
How do I create a resource dll
How do I create a resource dll ? The dll will be having a set of .png files. In a way these .png files should be exposed from the dll. My application would need to refer this dll to get a .png file.
A resource dll is the same as any other dll, it just has little or no code in it, and relatively more resources. Microsoft doesn't have a predefined resource type for PNG files, but you can define your own The most minimal possible resource dll is just a compiled .rc file passed to the linker like this. //save this as resources.rc (supply your own .png file) #define RT_PNG 99 #define ID_DIGG 1 ID_DIGG RT_PNG "image\\digg.png" Then execute these commands at a command prompt. rc resources.rc link /dll /noentry /machine:x86 resources.res Thats it. the first command compiles resources.rc into resources.res the second command turns resources.res into a dll. You should now have a dll called resources.dll that contains a single png file. In practice, of course, you will want to put the #defines in a header file that you share with the code that uses the dll. To use the dll in C++, your code would look something like this. #define RT_PNG MAKEINTRESOURCE(99) #define ID_DIGG MAKEINTRESOURCE(1) HMODULE hMod = LoadLibraryEx("resources.dll", NULL, LOAD_LIBRARY_AS_DATAFILE); if (NULL != hMod) { HRSRC hRes = FindResource(hMod, RT_PNG, ID_DIGG); if (NULL != hRes) { HGLOBAL hgbl = LoadResource(hMod, hRes) void * pPng = LockResource(hgbl); UINT32 cbPng = SizeofResource(hMod, hRes); // pPng now points to the contents of your your .png file // and cbPng is its size in bytes } // Don't free the library until you are done with pPng // FreeLibrary(hMod); }
2,220,166
2,220,491
to program GUI app , what will be the must user and developer frendly toolkit in c++
i like to build desktop application , that will be must user friendly in view what i mean is that the look and feel will be natural in the way the user used to see windows apps . and this toolkit/framework to be as much as possible easy fast to develop from the developer side in c++ .
Could we ask some more questions, what do you mean by user friendly(system integration easy keybingings/Accessibility)? Which platforms(windows only? You seem to indicate this, if so xp-7? Would fairly easy crossplatform support be a plus))? Do you want a form builder? an ide? special libraries? open source or closed source? do you mind paying? qt is probably the most recommended option although there is also FLTK Juce wxwidgets gtk+(c based or use with gtk-- a c++ wrapper)
2,220,230
2,221,470
Is a member of an rvalue structure an rvalue or lvalue?
A function call returning a structure is an rvalue expression, but what about its members? This piece of code works well with my g++ compiler, but gcc gives a error saying "lvalue required as left operand of assignment": struct A { int v; }; struct A fun() { struct A tmp; return tmp; } int main() { fun().v = 1; } gcc treats fun().v as rvalue, and I can understand that. But g++ doesn't think the assignment expression is wrong. Does that mean fun1().v is lvalue in C++? Now the problem is, I searched the C++98/03 standard, finding nothing telling about whether fun().v is lvalue or rvalue. So, what is it?
A member of an rvalue expression is an rvalue. The standard states in 5.3.5 [expr.ref]: If E2 is declared to have type “reference to T”, then E1.E2 is an lvalue [...] - If E2 is a non-static data member, and the type of E1 is “cq1 vq1 X”, and the type of E2 is “cq2 vq2 T”, the expression designates the named member of the object designated by the first expression. If E1 is an lvalue, then E1.E2 is an lvalue.
2,220,777
2,220,847
Which is more efficient ? if statement
Which is more efficient if(!var_name) or if(var_name == NULL)
Both will compile to the same code. Your choice of which to use should depend on which is most readable. This version: if(var_name == NULL) should only be used when var_name is a pointer, otherwise you will confuse anyone who reads your code in the future. Some compilers might complain if you use this on a non-pointer. This one: if(!var_name) should be used in cases when you are logically treating var_name as a boolean (true/false) value. This can include when var_name is a pointer, since NULL is the value for "false" or undefined pointers. If var_name is an integer, then I would choose a third option: if(var_name == 0) as I find it expresses intent more clearly.
2,220,916
2,220,956
Why isn't it legal to convert "pointer to pointer to non-const" to a "pointer to pointer to const"
It is legal to convert a pointer-to-non-const to a pointer-to-const. Then why isn't it legal to convert a pointer to pointer to non-const to a pointer to pointer to const? E.g., why is the following code illegal: char *s1 = 0; const char *s2 = s1; // OK... char *a[MAX]; // aka char ** const char **ps = a; // error!
From the standard: const char c = 'c'; char* pc; const char** pcc = &pc; // not allowed *pcc = &c; *pc = 'C'; // would allow to modify a const object
2,220,975
2,220,990
C++ static template member, one instance for each template type?
Usually static members/objects of one class are the same for each instance of the class having the static member/object. Anyways what about if the static object is part of a template class and also depends on the template argument? For example, like this: template<class T> class A{ public: static myObject<T> obj; } If I would cast one object of A as int and another one as float, I guess there would be two obj, one for each type? If I would create multiple objects of A as type int and multiple floats, would it still be two obj instances, since I am only using two different types?
Static members are different for each diffrent template initialization. This is because each template initialization is a different class that is generated by the compiler the first time it encounters that specific initialization of the template. The fact that static member variables are different is shown by this code: #include <iostream> template <class T> class Foo { public: static int bar; }; template <class T> int Foo<T>::bar; int main(int argc, char* argv[]) { Foo<int>::bar = 1; Foo<char>::bar = 2; std::cout << Foo<int>::bar << "," << Foo<char>::bar; } Which results in 1,2