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
5,886,958
5,887,092
A question about memory leaks
#include <QList> class MyType{ //This has some data in it.... }; QList<MyType> f() { QList<MyType> list; for(int i = 0; i<10; i++ ) { MyType* item = new MyType(); list << *item; } return list; } QList<MyType> temp_var = f(); When temp_var goes out of the scope an...
Yes, there will be a memory leak. As a general rule, you must have one delete for each new in your program. In your specific case, the faulty logic happens much earlier than temp_var's destruction. You allocate the items, and then store a copy of those items in the list. You should immediately destroy the original, no-...
5,887,416
5,887,433
In C++, how does the following code works?
Possible Duplicate: Do the parentheses after the type name make a difference with new? Which operations are performed by the following code: Test *t1 = new Test; // there is no () after new Test; if there is a user declared default constructor? What about this: Test *t2 = new Test(); // there is () after new Test; ...
They're equivalent, in both cases a ctor with no arguments will be called.
5,887,524
5,887,635
sorting a column with rows
I have a set of points (x,y,z). I want to sort these data using first column and 2nd and 3rd columns should be rearranged according to the sorting 1st column. is it possible to do this in c++, if so could you pls help me. Herewith I am attaching codes of my implementation but I got a error message “invalid conversion ...
It's almost certainly easiest to use std::sort instead of qsort: class Point { int x, y, z; public: Point(int x, int y, int z) : x(x), y(y), z(z) {} bool operator<(Point const &other) { return x < other.x; } // skipping the reading and other stuff for now... }; int main() { std::vec...
5,887,615
5,887,670
creating an array of object pointers C++
I want to create an array that holds pointers to many object, but I don't know in advance the number of objects I'll hold, which means that I need to dynamically allocate memory for the array. I have thought of the next code: ants = new *Ant[num_ants]; for (i=1;i<num_ants+1;i++) { ants[i-1] = new Ant(); } where a...
Will it work? Yes. However, if possible, you should use a vector: #include <vector> std::vector<Ant*> ants; for (int i = 0; i < num_ants; ++i) { ants.push_back(new Ant()); } If you have to use a dynamically allocated array then I would prefer this syntax: typedef Ant* AntPtr; AntPtr * ants = new AntPtr[num_ants...
5,887,655
5,887,677
Throwing, catching, scoping stl::string.c_str() exceptions
Say I've written some function myFunc that can throw const char* exceptions: void myFunc() { int returnCode = whatever(); if (!returnCode) { std::string msg; msg.append("whatever function failed"); std::cerr << msg << std::endl; // print warning message throw msg.c_str(); // ...
msg.str() returns a temporary std::string. As temporaries are deleted at the end of a statement ;, the contents of the character string returned by c_str() become undefined when the throw ... ; statement terminates by leaving the scope via the exception mechanism. (The lifetime of the const char* temporary is obviously...
5,887,733
5,900,851
Program Doesn't Terminate Correctly
I'm writing a computer vision app (C++ and OpenCV). I am creating a GUI for it with wxWidgets - this is very simple; a button-press event calls the tracker app to begin. My call to terminate the app (i.e. on clicking to close button) is as follows: // Exiting the App void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)...
Thanks for all the help, I have solved the problem. Seems fairly obvious now but couldn't figure it out at the time! Originally, my computer vision app was called from a main function. However, with the new GUI code there is no need for a main so I replaced the original main with a shell class. Though I had been carefu...
5,887,931
5,887,961
call of overloaded 'min(int&, int&)' is ambiguous
I got some problem on template.This code passed under vc6 but failed under g++. Is there anybody could tell me the reason? thanks. #include<iostream> using namespace std; template<class T> T min(T x, T y) { return (x < y ? x : y); } int main() { int i1 = 23, i2 = 15, i; float f1 = 23.04, f2 = 43.2, f; ...
It's because you've imported all of the std namespace, which is a no-no. Note the other candidates are template std::min. Remove the using namespace std; and either import select symbols: using std::cout; using std::endl; or qualify them: std::cout << "The smaller of " << i1 << " and " << i2 << " is " << i << std::end...
5,888,022
5,888,676
Split string by single spaces
Possible Duplicate: How to split a string in C++? I need to split a string by single spaces and store it into an array of strings. I can achieve this using a istringstream, but what I am not being able to achieve is this: I want every space to terminate the current word. So, if there are two spaces consecutively, on...
You can even develop your own split function (I know, little old-fashioned): size_t split(const std::string &txt, std::vector<std::string> &strs, char ch) { size_t pos = txt.find( ch ); size_t initialPos = 0; strs.clear(); // Decompose statement while( pos != std::string::npos ) { strs.push...
5,888,099
5,888,241
C++: specifying a base class for a template parameter
I need to design a framework that computes the result of a divide-et-conquer algorithm in parallel. In order to use the framework, the user needs to specify somehow the procedure that implements the "divide" phase (a function from T to T), the "conquer" phase (a function from D to D) and T and D themselves. I've though...
You could create the base classes like this: struct BaseDivide { enum EnumDiv { derivedFromBaseDivide = true }; } template <typename T, typename D, typename Divide, typename Conquer> static_assert(D::derivedFromBaseDivide); D compute(T arg); What is the purpose of the additional Divide and Conquer templa...
5,888,217
5,888,250
How to export a struct to a file, and then memory map the file?
I have a struct that I'd like to export to a file, and then mmap() that file. One issue is that the struct has a member variable that is a string, and I'm not sure how mmap would handle that. In this case all of these strings are of identical size, 8 characters. I'm working on Windows, although I'm using an mmap() func...
The representation of std::string is not guaranteed by the C++ standard, so this won't work. std::string may (and commonly will) allocate its contents anywhere on the heap, so you'll be storing a pointer and a size member, rather than the string itself. A char array with compile-time constant size, such as tsetArr, sho...
5,888,255
5,888,322
Delete duplicates from Doubly linked list
Hello I stumbled following question You given unsorted doubly linked list.You should find and delete duplicates from Doubly linked list. What is the best way to do it with minimum algorithmic complexity? Thank you.
If the space is abundance and you have to really optimize this with time, perhaps you can use a Hashset (or equivalent in C++). You read each element and push it to the hashset. If the hashset reports a duplicate, it means that there is a duplicate. You simply would delete that node. The complexity is O(n)
5,888,316
5,888,479
loading video files into a buffer in C++
I am currently trying to create a program that takes a video file, usually an AVI, and trying to convert it into images. So far I got the process working perfectly and could be left alone if needed. However, I would like to see if it was possible to optimize it for speed. So my question is if it is possible to load a p...
What you can do is to load a few frames, lets call it a chunk of N frames, into a queue from the disk. Once you set a limit for the buffer, you then pull the frames out and process them. You can do this in parallel by using two queues (Q1 and Q2) and two threads (T1 and T2). While processing frames from Q1 using T2, y...
5,888,364
5,888,487
Word value into a key map which has set value
I know what a map is and the general basic functions of it, but I don't know why a set is being used here instead of just having declared int i = value or something similar. What I'm really trying to do is: after putting the word into the vector, I want to use the same word as a key to a value also. But I really don'...
I don't think you completely understand the requirement for this algorithm. (Is this homework, by the way?) The goal here is to produce a concordance -- a list of all of the occurrences of each word. The point of the set is to hold all of the occurrences. (Ex: The word "apple" might appear on pages 1, 73, and 100. So t...
5,888,398
5,888,637
"Deep" header dependency analysis
I work on a mid-sized C/C++ project to which I've already applied Doxygen+Graphviz. Its header graphs are useful, but they only show relationships based on #include. I'm interested in finding a (preferably linux-based) tool that analyzes file dependencies based not just on #include, but on actual symbol usage. For exam...
I've used Include What You Use before with pretty good results. It uses Clang to parse the C++ code and suggest forwards declarations to add and header files to remove. One drawback is that it makes assumptions about the layout of your code - basically the Google coding standards. So it will only look at SomeFile.h if ...
5,888,432
5,888,492
In boost, how to pass boost iterator to a function somehow casted as std::string
See specific question as a comment at the end of the following code. std::string s("my sample string \"with quotes\""); boost::escaped_list_separator<char> els(""," ","\"\'"); boost::tokenizer<boost::escaped_list_separator<char> >::iterator itr; boost::tokenizer<boost::escaped_list_separator<char> > tok(s, els); ...
boost::tokenizer<boost::escaped_list_separator<char> >::iterator is not a pointer to std::string, but you can turn it into std::string const * with &(*itr) If a const pointer is not what you must pass, you may be able to do std::string s(*itr); and pass &s, depending on the ownership semantics of fn_that_receives_poi...
5,888,675
5,892,224
Difference between image of FT in matlab vs. cuda
I am trying to implement a matlab code that I have that does a 2D convolution. The matlab code first centers the 3x3 kernel in a padded matrix the size of the Image. I do the same thing in my C++ code. I have outputted my array and the matlab matrix to .csv files and confirmed that they are identical. I then run a for...
Two things : matlab natively computes using double. Is your CUDA code doing the same ? matlab displayed tried to scale the values before displaying them, there is some option in plot to prevent this.
5,888,737
5,888,752
c socket send commands in string
i am new in the socket programming in C/C++. I wrote Client and Server Socket. They can send and receive string. The idea is to send the commands to the server in the string. It can look something like this : "GET X" or "SET X 2". I know how i can split string. and the program know that the first word in the string is ...
I think it's best to use a switch statement. If not you can use a map with the command string as key and a pointer to the callback function as a value.
5,888,757
6,535,600
Error including fwpmu.h in Visual Studio 2010
I'm trying to call some WFP functions from a C++ CLR class library (New Project -> Visual C++ -> CLR -> Class Library) Code: #include <windows.h> #include <fwpmu.h> #pragma comment (lib, "fwpuclnt.lib") With only that, many include files from the Windows SDK fail to compile. What am I missing? Example: Error 12 error ...
I found the solution, it's a bug in some header files: http://social.msdn.microsoft.com/Forums/en/wfp/thread/8fd93a3d-a794-4233-9ff7-09b89eed6b1f And a conflict between the CLR and another header: http://social.msdn.microsoft.com/Forums/en/vcgeneral/thread/92c473d6-c963-44fa-9150-6c6af502112b
5,888,883
5,893,877
How do I set focus to CEdit in child dialog that is inside TabCtrl?
I have a dialog box (CDialog) with owner-drawn CTabCtrl in it. Tabs content are child dialogs (one for each tab). There is an CEdit in each tab. When the user clicks a tab, I'm hiding all child dialogs using ShowWindow(SW_HIDE) and showing a selected one. The problem is that when I have, for example, two tabs, click in...
Try this: GetDlgItem(IDC_YOURCONTROL)->SetFocus(); Or the related variable linked with the control: m_YOURCONTROLControl.SetFocus();
5,889,202
5,889,227
Sending a file from server side to client side using TCP in C++
Now this is a bit more of a request since I am not able to find any simple and direct example for this. Issue: I want to send a file from the server side to the client side. When the server is already up and listening on a port and the client requests a file (file's name being accepted as a parameter with the server ...
Check Beej's Guide to Network Programming. There are lots of examples there that shows how to implement a client/server architecture using sockets and send data between them. EDIT: Check items 8 and 9 from this tutorial for a complete example on client/server. Note that on item 8, the server sends a char* to the client...
5,889,235
5,889,550
Creating image with Boost.GIL
I've been trying to read the boost::gil documentation, but it's somewhere between lacking, and convoluted. Ranting aside, I need an example on how to do the following: Create an image of, say 512x512. Fill it with red pixels. Write to PNG. I can't find anything about doing any of that, at all, in the documentation for ...
I haven't used GIL yet, but I want to learn it as well. Having looked at the design guide and having googled up the error related to libpng, looks like the simplest example is #define png_infopp_NULL (png_infopp)NULL #define int_p_NULL (int*)NULL #include <boost/gil/gil_all.hpp> #include <boost/gil/extension/io/png_dyn...
5,889,249
5,889,333
Parameter evaluation and undefined behavior
Given this example (which is a simplication of an example in the documentation for boost::multi_index_container about update rollbacks): #include <iostream> struct change { int val_; change(int const &val) : val_(val) { } void operator() (int &v) const { ...
All the parameters to a function call are evaluated before the function is called. The order in which the parameters are evaluated is unspecified. In your case i would still be 17.
5,889,426
5,889,456
What does this mean in C++
I've encountered this in Visual C++ applications extern map<string, rpcfn_type> mapCallTable; or map<string, string> What does it mean? Not the map thing, but the <string, string> part
Those are template parameters; map is a class template, and it's not complete until you tell it the types it will be working with. The first is the type of the key, and the second is the type of the data that will be stored via the key.
5,889,532
5,892,565
How do I create a queue that holds boost::packaged_task<> with functions that return arbitrary types?
I'm trying to construct a work queue of functions that need to be executed by one thread and can be fed by many threads. To accomplish this, I was planning on using the boost::packaged_task and boost::unique_future. The idea would be you would do: Foo value = queue.add(myFunc).get(); which would block, until the functi...
You should store boost::function<void()>'s. Note that boost::packaged_task<R>::operator() doesn't return anything; it populates the associated boost::future. In fact, even if it returned something you could still use boost::function<void()> since you'd still have no interest in the returned value: all you care about is...
5,889,545
5,889,604
For loop for reading strings from a file into a 3D array
I'm having a problem with one of my functions, I'm working on a simple tile map editor, and I'm trying to implement a 3D array to keep track of tiles (x,y, layer). Before this I had a 1D array where all the tiles were just listed sequencially: bool Map::OnLoad(char* File) { TileList.clear(); FILE* FileHandle = ...
TileList2.clear(); This line reinitializes TileList2, so it is back to a zero-length vector. Delete that line, and you will probably be okay.
5,889,649
5,889,664
How many elements will be in the array?
char a [] = "EFG\r\n" ; How many elements will be in the array created by the declaration above?
6 characters: E F G \r \n \0 You can see this for yourself by running: char a [] = "EFG\r\n" ; printf("%d\n", sizeof(a)); // 6 The following code shows you the value for each byte: char a [] = "EFG\r\n" ; int length = sizeof(a), i; for(i = 0; i < length; i++) { printf("0x%02x ", a[i]); } // 0x45 0x46 0x47 0x0d 0x0...
5,889,691
5,889,856
Windows Mobile returns 0 on `new` failure
I have a Visual Studio 2008 Windows Mobile 6.5.3 ARMV4I project. I check for out of memory conditions using a try/catch block looking for std::bad_alloc exceptions. But, through testing I've found that it can actually just return a NULL value and not throw an exception. int _tmain( int argc, _TCHAR* argv[] ) { int...
What you observe simply means that the library supplied with the compiler is broken. It is broken in a sense that it does not follow the requirements of C++ language standard. This particular issue with new has been present in the earlier versions of C++ standard library (like the one supplied with VC 6.0). Later some...
5,889,821
5,889,951
C# loading C++ DLL - Problem on Exit
Ok so I have a C# user interface which uses a C++ DLL. The DLL is actually an OpenGL/SDL game. Once the game has finished it goes back to the C# UI. This all works nicely and as far as I know, correctly. The problem comes when I try to exit the actual program. The C# form closes, however an error follows shortly which ...
The dll is unloaded by Windows when the application exits. During this process the static variables of your dll will be destroyed. If your game did not properly end and some loop is still sending events to e.g. a static class which in turn routes them into your C# UI you can get this sort of error. At first you should...
5,889,843
5,892,112
Templates and friends
While reading from Thinking in C++ Volume 2, from the Templates in Depth chapter, I see that if you have a friendly function in a template class, you need to forward declaration that function. I made this example to test this, overlaoding the output operator: #include <iostream> using namespace std; /* template<class T...
Since it seems that my comment was satisfactory, here it is in form of an answer. The C++FAQ Lite has a chapter on this, which, for the sake of completeness, boils down to two possible ways to convince the compiler while it is examining the body of the class X that the friend function operator<< is actually a function ...
5,889,861
5,889,888
What constructor or operator is used in a return (C++)
I run this code for experimenting copy constructor and assignment operator class AClass { private: int a; public: AClass (int a_) : a(a_) { cout << " constructor AClass(int) " << a << endl; } AClass(const AClass & x) : a(x.a) { cout << " copy constru...
The compiler is allowed to elide copying in a case like this. This is called Return Value Optimization.
5,890,001
5,890,443
new to windows application development, need some advice
Hi I'm starting windows application development on windows7 with C++. ( or C#/Java if necessary ). The application in mind right now is a window that has a inner frame (kind like a iframe) displaying a web page in it, and to have the outer and inner frame be able to communicate ( ie. the webpage pass a message to the o...
I've seen projects use the status bar to communicate with Javascript in an embedded browser. RichHtml4Eclipse is such a project ; while no longer in development, it demonstrates the general approach. Events with structured data are raised by changing the status text, which native code on the outside can pick up and des...
5,890,084
5,890,191
pointer to a function or a functor? function generator
I'm trying to build a polynomial function generator, so that it takes a vector (arbitrary size) as argument, and generates a polynomial function I can use later. for instance, poly_gen(vector<int> power_index) returns a function (or by other method) in forms of (that i can call with another function) y(k)=a0+ a1*n+ a2...
You can't generate functions at runtime in C++, so you're going to have to go with a functor. You can create an object that stores the coefficients given by power_index in some manner (perhaps a direct copy), and give it an operator() (int n) operator that will take the coefficients and calculate the value of the polyn...
5,890,112
5,890,345
What are the potential security vulnerabilities? C++
My boss told me to look at the following code and tell him what the potential security vulnerabilities were. I'm not very good at this kind of thing, since I don't think in the way of trying to hack code. All I see is that nothing is declared private, but other than that I just don't know. #define NAME_SIZE (unsigned c...
What I saw (by no means a complete list): There's no guarantees you're going to get a char pointer which points to a null-terminating string (unless you're allowed to make that assumption, not really a safe one to make). strtok and strcpy are the C way of doing things and come with the fun stuff of programming C code....
5,890,228
5,890,300
C++ hash function which takes a seed
Update - What library can give me a good hash function that takes a seed in c++?
Do you mean something like a Perfect Hash Generator, and not something like a List of Hash Functions, written to share a common interface which is then melodramatically selected at runtime. EDIT: now that the question is clarified, only you can evaluate which is "the best" perfect hash generator for your application w...
5,890,382
5,890,644
Operator overload which permits capturing with rvalue but not assigning to
Is it possible to design and how should I make overloaded operator+ for my class C to have this possible: C&& c = c1 + c2; but this not possible: c1 + c2 = something; Edit: I changed objects to small letters. c1, c2 and c are objects of class C. && is not the logical operator&&, but rather an rvalue reference. For ex...
Have the assignment operator be callable on lvalues only: class C { // ... public: C& operator=(const C&) & = default; }; Note the single ampersand after the closing parenthesis. It prevents assigning to rvalues.
5,890,483
5,890,803
Output a vector of strings before and after 'word' NOT using regex. Making concordance program
I'm working on a concordance program and currently working on the getContext function. I need this function work somewhat like regex, but I want it to return a vector of strings before and after the specified word. I don't know if what I'm thinking about is correct, but it's all that I can think of. So this is what I h...
If you're just looking for a std::string in a std::vector<std::string> then you can use std::find bool IsWordInArrayOfWords(const std::vector<string>& arrayOfWords, const std::string& word) { auto found = std::find(arrayOfWords.cbegin(), arrayOfWords.cend(), word); return found != arrayOfWords.cend(); } If you...
5,890,594
22,964,562
Memory mapped file std::allocator implementation freezes WM6 device
I have a Visual Studio 2008 C++ project for Windows Mobile 6.x where I need more memory than is available to me in the 32MB process slot. So, I'm looking at using memory mapped files. I've created a standard allocator implementation that replaces new/delete with CreateFileMapping and MapViewOfFile. The intended use is ...
I just got the "popular question" badge for this one, so I thought I'd (belatedly) post the answer. I was running out of available handles. There is an unsigned short counter in the Windows Mobile kernel relating to handle allocation that was overflowing. Once that happened, the device would freeze.
5,890,875
5,901,754
Best Way to implement Socket Interface to support both IPV6 and IPV4
What is the best way to implement socket interface to support IPV6. The existing code suppports IPV4 only. Now, to support IPV6 also I have few doubts... 1) Should _I replace all the APIs of IPV4 by IPV6 APIs. Say AF_INET by AF_INET6, sockaddr_in by sockaddr_in6 etc. Will these new APIs support both the protocols. 2) O...
Technically neither option (1) or (2), you should migrate to IP family agnostic APIs and use struct sockaddr and struct sockaddr_storage instead of IPv4 and IPv6 hardwired structures. Stevens' gives good examples of creating an agnostic API, here is a similar method I employed: http://code.google.com/p/openpgm/source/...
5,890,950
5,891,200
How do I properly compare two unsigned char's?
Looking to compare two BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH]; from the IP_ADAPTER_ADDRESSES Structure where byte is defined in windows as typedef unsigned char BYTE; Do I need to compare memory? Thanks!
Matteo beat me to it. His answer is correct. Unfortunately I could not comment directly on his post (I may be too new here), but I wanted to confirm his response since the majority of answers thus far are incorrect. The data type in question is an array of bytes. Do NOT use the equality operator (==) for comparing th...
5,891,034
5,891,171
Serial.println within a class in Arduino
I'm trying to do Serial.println() within a class in the Arduino IDE. However, the compiler is saying that Serial was not declared in this scope. Here is the code: Code in Menu.h class Menu { public: int options[4]; void test() { Serial.println("here"); } private: }; Code in...
The right #include is probably added automatically by Arduino to your .pde. Try #include <WProgram.h> in the top of your Menu.h.
5,891,221
5,897,216
Variadic macros with zero arguments
I am working on a call macro, #define CALL(f,...) FN(f)->call((ref(new LinkedList()), __VA_ARGS__)) which when called, CALL(print,2,3,4,5); adds 2 3 4 5 to the linked list (, is overloaded to do so) and calls print which expects a linked list which works as expected how ever there are some calls which do not require ...
As for the updated question, by the use of auxiliary macro VA_ARGS like the following, the arguments will be expanded as expected. #define VA_ARGS(...) , ##__VA_ARGS__ #define CALL(f,...) FN(f)->call((ref(new LinkedList()) VA_ARGS(__VA_ARGS__)))
5,891,259
5,891,705
Empty destructor causing slow code?
I'm implementing a custom iterator for a non-STL container type and came across the following behaviour, which at this stage, seems a bit unexpected to me. It seems that there's a significant performance hit that results when you define an "empty" dtor?? Why?? To try to get to the bottom of this I implemented a simple ...
I recall experiencing something similar with GCC (-O3) on Linux. The code for a user-defined destructor, despite being empty and in the header file, was emitted, whereas the compiler-generated default destructor yielded no instructions. This perplexed me, and ultimately I made the code work with no explicit destructo...
5,891,339
5,901,943
How to compile c++ code with boost lib? on Ubuntu
#include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> I used headers shown above. Cannot find help on Boost Official website.
Assuming no errors in your code, you need to link the correct boost libraries: boost_thread, boost_system, and boost_date_time are the ones you've referenced, so #include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> int m...
5,891,610
5,891,643
How to remove certain characters from a string in C++?
For example I have a user input a phone number. cout << "Enter phone number: "; INPUT: (555) 555-5555 cin >> phone; I want to remove the "(", ")", and "-" characters from the string. I've looked at the string remove, find and replace functions however I only see that they operate based on position. Is there a string f...
string str("(555) 555-5555"); char chars[] = "()-"; for (unsigned int i = 0; i < strlen(chars); ++i) { // you need include <algorithm> to use general algorithms like std::remove() str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end()); } // output: 555 5555555 cout << s...
5,891,664
5,891,752
Is it possible to use Boost.Spirit V2.x without Boost.Fusion?
Is it really necessary to wrap structs/classes with Boost.Fusion in order to use them with Boost.Spirit V2.x (especially Boost.Spirit.Qi)? I would much rather use semantic actions to assign to members. If my memory serves me well, this is the way it used to be done in V1.x... The calculator example suggests that it sho...
Nevermind, I still had the old fusion printing stuff in there. Funny how mistakes become so much easier to find after you have posted the question... :) (Since this works, I must have made another error in the production code.)
5,891,774
5,892,005
Alternatives to FreeTDS?
We're running a Linux server with Microsoft SQL Server for the database. Are there any good (preferably open source) c libraries that we could use other than FreeTDS? Thank you
Not really. Sybase has some client libraries, but they only work for older versions of MS SQL Server (since it is a derivative of Sybase SQL Server).
5,891,811
5,892,147
Generate random number between 1 and 3 in C++
Possible Duplicate: Generating random integer from a range I just started learning C++ and I'm trying to generate a random integer thats either 1, 2, or 3. I searched around and all the examples I see of generating random numbers are confusing and always different from the last example I looked at. Is there a simple...
The modulo solution is the most straightforward but it usually loses randomness as modulo as the tendency to "eat up" the lowest bits of the result. A more random way is to map [0,1[ over [a,b[ in a linear way: int roll(int min, int max) { // x is in [0,1[ double x = rand()/static_cast<double>(RAND_MAX+1); ...
5,891,901
5,891,925
What is considered a statement in C++?
My professor commonly asks my class how many statements there are in a given program, but I can't determine what he defines as a statement. It seems as though an if/else is one statement, and a for loop is one statement regardless of if there are other supposed statements within it. Are there any governing rules for ...
For a precise definition of a statement: Definition: A statement is a block of code that does something. An assignment statement assigns a value to a variable. A for statement performs a loop. In C, C++ and C# Statements can be grouped together as one statement using curly brackets { statement1; statement2; } As...
5,892,009
5,892,069
can return type mix? or workaround solution
I have a Fraction class, works fine within its own yard, like 1/2+1/3=5/6 or even with int,1/2+2=5/2. It is okay for me to see 3/2+3/2=3/1, however, is there a way to return a type conditioned? For example, if the denominator is 1, it returns an int, otherwise returns a Fraction. If not possible, any other detour? cla...
You can't conditionally change the return type. (You could have polymorphism if you had a super class, but that's not what you're asking for here since int is an intrinsic type.) Consider this case: Fraction A, B; // initialize to 3/2 and 3/2 sometype C = A + B; What is the type of C? The compiler must know. Even in ...
5,892,137
5,892,218
Storing Socket Information Random Access Speed
Current situation: I have a linux server (for chatting with strangers) set up and I have a question on efficiency. Currently I'm using a map in a simple manager class to pair up two strangers: int sockManager::set_pair(int me, int them) { if (them != -1) { pairs[me] = them; pairs[them] = me; return 1; } ...
How would I go about implementing an event-based system to listen for incoming data from users? (OS: ubuntu linux) and How much faster will it be? I've stress tested my server as it is and I can handle several hundred clients across the network without a noticeable slowdown on the user's side. I'd like...
5,892,199
5,892,236
problem with virtualalloc
virtualpointer=(char*) VirtualAlloc (NULL, (unsigned __int64) (1<<31), MEM_RESERVE, PAGE_READWRITE); mainhashbuf=progression=virtualpointer; VirtualAlloc (progression, (unsigned __int64) (1<<15), MEM_COMMIT, PAGE_READWRITE); progression=progression+capacity; *(mainhashbuf+1000)='c'; mainhashbuf, progression and virtu...
VirtualAlloc attempts to allocate a contiguous range of virtual pages. 1<<31 == 0x80000000, which is the amount of memory user-mode processes have on windows by default. I severely doubt that the call to the first VirtualAlloc is succeeding. Choose lower values and start again. Also, why are you using VirtualAlloc? Wh...
5,892,323
5,892,969
How to print many format strings into window?
After successfully solve this problem how to print a format string into window, another problem comes to me. If there are many format strings, how to print them into window? For example below: sprintf(buf, formatString-1...); SendMessage(hwnd, WM_SETTEXT, NULL, (LPARAM)buf); ... sprintf(buf, formatString-2...); SendMes...
Are you trying to produce a console-style or log-style window, with multiple lines of text, one after the other? If so, simplest approach is to pick a control that will do this for you. Something like a static (usually used for labels) typically is only useful for one string at a time. If you want to display more than ...
5,892,420
5,903,298
When will cellChanged signal be fired in QTableWidget?
I am using a QTableWidget to display and edit a data matrix. For validation purpose, I used the QLineEdit as items in this table. As following, pTable=new QTableWidget(N,N,this); pItem=new QLineEdit(); pItem->setText(tr("%1").arg(pInfra->adjacencyM(i,j))); rx=new QRegExp("0|1"); ...
Not aware about causes of this problem. Considering another ways. You can catch QLineEdit signal textChanged and use QSignalMapper to bind signal, fired by each QLineEdit to particular cell number. Maybe itsn't the best qway to do that, but you can use it in case this problem won't be solved.
5,892,586
5,892,604
Class Packing and Alignment
What is the alignment for calling #pragma pack() with no argument in GCC compiler? Also, I often see that when we use placement new in creating object, the class is often being packed. What is the reason for that? Is it necessary to do so?
for the first part, you could have recklessly used google: http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html secondly there may be times when you need to control the binary format of your class. you may need to manage the amount of memory and the real binary offsets of data structures: struct { cha...
5,892,752
5,892,756
Model for a multithreaded/forked server daemon
I'm developing a database-connected Linux daemon in C++ that will act as a "server" for some networked controller devices. It has to have some form of concurrency to be able to service multiple devices at the same time. The server will listen for incoming connections and fork/thread/select()/whatever for each connected...
You should ahve a look at Boost::Asio and at the active object patterm. There is a nice video/talk about this very subject at boost'Con 2010 that you can find on blip.tvB
5,893,280
5,897,482
Adding Layout in QT on QMain WIndow using a code
I need some help I need to set a layout for my application but i don't know how to set layout on QmainWindow.. here is a part of my code for the window.cpp: window::window(QWidget *parent) : QMainWindow(parent) { createFilesTable(); queryopen(); exitButton = createButton("E&xit",SLOT(programout())); ...
For a QMainWindow, you use setCentralWidget(QWidget*), unlike all other QWidget subclasses. The reason is that QMainWindow already has its own layout, which includes places for menu bar, status bar, dock windows, etc. So you create another QWidget and set its layout to the layout you want, then make that QWidget the ce...
5,893,351
5,893,400
c++ problem inorder printing binary tree recursively
I have been practicing some old C++ problems to prepare for a few job interviews, and I am currently trying to recursively construct a binary tree from an array, and then print it inorder recursively as well. However, I got some weird values when trying to output the result. Problem : construct binary tree from array [...
The problem is in construct_tree. The calls to it are: construct_tree(0) -- from main() construct_tree(1) construct_tree(3) construct_tree(7) construct_tree(8) construct_tree(4) construct_tree(9) construct_tree(10) construct_tree(2) constru...
5,893,570
5,906,776
Boost MPL list of templates
I want to take a list of class templates, T1, T2, ... TN and have a list an MPL list of classes, where each template is instantiated with the same parameter. boost::mpl::list cannot be used with a list of template template parameters, just regular type parameters. So the following does not work: class A { ... }; templ...
You want something like this: #include <boost/mpl/list.hpp> #include <boost/mpl/apply_wrap.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/equal.hpp> #include <boost/mpl/assert.hpp> using namespace boost::mpl; template< typename U > class T1 {}; template< typename U > class T2 {}; template< typename U > c...
5,893,690
5,894,004
DFA Minimization Brzozowski algorithm
I am trying to implement Brzozowski's algorithm for minimizing my DFA Following is the algorithm for the same. DFA = d(r(d(r(NFA)))) where r() is reversal of NFA and D() converts NFA to DFA. But I do not understand what is the meaning of r() searching on google also does not gives much information. Can anybody please...
In the code for reverse.c (found here, but now defunct) you'll find a comment /* Create reversed edges */. So I'd say that r() is reversing the direction of all edges (plus making sure that the reversed automaton has a well defined start state).
5,894,121
5,894,331
C++ reading a sequence of integers
gooday programers. I have to design a C++ program that reads a sequence of positive integer values that ends with zero and find the length of the longest increasing subsequence in the given sequence. For example, for the following sequence of integer numbers: 1 2 3 4 5 2 3 4 1 2 5 6 8 9 1 2 3 0 the program should re...
In your program, you have made some assumptions, you need to validate them first. That the subsequence always starts at 1 That the subsequence always increments by 1 If those are correct assumptions, then here are some tweaks Move the cout outside of the loop The canonical way in C++ of testing whether an input oper...
5,894,262
5,894,324
Reverse word problem - program stuck in input loop?
I am trying to solve the reverse word problem. My solution works, and even skips blank lines. However, after all the lines of a file are read, the program gets stuck in a loop, constantly accepting input. This is very puzzling, and I feel like it has to do with my outer while loop, but I can't see what's wrong with it....
The problem is the inner loop. If I give in a text file containing only one word on a single line, it will fail since it will never come out of the inner loop. This code works for me: int main(int argc, char** argv) { stack<string> s; ifstream in; in.open(argv[1]); do { do { ...
5,894,323
5,894,357
linux pointers and references and methods
Sorry for destrubing. I have a problem: file.h #include <string> class X { public: X(); class Y { public: Y(); std::string name; }*yy; std::string method(X::Y *Y); }*xx; file.cpp #include "file.h" #include <iostream> #include <string> X::X() { yy= new X::Y(); } X::Y::Y() { ...
When you type fir->method(&tt); you pass the address of tt, which is a pointer. So you're passing a pointer to a pointer. What you want to do is fir->method(*tt);. Which will in fact pass your pointed object as a reference (because "converting" a pointer to a reference is done by "dereferencing" the pointer). This impl...
5,894,385
5,894,424
C++, #include problem!
My Includes are in a header called "stats.h" I have 2 classes A and B. A requires the header of B and A the header of B When I Try to compile, I get about 50 errors like this one identifier 'Player' int assumed ; before * missing Any ideads on how to fix this? :( (Here the relevant code) CLASS A - PLAYER #include "sta...
You don't have implementation in your headers, so you could pass with forward declarations and include the headers only in the cpp files. For example - before class Player, put forward declaration of class Weapon: //vvvvvvvvvvv class Weapon; class Player { public: Player(int x, int y); /* .. */ }; and remove...
5,894,405
5,894,517
Generate user customized .exe from another .exe in c++
In this project there is going to be two .exe files: Main, in this user can adjust settings and generate a .exe (child) Child, this .exe will have these user customized settings So basically the goal is let user generate their own customized .exe. All this happen from the main .exe I have embed a .exe (child) into an...
Store the settings as a resource in the embedded exe, then use BeginUpdateResource and friends to modify it after extracting. See Resource Functions on MSDN.
5,894,514
5,894,877
c++ finding the state of a sibling
In my code, there's a base class A which has three subclasses A1, A2, A3. These objects have a state to specify if they are active or not. Now in another class B , objects of A1, A2, and A3 are created. Now in a function inside B, int B::SetState( A& aObj) { //if aObj is an instance of A1, do nothing and return. /...
You can refactor this: if ( otherAObj.IsActive() ) { //do something with aObj } out into a doSomething() function public class A{ virtual bool isActive(){ return false; } virtual bool isPending(){ return false; } virtual void doSomething() { if(true == isActive()) { ... ...
5,894,558
5,894,602
typedef across same namespace in different header files
I'm currently learning c++ and struggling with some code: Garden.h: #ifndef GARDEN_H_ #define GARDEN_H_ #include <vector> #include <boost/tr1/memory.hpp> #include "Shape.h" #include "Utils.h" namespace cma { typedef boost::shared_ptr<cma::Shape> ShapePtr; typedef std::vector<cma::ShapePtr> GardenPlan; } #en...
You have a cyclical include problem. You're including Garden.h in Utils.h and Utils.h in Garden.h. You either need to put both definitions in the same header file or forward declare one of the types. However, you don't actually need to include Utils.h in Garden.h so removing that include should solve your problem.
5,894,775
5,894,903
Polymorphic objects on the stack?
In Why is there no base class in C++?, I quoted Stroustrup on why a common Object class for all classes is problematic in c++. In that quote there is the statement: Using a universal base class implies cost: Objects must be heap-allocated to be polymorphic; I really didn't look twice at it, and since its on Bjarnes h...
Looks like polymorphism to me. Polymorphism in C++ works when you have indirection; that is, either a pointer-to-T or a reference-to-T. Where T is stored is completely irrelevant. Bjarne also makes the mistake of saying "heap-allocated" which is technically inaccurate. (Note: this doesn't mean that a universal base cla...
5,894,940
5,898,066
Calling the constructor of the base class after some other instructions in C++
As far as I know it is not possible to call the constructor of the base class. The only way I know is this: MyClass::MyClass(/* args */) : Base(/* args */) { // ... } but this would invoke the constructor at the beginning. Is there any way to call it somewhere else in the constructor? Something like this: MyClass::...
If the base class constructor takes at least one argument, you could use a helper function like this: int DoStuffBeforeCtorAndForwardInt(int arg, Foo foo) { DoStuff(arg, foo); return arg; } MyClass::MyClass(int arg, Foo foo) : Base(DoStuffBeforeCtorAndForwardInt(arg, foo)) { // ... } If you want to def...
5,894,956
5,895,035
Does boost::bind cause overhead?
I am currently working on network software. It has one main class, server which obviously represents a server instance. A server instance can send requests and the user is notified of the response by a callback. The code is like: class server { public: typedef boost::function<void (int duration)> callback_func; ...
Of course it causes overhead. What it does is that it creates a functor that stores the bound parameters and has an operator() that you call with the remaining arguments. Now, is this significant? I don't know, because that is just a word. Make 10 million requests and measure it. You are the only one who can tell if th...
5,895,041
5,895,141
About the operations for the new operator
If I have a user defined default constructor in my Test class, and what operations will done by using the following statement: Test *test = new Test; //there is no () after new Test First, does the user default constructor means "constructor without Parameters"? for example: class Test { public: Test...
"Default constructor" means a constructor that can be called without parameters. It may have default parameters: class Test { public: Test(int x = 42); // Still default constructor. // Can be called as Test() and as Test(int); }; The new operator will call operator new to allocate memory, an...
5,895,067
5,895,086
Get drive letter of Hard drive
My application is for windows Vista and XP. There are more than on Hard drive connected to my machine. I need to get Drive Letters of the Hard drive from which my system is booting. By using GetLogicalDriveStrings Function I can get the drive letters of all Hard drives. But how can I differentiate that this particula...
Call GetLogicalDrives to get all the available drive letters. Call GetSystemDirectory to get the drive which contains the OS. Open the volume using CreateFile("\.\C:", ... Here replace C: with the drive letter returned in GetSystemDirectory. Call DeviceIControl of the returned handle with the IOCTL_VOLUME_GET_VOLUME_DI...
5,895,144
6,261,680
How can I identify the header that generates a warning?
I'm sure that many of you are familiar with this set of warnings. These are most of the time generated by a include file. Solution is pragma push/disable/pop, but identifying the header is not a nice task. Does anyone knows a way of identifying the header except trial-and-error ? 1>File1.cpp 1>C:\Program Files (x86)\M...
In my case, moving #include <strsafe.h> to the bottom of the list got rid of the warning without using extra compiler directives. A good way to find out where #pragma deprecated was being called was to go into the compiler settings under "Preprocessor" and to set Generate Preprocessed File to something like With Line N...
5,895,179
5,895,233
Syntax of out-of-class definition of a template member function of a template class
template<typename A, typename B> class mindF_ck { template<typename C> inline bool ouch(C & c_in); }; How do I define the signature for ouch out-of-class ? I send a query to my brain but it keeps coming up blank ;)
template<typename A, typename B> template<typename C> bool mindf_uck<A,B>::ouch(C & c_in) { }
5,895,265
5,895,330
Question about overloaded member functions in C++?
I am reading some C++ text from the address https://cs.senecac.on.ca/~chris.szalwinski/archives/btp200.081/content/overl.html. in the first lines, they say: The signature of a member function consists of: the function name, the data types of its parameters, the order of the parameters and possibly the const status of ...
In C++, you can declare a member function of a class to be const, by appending that keyword to its signature (for instance, int MyClass:doSomething(int param) const {...}). Doing so guarantees that the function won't change the (non-mutable) members of the class object on which the function is called - and hence it can...
5,895,337
5,895,340
Create file with certain size
Is there any method to create a file of desired size whenever I create a file using CreateFile(). Thanks.
SetEndOfFile can be used to extend or truncate a file.
5,895,374
5,895,417
getting errors with macros definition-c++
I am getting ClassID undeclared error in the following cpp code. #include "stdafx.h" #include <iostream> using namespace std; #define RM_SESSION_MSG 0x11 #define DECLARE_RS232_MSG(ClassID) enum { ID=ClassID } int main() { DECLARE_RS232_MSG(RM_SESSION_MSG) ...
You are missing the line splice characters #define DECLARE_RS232_MSG(ClassID) \ enum \ { \ ID=ClassID \ } The line splice characters say that the current line and the next line are merged into a single line. Without them, the macro ...
5,895,447
5,896,399
Changing from c++ to perl
I have unusual problem, there's no perl chat room so i decided to ask little questions here. #include <cstdio> double end, tmp; int test; int main(void) { scanf("%d", &test); for (int i = 0; i < test; i++) { scanf("%*s%*s%lf", &tmp); end += tmp; } end /= (double)test; ...
The following code is roughly equivalent to yours: my $divisor = <STDIN>; chomp $divisor; my $dividend = 0; while (<STDIN>) { my ($ignore1, $ignore2, $term) = split; chomp $term; $dividend += $term; } print( ($dividend / $divisor) . $/ ); It of course doesn't check for proper input, divide by zero or anything...
5,895,476
5,895,497
the pointer to a object in C++
I have a question about pointer to a object in C++. For example, if we have a CRectangle class and there is a y variable in it. CRectangle *x = new CRectangle; x->y means member y of object pointed by x, what about (*x).y? are they the same?
Yes, x->y and (*x).y are exactly the same in your example. The -> means dereference X, and *x means exactly the same.
5,895,649
5,895,721
Difference between .a .o and .lo file
What is the difference between .a .o and .lo file in C?
The '.lo' file is a library object, which may be built into a shared library, and the '.o' file is a standard object file The .lo file is the libtool object, which Libtool uses to determine what object file may be built into a shared library
5,895,790
6,078,905
How to change selection color in RichEdit control?
Basically, I want to change the standard RichEdit selection color in places where it is above colored text. I'm implementing a "highlight" function in a RichEdit control (like a yellow marker). Now when I apply highlight on the selected text, nothing changes visually because selection stays in place and it overrides ...
The color setting for text selection is hardwired to the system selection color in RichEdit 2.0 and higher. In RichEdit 1.0, the selection color is generated by inversing the background color, so you sort of have some control, but you will lose a lot of features if you downgrade to 1.0. A walkaround is to installing a...
5,896,030
5,897,276
How to use Windows ToolTip Control without bounding to a tool
I want to use the native windows tooltip control (pure Win32 API, no MFC stuff). I read the doc, it seems that I have to send a TTM_ADDTOOL message to bond a tool to the tooltip control. Only after that can I send TTM_TRACKACTIVATE & TTM_TRACKPOSITION to show the tooltip. But I want to display the tooltip anywhere I wa...
You need to call TTM_ADDTOOL at least once, you can't call TTM_SETTOOLINFO or get TTN_GETDISPINFO without it AFAIK. If your target it XP+ you can get away with using TTM_POPUP to display the tip at any position and at any time (But you need to handle the initial delay yourself unless you want a tracking tooltip) Genera...
5,896,062
5,896,104
Use an un-initialized pointer as a function parameter
As I want to pass an uninitialized pointer to a function, it goes runtime error. but if I pass this pointer as a reference, it works OK. I cannot explain why... class Body { }; void check(Body* b) { b = new Body(); } void checkRef(Body* &b) { b = new Body(); } int main001() { Body* b; //check(b);/...
In Body * &b b is an alias of/reference to the b in main - so when you assign to it you modify the b in main. In Body* b b is a local copy of the b in main, you're modifying this local copy and not the b in main. Your runtime error is likely due to using the uninitialized b in main. EDIT: The actual error you get is an...
5,896,098
5,897,235
Direct3D 9 Shadow Mapping Blend Mode
I am currently trying to draw shadows over a scene in direct3d 9. I am trying to do some multi pass rendering and am having trouble understanding how to use/set the blend mode. I have done a depth pass which fills the depth buffer and I then have a loop which loops through all the lights in the scene. Within that loop ...
I also think that you have wrong alpha blend states set. I assume that you do a SRC blend and replacing your old image with the new one and not doing any alpha blending. You need to think about what you want. I assume that you want a SRC_OVER blending. The Porter Duff rules can give you a hint and they are very easy to...
5,896,136
5,896,166
question about Scope Resolution Operator in C++?
I am learning C++ and not quite sure about the Scope Resolution Operator. suppose I have the following code: code 1: class Student { int no; int semester; char grade[M+1]; public: void display() const; }; void Student::display() const { cout << "Hi!" << endl; } code 2: class Student { ...
There is one difference - if defined in the class the function behaves as if it were declared as inline. But this is no big deal, and the compiler may well ignore it. The big difference is that for large, multi-file projects, if you make a change to the function body defined in the header, EVERY other file that uses yo...
5,896,230
5,896,294
Unqualified-id before string constant
On compiling following code I get error "expected unqualified-id before string constant" In file "Notification_Constants.h" namespace NOTIFICATION_CONSTANTS { #define SERVICE_EMAIL "service@company.com" } In file SendEmail.cpp #include "Notification_Constants.h" void UserPreferences::get_senders_email(String &_e...
First, you should put quotation marks around the email address: #define SERVICE_EMAIL "service@company.com" Second, you should not use #define at all. Use a const variable instead: const String SERVICE_EMAIL = "service@company.com"; #defines are type unsafe, have no scope and are generally evil. Last, you may want to...
5,896,354
5,896,395
C++ difference between a reference and a pass-by-reference argument
My question relates to the following member function of Bifstream which inherits from ifstream. Read expects a char pointer. I give it (char*)&target. target is a reference so what I've given it is a reference to a reference to an int. Why does this work? bool cBifstream::ReadInt( int& target ){ if( !this->is_op...
You're taking the address of a reference - this produces the address of the variable target refers to. A reference is an alias of the variable it refers to, there's no syntactic indirection anywhere - so any operation performed on the reference affects the referred to variable. int x; int & y=x; Using the above, any...
5,896,695
5,896,734
what is the problem of the following code?
I overload the operator (), as following: #include <iostream> using namespace std; class Test { public: Test() {}; void operator () (Test); }; void Test::operator () (Test test) { cout << "yes"; } int main() { Test test; (test); } when I run it, the "yes" does not show up? any problem with...
With that signature for operator() you would need to call it with something like: test(test); or possibly test(Test()); (test) is just an expression which has type Test that doesn't do anything.
5,896,887
5,896,919
What is the purpose of malloc hooks?
What exactly is the purpose of using malloc hooks? And I've read it's used in memory-profiling, etc. but never really understood how.
Well, if you can hook into the behaviour of allocation functions, then you can track memory allocations for profiling and debugging. The GCC documentation on malloc hooks has a nice little example demonstrating adding debug output every time the allocation functions are invoked. I'm not really sure what else to tell yo...
5,896,908
5,896,943
Understanding (simple?) C++ Inheritance
I'm struggling a bit to understand why this code snippet does not compile. #include <cstdio> class A { public: virtual int potential()=0; virtual int potential(int arg, int arg2)=0; }; class B : public A { public: int potential() { return 1; } virtual int potential(int arg, int arg2) { return 2; } }; ...
However, on compilation, only the method defined in C is recognized, and potential() isn't seen (this should have been inherited from B). C++ doesn’t work like this: because you implemented a different potential method (a method of the same name but with different parameters) in C, the other method is hidden as far a...
5,897,184
5,897,393
Algorithm to determine coin combinations
I was recently faced with a prompt for a programming algorithm that I had no idea what to do for. I've never really written an algorithm before, so I'm kind of a newb at this. The problem said to write a program to determine all of the possible coin combinations for a cashier to give back as change based on coin values...
This seems somewhat like a Partition, except that you don't use all integers in 1:50. It also seems similar to bin packing problem with slight differences: Wikipedia: Partition (Number Theory) Wikipedia: Bin packing problem Wolfram Mathworld: Partiton Actually, after thinking about it, it's an ILP, and thus NP-hard....
5,897,249
6,159,453
Using on_<widget>_<signal> where widget it own class
Is there a way to use the naming convention described in the title to connect a signal from your own class. E.g: class MyTree : public QTreeWidget { Q_OBJECT private slots: void on_this_itemClicked(QTreeWidgetItem* item, int column); }; i understand i could use connect like this... connect(this, SIGNAL(itemCl...
I am quite sure Qt auto connection use the objectName (QObject::setObjectName()), so there is no chance it can resolve this.
5,897,319
5,897,358
How to use std::sort to sort an array in C++
How to use standard template library std::sort() to sort an array declared as int v[2000]; Does C++ provide some function that can get the begin and end index of an array?
In C++0x/11 we get std::begin and std::end which are overloaded for arrays: #include <algorithm> int main(){ int v[2000]; std::sort(std::begin(v), std::end(v)); } If you don't have access to C++0x, it isn't hard to write them yourself: // for container with nested typedefs, non-const version template<class Cont> ...
5,897,500
5,897,561
Is this way of exceptions handling good practice?
Would you change anything in this code? class LocalPort { public: LocalPort(int portNumber) { innerPort = new ACMEPort(portNumber); } void Open() { try { innerPort->Open(); } catch (DeviceResponseException& e) { throw PortDeviceFailure(e); } catch (A...
It seems like you have badly designed exception classes. Why don't you simply add a member-function getMessage to your exception-hierarchy (preferably in the base-class all your exceptions derive from - std::exception provides the method what that returns an error message). This way, you could simply catch all exceptio...
5,897,602
5,904,963
Iterate to sequential position in boost::multi_index by size_t index?
I've just started to use boost multi_index and so far have a container that consits of a sequenced type and composite key unorderd hashes. What I want to do is access the sequenced container as if it were a std::vector or std::list. By this I mean by means of using size_t index. Here is my code below: // tags struct li...
Problem was solved by changing the function CVertexElementPtr CVertexFormat::GetElement(size_t index) const. The correct function is: CVertexElementPtr CVertexFormat::GetElement(size_t index) const { //sequenced_index. typedef ElementContainer::index<linear>::type element_by_linear; const element_by_linear&...
5,897,874
5,898,517
_nextafterf on Visual C++
I need to use the function _nextafterf on Visual C++ 32 bit to compute the distance in ULP of some results compare to reference functions. C99 provides nextafterf and nextafter for float and double but these functions are not supported by Visual C++. However, Visual C++ 2010 supports _nextafterf and nextafter from but...
You can always implement it... https://www.google.com/search?q=libm%2Fsrc%2Fs_nextafterf.c
5,898,107
5,910,210
D3D11: How to draw a simple pixel aligned line?
I tried to draw a line between two vertices with D3D11. I have some experiences in D3D9 and D3D11, but it seems to be a problem in D3D11 to draw a line, which starts in one given pixel and ends in an other. What I did: I added 0.5f to the pixel coordinates of each vertex to fit the texel-/pixel coordinate system (I re...
According to the rasterisation rules (link in the question above) I might have found a solution that should work: sort the vertices StartX < EndX and StartY < EndY add (0.5/0.5) to the start vertex (as i did before) to move the vertex to the center of the pixel add (1.0/1.0) to the end vertex to move the vertex to the...
5,898,531
5,898,600
use a string or stream?
I need to progressively build a string and am trying to find the best way to do it. The maximum it can grow to is about 10k and hence was planning to do something like this: const unsigned long long configSize = 10240; //Approximation void makeMyConfig() { std::string resp; std::string input; resp.reserve(conf...
Looks pretty great to me. You're pre-allocating the buffer, avoiding ongoing allocations and copies. You already have it implemented Don't optimize until you actually have a performance problem and can measure any performance changes. You might end up making it worse without realizing!
5,898,909
5,899,006
Container containing Objects and Containers
I'm trying to create a structure that will will be iterated across and the objects stored in it will be drawn in order from left to right. But there will be containers that are stored alongside of the drawable objects. These containers I consider them as drawing stacks where drawable objects are drawn on top of each ...
This is the classical Composite design pattern you need to apply: http://en.wikipedia.org/wiki/Composite_pattern
5,899,096
5,899,772
Function overloading error
I can't understand why the code behaves this way? #include <iostream> #include <boost/fusion/container/vector.hpp> #include <boost/fusion/include/vector.hpp> #include <boost/fusion/container/vector/vector_fwd.hpp> #include <boost/fusion/include/vector_fwd.hpp> #include <boost/fusion/container/generation/make_vector.hp...
This is roughly what I understand... boost::fusion::make_vector() from your usage of boost::fusion::make_vector(33,44) returns a boost::fusion::vector2<int, int> type and NOT a boost::fusion::vector<int, int, T2, T3,...> (variadic) type. boost::fusion::vectorN types can however convert itself to boost::fusion::vector<>...
5,899,149
5,899,254
openAL - choppy sound when playing the buffers
I have a voice chat which receives rtp packets (each packet contains 20ms of voice afaik), adds them to a buffer and plays it out. If I call alSourcePlay() directly after buffering a packet(I have 5 buffers and each buffer gets one packet, which are then re-used once the packets are played), the sound will be 'choppy'...
If you are, on average, getting less than 50 20ms packets per minute then there has to be pauses somewhere. If you store the packets for a while before playing them, then you can look for natural pauses ( silence ) and combine the gaps with the natural pauses so things sound more natural. The more you store the bette...