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,621,052 | 5,621,222 | time in C++ calculation | I have a text file with records in it. I need to decide if the time (which is part of the record structure) is between 2 times (stored in strings) that represents the lower and upper range.
In the file the time is represented in 145540123456, which means 14 is the hour, 55 - minutes, 40 - seconds, 123456 - micrseconds ... | The format you specify has the simple advantage that sorting these time-strings alpha-numerically will keep them in the correct order.
Therefore, using strcmp (simple C function if using null-terminated char * buffers), or the comparison operators for std::string can allow you to determine easily if a certain time stri... |
5,621,077 | 5,621,177 | Tests of hash collision on ASCII characters | I'm currently in the process of building a caching system for some of our back end systems, which means that I'll need a hash table of some sort, to represent cached entities. In this context, I was wondering if anyone knows about any tests showing different algorithms and the minimum ASCII string length necessary to p... | If you want a strong hash, I'd suggest something like the Jenkins Hash. This should be less likely to generate clashes. In terms of algorithms, what you're looking for is an avalanche test
Bob Jenkins' Site has a whole lot of handy information on this sort of thing.
As for the size of the hash table, I believe Knuth re... |
5,621,417 | 5,621,724 | Vector of object pointers containing vectors end up pointing to same object | I am storing multiple objects in a vector of pointers to these objects, like so, in C++:
vector<Host *> somevector;
I then initialize each item like this:
somevector.push_back(new Host(x));
The object takes an initializing argument.
As I read through data (strings) and end up with a list of object pointers, I add the... | From what I can see from the example code you have posted 'v' isn't a member object of Host. So calls to Host::add are simply pushing back to a globally available vector. Is this perhaps where your problem is?
|
5,621,810 | 5,624,015 | choose correct template specialization at run-time | I have
template <int i> struct a { static void f (); };
with specializations done at different places in the code. How can I call the correct a<i>::f for an i known only at runtime?
void f (int i) { a<i>::f (); } // won't compile
I don't want to list all possible values of i in a big switch.
Edit:
I thought of someth... | I am not sure that this is the best solution that you can get, as there might be better designs, at any rate you can use some metaprogramming to trigger the instantiation and registry of the functions:
// in a single cpp file
namespace {
template <unsigned int N>
int register_a() { // return artificially added
... |
5,621,944 | 5,622,002 | How to find out if a folder exists and how to create a folder? | I'm trying to create a folder if it doesn't exist. I'm using Windows and I am not interested on my code working in other platforms.
Never mind, I found the solution. I was just having a inclusion problem. The answer is:
#include <io.h> // For access().
#include <sys/types.h> // For stat().
#include <sys/stat.h> //... | The POSIX-compatible call is mkdir. It silently fails when the directory already exists.
If you are using the Windows API, then CreateDirectory is more appropriate.
|
5,622,053 | 5,622,073 | If there are virtual methods, is vtable is going to be created? | If I create a very simple class like this :
class A
{
public :
virtual void foo()
{
}
};
(no virtual destructor) is the compiler going to create vtable?
Or are modern compilers smart enough to recognize this case (which might be a bad copy and paste) and not add virtual table for such classes?
| The v-table is an implementation detail. Compilers that use v-tables for virtual functions will create one for this class. Those that don't, won't.
|
5,622,092 | 5,622,270 | Can anyone explain this paragraph of the current C++0x standard draft? | Can anyone explain this statement from ISO N3242 §3.2, 4th point
The added part of n3242 when compare to ISO Standard 2003 :
4 Exactly one definition of a class is required in a translation unit if the class is used in a way that requires theclass type to be complete.
A class type T must be complete if:
a non-static ... | Straight from Wikipedia:
In general, a translation unit shall contain no more than one
definition of any class type. In this
example, two definitions of the class
type C occur in the same translation
unit. This typically occurs if a
header file is included twice by the
same source file without appropriate
... |
5,622,433 | 5,622,502 | Terminate application AND call the destructors of local objects | I have some objects on the stack in main function:
int main(...)
{
CFoo foo;
CBar bar;
}
Also, I have a function, that keeps track of errors in my application:
void Err(std::string msg)
{
SomehowLogErrorMessage(msg);
exit(1);
}
Err function is definitely useful when I have to report a fatal error. I just ... | Not without exceptions or returning normally from Err all the way up the callstack. You need to unwind the stack.
|
5,622,574 | 5,622,848 | Nifty/Schwarz counter, standard compliant? | I had a discussion this morning with a colleague about static variable initialization order. He mentioned the Nifty/Schwarz counter and I'm (sort of) puzzled. I understand how it works, but I'm not sure if this is, technically speaking, standard compliant.
Suppose the 3 following files (the first two are copy-pasta'd... | I believe it's guaranteed to work. According to the standard ($3.6.2/1): "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place."
Since nifty_counter has static storage duration, it gets initialized before initializer is created, regardless of distribut... |
5,622,646 | 5,622,872 | using wininet in C++ | I Have a server that if I sent it "https://MyDomain/Dir1/Dir2/login.html?u=1234&t=5678" will respond with an xml document. Does anyone know how I can do this in wininet?
Here is what I have done so far:
std::string GetLoginData(void)
{
HINTERNET hInternet, hConnection, hRequest;
std::string retVal;
hIntern... | That's ERROR_WINHTTP_INVALID_SERVER_RESPONSE. Best guess you're making an HTTP request on an HTTPS port.
I don't know the API very well but it looks like you need to add INTERNET_FLAG_SECURE to your HttpOpenRequest call, and / or in the flags parameter of your InternetConnect call too:
INTERNET_FLAG_SECURE
Uses secu... |
5,622,728 | 5,623,431 | unordered_map with forbidden collisions | I want to implement a performance-optimized variant of unordered_map that works in several phases:
Initialization: Insert about 100 elements into std::map
Preparation: Do some magic, converting std::map to a variant of std::unordered_map
Work: Perform a large (unbounded) number of lookups; insertions/deletions are for... | Here is the "collision management" API:
size_type bucket_count() const;
size_type max_bucket_count() const;
size_type bucket_size(size_type n) const;
size_type bucket(const key_type& k) const;
local_iterator begin(size_type n);
local_iterator end(size_type n);
const_local_iterator begin(size_type n) const... |
5,622,757 | 5,622,791 | Weird characters appear in ostream in C++ | I have a program that should emulate a simple filesystem, I want to print the structure of directories, so I have overloaded the << operator, and called another function that goes through my structure in rectursion. It works, BUT there are some weird hex values before some of the lines in the output. Is there something... | os << printTree(os, x.m_Root,1);
What is this? printTree returns std::ostream &, and you're trying to output that (an ostream)?
That should be this:
printTree(os, x.m_Root,1);
That means, your operator<< should be implemented as:
std::ostream& operator<<( std::ostream & os, const CFileSystem & x)
{
os << "/" <... |
5,622,764 | 5,622,818 | std::unique_ptr usage | std::unique_ptr<int> p1(new int);
std::unique_ptr<int> p2(new int);
p2=p1;
It seems here that p1 is no longer "unique" since p2 refer to it also
It is legal c++ ?
Does unique_ptr have copy_semantics ?
If no, and if it has only move semantics, is p1 set to NULL after assign it to p2 ?
EDIT:
ok so the correct version... | std::unique_ptr is non-assignable and non-copyable. You need to use std::move();
so
p1 = std::move(p2);
Have a look here for more info.
|
5,622,833 | 5,623,123 | C++ how to pass method as a template argument | Suppose I have a class X:
class X {
// ...
size_t hash() const { return ...; }
};
I would like to create a std::tr1::unordered_map<X, int, HashFn> where I want to pass in
X::hash() as HashFn. I know I can declare my own functor object. I feel that
there should be a way to do this by directly passing a pointer ... | No; as you've shown it, you need a small utility struct:
#include <functional>
template<typename T, std::size_t (T::*HashFunc)() const = &T::hash>
struct hasher : std::unary_function<T, std::size_t>
{
std::size_t operator ()(T const& t) const
{
return (t.*HashFunc)();
}
};
Then you can create an u... |
5,622,847 | 5,624,215 | Help with this issue | Here is the problem:
The way the GUI system I'm using works is as follows:
A widget can listen to mouse events. The listeners can consume an event they are listening to and as a result, the widget they were listening to will not receive the event, even if it was intended for them, only the listener will have received ... | The usual way to deal with this is that the ListBox only consumes the event if it actually scrolls. If you place the mouse in the listbox and use the scrollwheel the listbox scrolls until it reaches its scroll limit. After that further moves of the wheel cause the scrollpane to scroll.
Obviously there are variants on t... |
5,622,867 | 5,625,082 | catching an exception in a loaded shared library | Is catching an exception thrown in a loaded shared library portable?
I've noticed that it works with dlfcn.h, but I wonder if this behaviour is in general expected, for example when using LoadLibrary on windows instead?
Example code:
main.cpp:
#include <stdexcept>
#include <cstdio>
#include <dlfcn.h>
typedef void(*dum... | Yes, that should work fine under Windows.
|
5,623,218 | 5,623,434 | Why use QVector(Qt) instead of std::vector | I'm very new to C++ and Qt, but I'm very good at C#/Java.
The point is I like cross-platform, but I'm confuse with Qt. Isn't std::vector already cross-platform, doesn't Qt provide an equivalent to a non-crossplatform thing?
Also how are File and QFile different?
A link would be nice, thanks :)
| This article loooks good. It compares Qt Template Library with Standard Template Library:
QTL vs STL
Hope, you'll find it interesting seeing all the differences listed there in the article.
EDIT:
Here is what I find interesting:
My opinion is that the biggest
advantage of the QTL is that it has
the same implemen... |
5,623,268 | 5,623,512 | Convert custom API to Ruby on Rails ActiveResource | I have a set of embedded devices that run software written in c++. The API to communicate the devices is simple: get/set/acquire parameters and signals.
I'd like to implement common web application to access all of the devices from a single point.
My idea was to add XML RPC interface to devices and then use ActiveResou... | If you're already considering XML RPC I'm assuming you have some sort of web server running on the device. I would probably choose a RESTful web service over XML RPC. If designed carefully you could have corresponding services on your Rails app.
For example:
http://somedevice/signals.json - gets all signals
http://you... |
5,623,287 | 5,623,388 | Destructor and python | I have some Base class in c++. I export it into python using boost::python. But what about virtual destructor? Any base class should have virtual destructor to avoid wrong memory freeing, right? I forget about that and wrote Base without destructor. Everything works, but with a lot of memory leaks.
Now I've added:
clas... | The missing symbol error is probably caused by you failing to define the destructor (you're declaring the destructor, but it's unclear from your question whether you're defining it):
class Base
{
public:
virtual ~Base() {}
// Other members...
};
(note the added curly braces)
As to your question about wh... |
5,623,555 | 5,623,579 | Multithreaded code: vector<bool> iterators incompatible | The following code is intended to return the smallest non-negative integer that is not already in use. It is called from multiple threads. If style looks a bit odd, it's because this class is intended to live in a header-only library.
class Unique
{
public:
static unsigned int getIndex()
{
boost::uniq... | The get function certainly isn't thread-safe unless you guarantee that it's called once before any threads are created. And since you use the get call to get the mutex to protect the rest of the code, you could definitely get some unexpected results there.
std::vector<bool> is explicitly specialized to use one bit per ... |
5,623,791 | 5,624,339 | c++ network serialization | I'm looking for a solution for serializing of c++ packets to a network stream.
I have seen many posts here refering people to:
ACE
Google Protocol Buffers
Boost::Serialization
Qt ::QDataStream
My Requirements/ Constraints:
The solution must be unaware of LitteEndian/BigEndian. Machine Architecture x86/x64 and plat... | If you find that Google Protocol Buffers are to heavy (I can agree with that because compiled library could take more than 1 MB), you could try the lite version of protobuf which is a few times smaller.
It can be enabled in *.proto files by inserting the following line
option optimize_for = LITE_RUNTIME;
But if you ne... |
5,623,866 | 5,623,979 | How to set the text in a TextBox control from native code? | Is it possible to manipulate .net controls from native code? Particularly, I'd like to set the text of a TextBox from some native code. I want it done this way to keep the business logic separated from the user interface, but it is precisely the native code which only knows how to appropriately format the data (some by... | The "native" way of setting the text on a textbox is to send the textbox the WM_SETTEXT message:
// handle is initialized from TextBox::Handle
PostMessage(handle, WM_SETTEXT, 0, _T("Some text"));
Read up on PostMessage and SendMessage, too. Depending on how you allocate and build up the text, you may need to use SendM... |
5,623,931 | 5,624,042 | template code returntype overload not compiling. whats wrong | I am trying the following code to overload a simple function to work for multiple types. However, it fails to compile. Can some one please tell me whats wrong and how to fix this?
typedef struct str1_type
{
int f1;
int f2;
} STR1;
typedef struct str2_type
{
char f1[100];
char f2[100];
}STR2;
template ... | template <typename T1, typename T2>
T2 getFieldOffset(const T1& t, int i);
Only template argument T1 can be deduced from the arguments, so you have to explicitly provide the template argument T2 in the template argument list when you make the call.
However, if you use the function template as written, you have to ... |
5,624,007 | 5,624,997 | CMake set_target_properties and include_directories | My question is largely related to this (unanswered) question on the CMake mailing list.
Essentially I want to know about the behaviour of include_directories behind the scenes of the Visual Studio 2010 generator; do the directories from previous calls to include_directories get overwritten when you do this:
set_target_... | I haven't seen your CMakeLists.txt, but is the ordering of the include paths good? I think the order of the include paths is not defined if you do it that way. See: /I compiler option, set_target_properties and include_directories documentation.
|
5,624,020 | 8,055,427 | DeferWindowPos weird behaviour | This happens with all ActiveX controls. If I reposition an ActiveX control with DeferWindowPos
HDWP hdwp = BeginDeferWindowPos(1);
DeferWindowPos(hdwp, m_pActiveX->GetSafeHwnd(), NULL, left, top, width, height, SWP_NOZORDER);
EndDeferWindowPos(hdwp);
it goes there but then moves/resizes to its old rectangle once you c... | You never got an appropriate answer. I'll try to help out a bit here.
The issue is that MFC hides a lot of the trickiness with hosting an ActiveX control within it's framework. Specifically, if you step into the MoveWindow call, it is not simply a wrapper around the Win32 MoveWindow function. It calls into the OLE Cont... |
5,624,245 | 5,785,815 | Library to generate a CHM file | I have been looking for a library that will expose functionality to allow me to generate CHM files. As far as I can tell, that does not exist and I will have to rely on CHMBuilder (in SandCastle) but I thought I would ask before going that route.
| Microsoft HTML Help SDK
http://msdn.microsoft.com/en-us/library/ms670169(VS.85).aspx
|
5,624,397 | 5,624,692 | How do I run a class from another project? | I am fairly new to c++ and I am trying to figure out the best way to run a class from another project in my solution.
Lets say I have 2 projects in my solution: proj_A and proj_B.
Now I would like to create an instance of a class in proj_B from inside proj_A. I have tried including the headers and source files from pro... | In C++, you have two options for splitting your application into modules. You can you use Libraries, which are linked directly into your executable, or you can use DLLs, which you are familiar with from C#.
It sounds like you are using DLLs. If that is the case, you need to export your classes from the DLL (proj_B) tha... |
5,624,489 | 5,624,552 | I am trying to create a lexicon using an input file in C++ | I have a file.txt I want to create a function in C++ that can read the words in that file, and print each word and how many times they occur into a file2.txt
I am doing some research I know i can use the parser and writer, and also the map class, any help please?
bool Parser::hasMoreTokens() {
if(source.peek()!=NULL)... | Is this home work? Look online for std::map, std:string, std::ifstream and std::ofstream.
|
5,624,658 | 5,624,698 | Namespace Scope Question | I have a quick question about namespace scope:
I have two namespaces, A and B, where B is nested inside A.
I declare some typedefs inside A.
I declare a class inside B ( which is inside A )
To access the typedefs (declared in A), from inside B, do I need to do "using namespace A;"
ie:
B.hpp:
using namespace A;
name... |
To access the typedefs (declared in A), from inside B, do I need to do "using namespace A;"
No.
However if there is a typedef or some other symbol with same name as your typedef, defined in the namespace B, then you need to write this:
A::some_type a;
Lets do a simple experiment to understand this.
Consider this ... |
5,624,788 | 5,624,828 | C++ Boolean Variables Changing | I have a C++ class; this class is as follows:
First, the header:
class PageTableEntry {
public:
PageTableEntry(bool modified = true);
virtual ~PageTableEntry();
bool modified();
void setModified(bool modified);
private:
PageTableEntry(PageTableEntry &existing);
PageTableEntry &operator=(PageT... | Either your debugger isn't reporting the value correctly (not unheard of, and even expected in optimized builds) or you have memory corruption elsewhere in your program. The code you've shown is more-or-less fine and should behave as you expect.
EDIT corresponding to your 'UPDATE2':
The problem is in this line:
return... |
5,625,131 | 5,625,244 | Generic list deleting non pointers | I have a generic list with a template
template<class t>
class GenericList {
//the data is storeed in a chained list, this is not really important.
struct c_list { t data; c_list* next; ...constructor... };
public:
bool isDelete;
GenericList() : isDelete(false) {...}
void add(t d) {
c_list*... | Without changing much your code, I would solve your problem as
template<class t>
class GenericList
{
//same as before
//add this function template
template<typename T>
void delete_if_pointer(T & item) {} //do nothing: item is not pointer
template<typename T>
void delete_if_pointer(T* item) { delete ... |
5,625,193 | 5,625,353 | Is there an implicit template<typename T>operator<<(const ostream&,T)? | I have a class I've written, meant to represent vectors (in the linear algebra sense). I just started writing it so it isn't finished, but i've pasted it and some test code here
I'm not really sure what's going on. I was going to write an overloaded operator<< for testing in a second, so I went ahead and put it in my m... | First of all, vect3f v(); declares a function (named v), taking no parameters and returning vect3f. And the operator<< that is being called is called for this function pointer (which is implicitly converted to bool, because there's no overload for function pointers).
vect3f v; is the correct way of creating default-con... |
5,625,222 | 5,625,285 | double pointer reference in C++ | This may a stupid question, but I'm gonna ask it anyway:
Suppose you have a pointer: Object* pointer which points at a dynamically allocated object.
class PointClass
{
Array<Object*> m_array1;
Array<Object*> m_array2;
void Delete1()
{
for (int i = 0; i < m_array1.Length; i++)
{
delete m_array1[... | Well the simplest way would be to use a reference-counting pointer, like those available in boost::smart_ptrs.
Otherwise, you need to assign owners to the pointers - you need to decide which class will be responsible for allocating/deleting that particular pointer. If for some reason you decide that should be this cla... |
5,625,268 | 5,625,414 | The error representation and handling | I am designing a cross-platform application protection library to communicate with a dongle. The dongle is able to send and receive blocks of data, to create and delete directories and files inside the dongle's internal file system, etc. To put it simple, the main dongle object has methods to implement all of these fun... | Of the options you have presented, the best is to use return codes. Typically a return code of zero indicated success, and each other return code has its own positive integral value. 30 error conditions isn't many. As you've said, you'll have to write code to translate these codes to something human-readable, but yo... |
5,625,431 | 5,625,446 | Efficient way to compute p^q (exponentiation), where q is an integer | What is an efficient way to compute pq, where q is an integer?
| Exponentiation by squaring uses only O(lg q) multiplications.
template <typename T>
T expt(T p, unsigned q)
{
T r(1);
while (q != 0) {
if (q % 2 == 1) { // q is odd
r *= p;
q--;
}
p *= p;
q /= 2;
}
return r;
}
This should work on any monoid (... |
5,625,600 | 5,625,782 | What is the meaning of "... ..." token? i.e. double ellipsis operator on parameter pack | While browsing through gcc's current implementation of new C++11 headers, I stumbled upon "......" token. You can check, that the following code compiles fine [via godbolt.org].
template <typename T>
struct X
{ /* ... */ };
template <typename T, typename ... U>
struct X<T(U......)> // this line is the important one
{ ... | Every instance of that oddity is paired with a case of a regular single ellipsis.
template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes...)>
{ typedef _Res result_type; };
template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes..... |
5,625,677 | 5,625,703 | c++ default parameters |
Possible Duplicate:
Nonstatic member as a default argument of a nonstatic member function
Ok. So I'm having problems understanding how to accomplish a seemingly simple task... Here is what I want to accomplish:
#include <iostream>
using namespace std;
class A{
private:
int _x;
public:
A(int x){
_x ... | You can't do that.
You can however have an overload for test that takes no parameters.
void test(){
test(_x);
}
|
5,625,790 | 5,625,834 | Template assignment operator overloading mystery | I have a simple struct Wrapper, distinguished by two templated assignment operator overloads:
template<typename T>
struct Wrapper {
Wrapper() {}
template <typename U>
Wrapper &operator=(const Wrapper<U> &rhs) {
cout << "1" << endl;
return *this;
}
template <typename U>
Wrapper &operator=(Wrapper<U... |
Why does assigning d to c not use the const overloaded assignment operator provided?
The implicitly-declared copy assignment operator, which is declared as follows, is still generated:
Wrapper& operator=(const Wrapper&);
An operator template does not suppress generation of the implicitly-declared copy assignment ope... |
5,625,842 | 5,625,923 | Cost of memory [de]allocation and potential compiler optimizations (c++) | Is the cost of memory [de]allocation specifically defined? If the cost depends upon the specific compiler being used, is there a general way memory [de]allocation is implemented such that I can reasonably assume the cost?
Is the compiler able to optimize the following code such that the call to 'new' is only done once?... | The compiler is almost certainly not able to perform this optimization. At the lowest level, storage allocation boils down to calls to library functions such as malloc (and, one layer deeper, to OS APIs). For the compiler it's not safe to assume that individual malloc/free pairs can be left out and their storage reused... |
5,625,870 | 5,628,591 | How to launch a QProcess with root rights? | I need to launch gphoto2 from a Qt program. I do this:
QString gphotoProgram = "/usr/bin/gphoto2";
QStringList gphotoArguments;
gphotoArguments << "--capture-image";
QProcess *gphotoProcess = new QProcess(this);
gphotoProcess->start(gphotoProgram, gphotoArguments);
but it never enters the Running state this way, as gp... | I would strongly recommend finding a way to allow gphoto2 to be run with the logged in user's permissions. Perhaps this article has some helpful info.
|
5,625,884 | 6,823,122 | Conversion of std::wstring to QString throws linker error | Hi I need to convert a std::wstring to QString and I tried the most obvious way of
std::wstring wideString;
QString qtString = QString::fromStdWString(wideString);
I got the error:
Error 2 error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QString __cdecl QString::fromStdWString(... | Edit your Visual Studio project settings and under C/C++ -> Language set the option Treat wchar_t was Built-in Type to No.
|
5,626,090 | 5,626,130 | How to compile a program to make it capable to use >4GB memory on 32-bit Linux? | The whole code is written in C, C++, and Fortran.
Is it possible to make it to use more than 4GB memory.
Now it is always crashed when it reaches 3GB memory.
If it is possible, how to set up the compiling options (or configure flags)?
We can use gcc, g++, ...or intel compilers
our OS: Fedora 12 x32
cat /proc/cpuinfo
f... | Unfortunately you are hitting the limit that
R> 2^32
[1] 4294967296
which is your 4 gb limit. So you simply cannot index beyond for a single application, no matter what the OS.
This is one of the reasons many of us switched to 64 bit versions of our OSs. Linux has supported this since the late 1990s. Just switch to... |
5,626,147 | 5,627,659 | (MFC) CListBox -> Edit Item in List? | I'm currently using the CListBox Control for MFC. Is it possible to retain the data inside the List Item but edit it, without deleting then re-adding it?
Thanks!
| You can do this by extending CListBox. Check out this code project article.
|
5,626,429 | 5,626,465 | Assert and unused local variable warning in GCC don't mix well? | I have a problem with the unused local variable warning in GCC.
Often I have code that looks like this:
bool success = foo();
assert(success);
This is fine for debug builds. In release however, the assert compiles to nothing, and GCC gives me a warning.
What is the best way to work around this? Wrapping the bool succe... | I would probably define a macro specific to this scenario
#ifndef NDEBUG
#define verify(expression) assert(expression)
#else
#define verify(expression) expression
#endif
I prefer this approach over using a local variable because it doesn't pollute the method with values that only conditionally exist.
In general I fi... |
5,626,521 | 5,631,976 | C++ where I'll need local extension or foreign method? | I'm not familiar with C++ enough to know where those 2 very similar refactorings (introduce local extension and introduce foreign method) will be needed. I know cases that forces to use those, but I can't figure sample classes that will need this "trick". I'm making C++ refactoring tutorial, to help new developers, but... | "Foreign" methods are methods that operate on, but aren't members of a class. In Java, that just means (static) methods of other classes that take the first class as an argument. In C++, you'll need to be aware of free functions. Unlike Java , in C++ methods can exist outside classes. int main() is the most famous one.... |
5,626,661 | 5,626,734 | Transforming Lisp to C++ | I am working on a toy language that compiles to C++ based on lisp (very small subset of scheme), I am trying to figure out how to represent let expression,
(let ((var 10)
(test 12))
(+ 1 1)
var)
At first I thought execute all exprs then return the last one but returning will kill my ability to nest let expre... | One way to expand let is to treat it as a lambda:
((lambda (var test) (+ 1 1) var) 10 12)
Then, transform this to a function and a corresponding call in C++:
int lambda_1(int var, int test) {
1 + 1;
return var;
}
lambda_1(10, 12);
So in a larger context:
(display (let ((var 10)
(test 12))
... |
5,626,787 | 5,626,890 | Calling C++ functions from Java | I am developing a Java application in which I need to call some C++ functions (from Google Talk library libjingle) . The objective is to run it all on Google App Engine (which only supports Python or Java).
How can I do this?
| You need to define native methods in your java code for whatever you want to be implemented in C++ and directly access your native code. Then you run javah on your code and it will generate the C header files for you and you'll need to provide C++ implementations.
The native methods you can call from your Java code lik... |
5,626,843 | 5,626,878 | template syntax for containers | This is what I have now:
template<template<typename T> class container, typename T>
inline bool contains( const container<T> &cont, const T &element )
{
if( cont.size() == 0 )
return false;
return( std::find(cont.begin(), cont.end(), element) != cont.end() );
}
An I'd like to call it like so:
std::vec... | STL containers take two arguments, one for the contained type and another for the allocator that describes how to obtain memory.
Try this:
template<template<typename T, typename Alloc> class container, typename T, typename Alloc>
inline bool contains( const container<T, Alloc > &cont, const T &element )
However, this ... |
5,626,854 | 5,627,048 | c++ select async programming | Is there a way to have 'select' waiting for reads and writes, while also being able to add new file descriptors? Preferrably on one thread?
| Now that I know what your scenario is (a socket-based server that may want to accept new incoming connections), did you know that you can append the file-descriptor for your listening socket to the list for select? See e.g. http://www.lowtek.com/sockets/select.html.
(Paraphrased example:)
fd_set socks;
FD_ZERO(&socks... |
5,626,914 | 5,627,271 | boost regex without possessive quantifiers | Is there a similar way to write this regex without using possessive quantifiers (ie ++ and *+ ?
boost::regex testing123("\"value\":\"((?:[^\\\"\\\\]++|\\\\.)*+)\"");
I think this is comparable(?):
boost::regex testing123("\"value\":\"(?>(?:(?>[^\\\"\\\\]+)|\\\\.)*)\"");
Update: It's trying to match quoted text--... | Possessive quantifiers are just syntactic sugar for atomic grouping, i.e. (ab)*+ is equivalent to (?>(ab)*). Using this, you can rewrite your whole expression without using possessive quantifiers.
|
5,627,030 | 5,627,278 | Why was std::pow(double, int) removed from C++11? | While looking into Efficient way to compute p^q (exponentiation), where q is an integer and reviewing the C++98 and C++11 standards I noticed that apparently the std::pow(double, int) overload was removed in C++11.
In C++98 26.5/6 it has the double pow(double, int); signature.
In C++11 26.8 all I could find was overloa... | double pow(double, int);
hasn't been removed from the spec. It has simply been reworded. It now lives in [c.math]/p11. How it is computed is an implementation detail. The only C++03 signature that has changed is:
float pow(float, int);
This now returns double:
double pow(float, int);
And this change was done for... |
5,627,170 | 5,628,391 | Qt: How to repeat sound x times with QtSound | I'm not sure I understand correctly how QSound.setLoop function should work.
I want to play some wave file 3 times. Tried the following code but it only plays it once.
QSound soundObj(filePath);
soundObj.setLoops(3);
soundObj.play();
Help :-)
Edit:
The full version of this code looks like this
void Alarms::playSound(Q... | soundObj object is destroyed to quickly.
Has to be allocated dynamically.
|
5,627,175 | 5,627,248 | In ICU UnicodeString what is the difference between countChar32() and length()? | From the docs;
The length is the number of UChar code units are in the UnicodeString. If you want the number of code points, please use countChar32().
and
Count Unicode code points in the length UChar code units of the string.
A code point may occupy either one or two UChar code units. Counting code points involves re... | The two values will only differ if you use characters out of the Base Multilingual Plane (BMP). These characters are represented in UTF-16 as surrogate pairs. Two 16-bit characters make up one logical character. If you use any of these, each pair counts as one 32-bit character but two elements of length.
|
5,627,215 | 5,627,541 | How to Make a vector of template structs |
Possible Duplicate:
c++ template problem
Hi Everyone:
I'm stuck trying to do the following:
template <typename T>
struct test {
T* value;
test(int num_of_elements) { value = new T[num_of_elements] };
}
std::vector<test *> fields_;
i.e. I want to make a vector of pointers to a set of test structs with dif... | You could use something like Boost::any. An example from the documentation illustrates your use case almost exactly (at least, as you've described so far):
struct property
{
property();
property(const std::string &, const boost::any &);
std::string name;
boost::any value;
};
typedef std::list<propert... |
5,627,384 | 5,627,428 | Visual Studio Output Window Error - C++ | Using Visual Studio 2008, I keep seeing this error in the output window:
_CrtDbgReport: String too long or IO Error
I have a lot of TRACE macros scattered throughout my code used to dump information about error conditions: file path, line number, error, etc. I need to trace down the source of this error because it m... | Ultimately I'll bet the problem is passing an object string instead of string.c_str() to the Macro. TRACE uses variadic argument passing to, ultimately, something that calls something in the vsnprintf() family for %s processing. It cannot deal with objects because C can not.
The maximum length for OutputDebugString... |
5,627,843 | 5,627,908 | insertions into c++ map STL container is failing | Please see the following code to understand my question better.
class compareByValue {
public:
bool operator()(const string* s1, const string* s2) ... | Your comparison operator isn't right. As long as you can assume that no nulls are added, you can throw if you detect any:
bool operator()(const string* s1, const string* s2) const
{
if (... |
5,627,917 | 5,629,199 | use a custom directory for build in eclipse cdt c++ makefile project | hi i have a c++ makefile project in eclipse helios cdt.
my external makefile make the binary output files in projectdirectory/bin
if i build project eclipse runs the makefile and there are no compilation problem but if i run it.. eclipse doesn't find the files..
some advice?
| If you goto the "Run" menu and select "Debug Configurations" or "Run Configurations" (whichever concerns you), select "C/C++ Application", and then press the 'New' icon which is a little white page with a yellow plus icon in the top right.
On the right hand side you should see a text field "C/C++ Application:" with the... |
5,628,057 | 5,628,589 | Solving floating-point rounding issues C++ | I develop a scientific application (simulation of chromosomes moving in a cell nucleus). The chromosomes are divided in small fragments that rotate around a random axis using 4x4 rotation matrices.
The problem is that the simulation performs hundreds of billions of rotations, therefore the floating-point rounding error... | You need to find some constraint for your system and work to keep that within some reasonable bounds. I've done a bunch of molecular collision simulations and in those systems the total energy is conserved, so every step I double check the total energy of the system and if it varies by some threshold, then I know that... |
5,628,059 | 5,628,139 | C++ STL allocator vs operator new | According to C++ Primer 4th edition, page 755, there is a note saying:
Modern C++ programs ordinarily ought to use the allocator class
to allocate memory. It is safer and more flexible.
I don't quite understand this statement.
So far all the materials I read teach using new to allocate memory in C++.
An example of ... | For general programming, yes you should use new and delete.
However, if you are writing a library, you should not!
I don't have your textbook, but I imagine it is discussing allocators in the context of writing library code.
Users of a library may want control over exactly what gets allocated from where. If all of the ... |
5,628,068 | 5,628,644 | Starting with OpenGL and C++, proper path? | I need some specific and some general advice. I'm a fairly proficient Java programmer and a very experienced web programmer, but I would like to get into software development and I've been tackling C++. I have a great idea for a game I'd like to do, and I realize it will be a huge undertaking--but I'm looking at it m... | Assuming you're learning OpenGL as a learning experience, I would recommend you this:
Use GLEW, no argument. Just do it, everyone does
Code only to the core profile. By default, OpenGL accepts old command (eg fixed function pipeline) that will later disappear, and you don't want to waste your time on that. Specifically... |
5,628,121 | 5,628,222 | Is it possible to emulate template<auto X>? | Is it somehow possible? I want that to enable compile-time passing of arguments. Suppose it's only for user convenience, as one could always type out the real type with template<class T, T X>, but for some types, i.e. pointer-to-member-functions, it's pretty tedious, even with decltype as a shortcut. Consider the follo... | After your update: no. There is no such functionality in C++. The closest is macros:
#define AUTO_ARG(x) decltype(x), x
f.bar<AUTO_ARG(5)>();
f.bar<AUTO_ARG(&Baz::bang)>();
Sounds like you want a generator:
template <typename T>
struct foo
{
foo(const T&) {} // do whatever
};
template <typename T>
foo<T> make_f... |
5,628,240 | 5,628,263 | Create a array of structs but define the size later? | I'm trying to create a array of structs, but define it's size later, like so:
struct xy{
int x;
int y;
};
int main(){
xy pos;
int size = 10;
pos = new xy[size];
pos[0].x = 5;
}
But I can't get it to work no matter what I try. Also I don't want to use a vector for this, so please don't say I should.
| new returns a pointer:
int main(){
xy* pos;
int size = 10;
pos = new xy[size];
pos[0].x = 5;
}
|
5,628,460 | 5,628,537 | getline with delimiter storing an empty character | I am trying to input a delimited text file with getline but when I debug it it shows me that there is an empty character at the beginning of the variable.
This is only happening with my tID variable which happens to be the first on each line. When I debug it shows this as the character array:
[0] = ''
[1] = '2'
[2] = ... | Because ; is the delimiter for getline, it doesn't consume the newline. Add a getline call without an explicitly specified delimiter, or ignore( numeric_limits<streamsize>::max(), '\n' ) to the end of the loop. This has the "bonus" of ignoring data after the last semicolon.
Bonus diagnostic code: http://ideone.com/u9om... |
5,628,484 | 5,628,523 | Unexpected behavior from unsigned_int64; | unsigned__int64 difference;
difference=(64*33554432);
printf ("size %I64u \n", difference);
difference=(63*33554432);
printf ("size %I64u \n", difference);
the first # is ridiculously large. The second number is the correct answer. How does changing it from 62 to 63 cause such a change?
First value is 18446744071562... | Unless qualified otherwise, integer literals are of type int. I would assume that on the platform you're on, an int is 32-bit. So the calculation (64*33554432) overflows and becomes negative. You then cast this to a unsigned __int64, so this now gets flipped back to a very very large positive integer.
Voila:
int mai... |
5,628,518 | 5,628,540 | C++ or Java for android? | I am thinking about picking up android development in my free time. I see that development is possible in Java and C++ but the latter is limited.
I am much more comfortable with C++.
So my question is what limitations exist with C++ on Android? Will I be able to develop full apps with it, or will I eventually have ... | Pick the right tool for the job. The right tool for android is java, and occasionally c++ if it's really needed. Android runs on several different CPUs, and you'd be required to deal with fun stuff like compiling for platforms that you can't really test on - at least if you want to make apps for anyone but yourself.
|
5,628,620 | 5,628,654 | How to start a process using a .dll file in VC++ 2010 | I am trying to learn how to use DLL file in C++. According to my research, this should open notepad when I use the DisplayNotepad() in my code. I am trying to compile it but I am getting compiler errors and I know for a fact windows.h defines ShellExecute but it says identifier not found. here is my code:
#include "std... | The declaration of ShellExecute is found in Shellapi.h, not windows.h.
|
5,628,815 | 5,628,853 | Converting a string representing binary to a string representing equivalent hex | So i have a string x = "10101" and i need to put into any string y the hex value of the binary in x. So if x="10101" then y="0x15"
| I don't want to provide you with the complete answer.
That said, the basic idea should be fill the start of the string with up to 3 zero's so that you can split the string into substrings with a length of 4.
This can then easily be turned into hex by a variety of ways, the easiest being just using a switch case statem... |
5,628,929 | 5,629,146 | problem blending properly in openGL | I'm trying to draw a 2d character sprite on top of a 2d tilemap, but when I draw the character he's got odd stuff behind him. This isn't in the sprite, so I think its the blending.
This is how my openGL is set up:
void InitGL(int Width, int Height) // We call this right after our OpenGL window is created.
{
... | Does your sprite have premultiplied alpha? Your glBlendFunc setup is a little unusual, if you don't have premultiplied alpha it could definitely be causing the issue.
|
5,629,105 | 5,629,551 | Relative coordinates with slider widget containing thumb widget | My slider had a child button widget. I have recently changed my gui to send the mouse coordinates as relative to the widget, so if the widget is at 50,50 and the mouse is at 50,50, it will now report as 0,0.
This has created some problems for my slider. When I would drag around the button it would position to value.
Th... | Since this is a custom GUI, I'm going to make some assumptions and restate your question to make sure I'm answering your question.
You have a slider widget that contains a thumb widget. The user can click and drag the thumb to reposition it. Your GUI sends mouse notifications to your widgets in local relative space r... |
5,629,383 | 5,629,648 | CreateProcess running as user: "NT AUTHORITY/Network Service" without knowing the credentials? | I have a windows service running as local system. I would like the service to spawn a process as "NT AUTHORITY/Network Service". However, I do not have the credentials for this account. How can I spawn the process as the "Network Service" user, using c++.
| I'm not in front of my win32 dev box, so I can't confirm, but I'll offer two possible approaches:
Iterate through the list of processes
Call OpenProcess() to get the handle of an existing NETWORK SERVICE process
Call OpenProcessToken() using that handle to get the security token from his process
Call CreateProcessAsUs... |
5,629,482 | 5,629,494 | Why this code compiles in VS? ("extra" comma) | The line below is inside a for loop. If the method fails, it needs to break. CATEGORY_1 is an enum. I added this enum as a new parameter to AddToList method with a default value. If you see closely below, I actually made the mistake of putting the comma and the enum outside the parameter list of the function. This comp... | In C++, the comma isn't just a separator; it can also be an operator. That comma is an operator. The comma operator evaluates the first expression, discards the result, then evaluates the second expression and yields its result.
!AddToList(obj1, (unsigned int) Val) , CATEGORY_1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ... |
5,629,543 | 5,629,564 | Why has my program stopped working? Are my pointers wrong? | I'm working on a program which reads some data from a file formatted like so:
21
285 270 272 126 160 103 1
31
198 180 163 89 94 47 1
32
240 230 208 179 163 104 1
33
15 13 12 14 15 15 0
34
63 61 62 24 23 20 2
I'm trying to read the first number into one pointer array and the other 7 numbers into a parallel two dimens... | This code doesn't need pointers at all; why would you think it does? Just change the types of precinct_num and num_votes and stop dereferencing them and I think (at a glance) that it should be fine.
#include <iostream>
#include <fstream>
using namespace std;
//bool openFileIn(fstream &, char *);
int main()
{
cons... |
5,629,560 | 5,629,581 | creating a database class using the multimap class in c++ | I'm working with C++ for a project. I need to store a pair (string,integer) and access them based on the string. The multimap class seems perfect for that. I am trying to make my own class, database, which will include methods to find the average and count of all the integers associated with a particular string. Howeve... | You declare data as a multimap<string,double>* but then you try to assign to data a multimap<string,int>* -- reconcile these.
As an aside, database data(); is not what you want -- it is in fact a declaration of a nullary function named data with a return type of database; use database data; instead.
|
5,629,592 | 5,629,623 | Resource leak during object creation | I have the following code for creation of a node inside a graph. I'm getting resource leak error when I run a static checking tool (coverity). I would appreciate if you can point out how to improve the code:
class node {
public :
explicit node(std::string& name) : m_name(name) { }
void setlevel(int... | I am not familiar with coverity or the exact rules that it uses, but it seems that you will have a memory leak if the name of the node is already in the map. That is, if the body of your if statement is not executed, then you loose the pointer to the memory that you just allocated. Perhaps you wanted something like:
if... |
5,629,613 | 5,630,191 | Hide Cursor in Client Rectangle but not on Title Bar | I am trying to hide the cursor in the client area of my window (DirectX application) but would like the default behavior in the title bar. I've tried several things but I didn't find any way to do this. Does anyone have an idea how to achieve this?
| Add something like this to your wndproc:
case WM_SETCURSOR:
{
WORD ht = LOWORD(lparam);
static bool hiddencursor = false;
if (HTCLIENT==ht && !hiddencursor)
{
hiddencursor = true;
ShowCursor(false);
}
else if (HTCLIENT!=ht && hiddencursor)
{
hiddencursor = false;
... |
5,630,114 | 5,630,156 | How to read UTF-8 text from file using Qt? | I have some problems with reading UTF-8 encoded text from file. My version reads only ASCII characters.
#include <QtCore>
int main()
{
QFile file("s.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return -1;
}
QTextStream in(&file);
while(!in.atEnd())
{
QSt... | See QTextStream::setCodec():
in.setCodec("UTF-8");
|
5,630,149 | 5,630,369 | How to convert a C++ Struct with Union into C#? | Guys I am having difficulties on retrieving struct member values after calling a function in the DLL. I tried to convert the C++ codes into C# but I’m not sure if it is correct or not. Please help me understand my mistakes here (if there is) and how to correct.
My problem here is I can’t correctly retrieved the values ... | Akash is right, have a look here: http://social.msdn.microsoft.com/Forums/en/csharplanguage/thread/60150e7b-665a-49a2-8e2e-2097986142f3
Another option is create two structs and use an appropriate cast once you know which type it is.
hth
Mario
|
5,630,363 | 5,630,404 | Find two elements in an array that sum to k |
Possible Duplicate:
Given two arrays a and b .Find all pairs of elements (a1,b1) such that a1 belongs to Array A and b1 belongs to Array B whose sum a1+b1 = k .
Given : An unsorted array A of integers
Input : An integer k
Output : All the two element set with sum of elements in each set equal to k in O(n).
Example:... | Make a constant-time lookup table (hash) so you can see if a particular integer is included in your array (O(n)). Then, for each element in the array, see if k-A[i] is included. This takes constant time for each element, so a total of O(n) time. This assumes the elements are distinct; it is not difficult to make it ... |
5,630,440 | 5,630,449 | sqrt() pow() fabs() do not work | i am trying to compile my program where i am using the functions like sqrt pow and fabs. I do have math.h included but for some reason i get errors like:
error C2668: 'fabs' : ambiguous call to overloaded function
same for the rest of the functions
i have this included:
#include "stdafx.h"
#include "math.h... | It's because those functions are overloaded for several types: float, double and long double. Thus, if you pass in an integer, the compiler doesn't which one to choose. An easy fix is to simply pass a double (or multiply what you pass in by 1.0), this should fix the problem.
int value = rand();
int result1 ... |
5,630,881 | 5,631,046 | Extension of STL container through composition or free functions? | Say I need a new type in my application, that consists of a std::vector<int> extended by a single function. The straightforward way would be composition (due to limitations in inheritance of STL containers):
class A {
public:
A(std::vector<int> & vec) : vec_(vec) {}
int hash();
private:
... | Hashing is an algorithm not a type, and probably shouldn't be restricted to data in any particular container type either. If you want to provide hashing, it probably makes the most sense to create a functor that computes a hash one element (int, as you've written things above) at a time, then use std::accumulate or std... |
5,630,994 | 5,632,217 | Merge-sorting a linked list | I'm required to sort a Linked list using merge sort. I've put together this code, but I'm running into a weird error.
My linked list is populated by random numbers. However, after sorting, it only displays numbers that are larger than the first element of the linked list, in sorted order.
Here is some of my code:
node*... | I have tried your code and it works perfectly.
Have you looked at the right list in the end?
Your new head of the list is not the previous head, but the return value of
the Merge function.
printList(myList);
node* sortedList = MergeSort(myList);
printList(sortedList); //whole list sorted
printList(myList); //list (of ... |
5,631,009 | 5,660,058 | Return SAFEARRAY of custom interface types to VB6 through COM | Is it possible to return an array of defined interface objects from a C++ COM function (VC6) to a VB6 client? I've scoured the web and haven't been able to come across anything that describes what I need to do. I've seen a lot of passing BSTR and VARIANT types, but I need some way to actually have the client side utili... | I've come up with a solution that is suitable for my purposes, despite not being exactly what I set out in the question.
My solution was to create a COM function that takes a SAFEARRAY as a parameter and modifies it, instead of returning a created array. The VB6 client instantiates the array, and passes it to C++ for... |
5,631,152 | 5,631,242 | Traversing an array to find the second largest element in linear time | Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.
Solution : Sort the array and take the second element but Sorting not allowed
Modification : By definit... | If you want a true O(n) algorithm, and want to find nth largest element in array then you should use quickselect (it's basically quicksort where you throw out the partition that you're not interested in), and the below is a great writeup, with the runtime analysis:
http://pine.cs.yale.edu/pinewiki/QuickSelect
|
5,631,229 | 5,631,286 | using exec to execute a system command in a new process | I am trying to spawn a process that executes a system command, while my own program still proceeds and two processes will run in parallel. I am working on linux.
I looked up online and sounds like I should use exec() family. But it doesn't work quite as what I expected. For example, in the following code, I only see "... | You're missing a call to fork. All exec does is replace the current process image with that of the new program. Use fork to spawn a copy of your current process. Its return value will tell you whether it's the child or the original parent that's running. If it's the child, call exec.
Once you've made that change, it o... |
5,631,486 | 5,648,889 | How do I set the number of visible lines in a Gtk::TextView? | I have a Gtk::TextView that I would always like to have two lines of text visible, regardless of the font size. Obviously if more than two lines were entered then the box would scroll but I'd like the text view to remain 2 lines tall.
How do I do this?
| This is very difficult. For example, what will you do if two font sizes are mixed in one line?
One way to do it is to create a Pango layout of one letter and find out its height. This is an untested simplification of some code I wrote in C one time; but it shouldn't be too much trouble to convert it to C++ and GTKmm:
P... |
5,631,553 | 5,637,060 | Qt - Why won't my widgets line up using a vertical layout inside a splitter? | As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?
/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
** by: Qt User Interface Compiler version ... | I pulled up designer and made your layout without any trouble at all. As shown in the hierarchy in the top right of my screenshot, I created a line edit and a text edit. Joined those in a vertical layout. Created a treeWidget and joined that with the layout in a horizontal splitter.
I was able to get it to look like... |
5,631,710 | 5,631,732 | finding whether the body contains gzipped data | i have a program wherein it searches the reply from a curl request for specific strings. i sometimes get gzipped data. is there a way to find whether the reply is text or gzipped format?
header sometimes contain gziipped,deflate header, but its not consistent. is there a way to search the string and find if its gzipped... | You could try taking a look at the first two bytes of data. For gzipped data, they should be 0x1f, 0x8b.
Member header and trailer
ID1 (IDentification 1)
ID2 (IDentification 2)
These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213),
to identify the file as being in gzip format.
|
5,632,079 | 5,632,255 | Why does std::set.insert() return a non-const iterator, and yet I cannot modify it? | Consider this code example:
#include <set>
#include <string>
using namespace std;
set<string> string_set;
void foo(const string& a)
{
pair<set<string>::iterator, bool> insert_result = string_set.insert(a);
string& val = *(insert_result.first);
val += " - inserted";
}
So, correctness aside, such as not ... | Because according to the standard, modifications through
a set<>::iterator are not allowed. The standard specifically
allows set<>::iterator and set<>::const_iterator to be the
same type. And although it doesn't require them to be the same
type, it does require the value_type of set<>::iterator to
be const.
The reaso... |
5,632,101 | 5,632,482 | Stack of polymorphed classes | dear C++ professionals. I got a problem. I have a program, which has 1 abstract class base_class and 2 derived classes: sippeers and dbget. It also has 2 threads. First thread gets commands from user, second thread pocesses these commands. Both derived classes represent different commands. So, I have to create some kin... | An std::queue of shared_ptr<base_class> is the most straightforward solution to pass classes from 1 thread to another without worring about memory management. Combined with a conditional variable to signal that the queue is not empty, so the consumer-thread can wait.
For the polymorphism part, have an extra virtual fu... |
5,632,194 | 5,632,419 | Why does multimap allow duplicate key-value pairs? | EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.
What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)
#include <map>
#include <string>
#include <iostream>
int
main(int argc, char** argv)
{
std::multimap<std::string, std::string> m;
m.insert(std::make_p... | Multimap only has a predicate ordering the keys. It has no method to determine whether the values are equal. Is value "A" a duplicate of value "a"? Without a second predicate for the values, there's no telling. Therefore, it doesn't even make sense to talk about duplicate values in a multimap.
If you would like a conta... |
5,632,243 | 5,632,317 | Qt - What is meant by those lines of code | In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:
#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.set... | "ui_gotocelldialog.h" is a file generated automatically based on the file "gotocelldialog.ui" which contains the GUI for the dialog. Ui::GoToCellDialog::setupUi() must be called for the UI to be initialized.
|
5,632,572 | 5,632,723 | What to watch out for when converting a std::string to a char* for C function? | I have read many posts asking the question on how to convert a C++ std::string or const std::string& to a char* to pass it to a C function and it seems there is quite a few caveat's in regards to doing this. One has to beware about the string being contiguous and a lot of other things. The point is that I've never re... | First, whether const reference or value doesn't change anything.
You then have to consider what the function is expecting. There
are different things which a function can do with a char* or
a char const*---the original versions of memcpy, for
example, used these types, and it's possible that there is still
such code a... |
5,632,714 | 5,632,734 | Compiler policies on destruction of temporaries | I've been playing with the following piece of code. file_string returns a temporary string that should only "live" until the end of the statement. In Visual Studio 2008, when you use pTempFolder, it contains rubbish as expected. In Linux though, with Intel compiler 11.0, pTempFolder still points to a valid string. Do c... | Likely, the string is still invalid, it just so happens that that section of memory hasn't yet been de-allocated at the operating system level and it "happens" to work. This program exhibits undefined behaviour- which always includes "may continue to work as if nothing went wrong". Visual Studio is completely correct h... |
5,632,739 | 5,633,389 | Is there a way to completely remove an inode when the Link count is 2? | Currently my data is organised in a volume which has a cache directory (where all the files are first created or transferred). After that there are suitable directories on the volume which in their subdirs, contain files hardlinked to files in the cache.
This is done so that the same inode (file) can be hardlinked mult... | No, there isn't anything that does what you want out of the box.
It might be useful to do the deletion when unlinking the hardlink and noticing that the link count is 1, since at that point the inode should be in the page cache; this of course is dependent on knowing the name of the file in the cache directory.
|
5,632,902 | 5,633,019 | Linked List From Text File | I'm very new to pointers and linked lists but I'm trying to write a simple program that reads in data from a text file into a linked list. I'm having trouble with the input function. It looks like this:
DVDNode* CreateList(string fileName)
{
ifstream inFile;
inFile.open(fileName.c_str());
DVDNode* head = N... | It is not hanging, it is waiting for your input because you have:
cin >> dvdPtr -> year; // read year from std input!!
cin >> dvdPtr -> rating;
in the function CreateList. This function opens the user specified file and reads the DVD fields from it.
Change the above lines to:
inFile >> dvdPtr -> year; // read year... |
5,633,023 | 9,789,473 | Include .so library to android ndk project | I'm beginning with android NDK. I have to compile a native library for the 1.6 sdk (mupdf) but it requires the ljnigraphics lib (which was added lately on 2.2). I'm trying to include the compiled library to my android project but I can't figure out how to do it.
1. Is it the best way to do this ?
2. If yes how shoul... | I finally used the code at http://code.google.com/p/droidreader/
|
5,633,226 | 5,633,319 | Asynchronous socket send on Linux | When send on an asynchronous socket returns EAGAIN, does that mean :
that the current call has just been successfully queued or that nothing was done because the system is still processing a previous send ?
Thank you in advance.
| From man 2 send:
The socket is marked nonblocking and the requested operation would block. POSIX.1-2001 allows either error to be returned for this case, and does not require this constants [EAGAIN EWOULDBLOCK] to have the same value, so a portable application should check for both possibilities.
So, I think EAGAIN m... |
5,633,253 | 5,633,283 | openGL lighting rotates with camera | I'm trying to build something simple for uni coursework and I've just tried to light it, but the lights seem to rotate with the camera, which is totally annoying...
I've pasted my code below using a pastebin (so that it doesn't stretch the page), but here's a little explanation too:
I added the lights in Display::Init ... | After changing the camera position, call glLightfv(lightNumber, GL_POSITION, position) again with the world-coordinates of the light. Then draw the scene.
|
5,633,350 | 5,633,632 | Extracting the "n"th image out of a bmp (or other image type) | I have a bmp image that's comprised of 13 images, and each image is exactly 17x17. Aside from breaking this image down through gimp into 13 different images, what is a good way to 'extract' the nth image from this list (into a char array, preferably) so that I may then use it?
I've tried advancing the pointer forward b... | Perhaps use existing tools for tile cropping
convert paged.gif +gravity -crop 32x32 tiles_%d.gif
Imagemagick comes with an API that is usable from many language, including C, C++, php, perl, etc etc
The relevant function would seem to be
CropImageToTiles
|
5,633,609 | 5,634,062 | C++ Matrix Class - Suggestions | I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.
The whole implementation is public and also there are no explicit bound/... | A couple of points:
Use a single std::vector<T> instead of std::vector<std::vector<T>>. Index it with y*r+x - use and operator overload to make this easier (see next point). This will be more memory efficient and slightly faster (and your init will be a lot easier: resize(r*c)).
Make your data members private to prote... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.