question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,283,546 | 4,283,703 | How to get a list of files in a folder in which the files are sorted with modified date time? | I need to a list of files in a folder and the files are sorted with their modified date time.
I am working with C++ under Linux, the Boost library is supported.
Could anyone please provide me some sample of code of how to implement this?
| Most operating systems do not return directory entries in any particular order. If you want to sort them (you probably should if you are going to show the results to a human user), you need to do that in a separate pass. One way you could do that is to insert the entries into a std::multimap, something like so:
names... |
4,283,576 | 4,283,589 | constructor invocation mechanism | struct my
{
my(){ std::cout<<"Default";}
my(const my& m){ std::cout<<"Copy";}
~my(){ std::cout<<"Destructor";}
};
int main()
{
my m(); //1
my n(my()); //2
}
Expected output :
1 ) Default
2 ) Copy
Actual output :
What's wrong with my understanding of the constructor invoking mechanism?
Note I have om... | Case 1)
m is interpreted as a function return my and taking no arguments.
To see the expected output remove () i.e use my m;
Case 2)
This is something better known as the "Most vexing parse".
n is interpreted as a function returning my that takes an argument of type pointer to function returning my taking no arguments.... |
4,283,731 | 4,285,583 | plotting package for c++ | I have got a question about plotting package for c++. For last few years I was using python and matplotlib, right now I am using c++ and I would like to find something similar to matplotlib (http://matplotlib.sourceforge.net/gallery.html) like 2d, 3d plots, histograms and so on and so on. I just want to know Your recom... | I again would recommend gnuplot.
If you don't want to use it then I liked plplot when I used it: http://plplot.sourceforge.net/ . The canvas to plplot can be put into gtk+ frame too if you want to add buttons to your plot.
That said, I returned to gnuplot before too long.
|
4,283,745 | 4,283,784 | Array as a parameter | I have created an array:
CString* pstrArray = new CString[nMySize];
Now how can I pass it to a function to be filled up? What is the actual parameter?
void FillThisArray(what goes here?)
{
}
| You should use a container class: CStringArray
void FillThisArray( CStringArray & rMyStrings )
If you don't want this (I don't see any possible reason, but anyway):
void FillThisArray(CString* strings, size_t num)
{
// example
for( size_t s=0; s<num; s++ )
{
strings[s].Format( _T("This is the %d. string"), ... |
4,283,792 | 4,283,848 | Ambiguous inheritance of abstract base classes: | I have a far more complicated class structure than this, but boiling the problem down to its essence, this describes my scenario: I have two classes, A & B, that implement pure virtual base classes that share a common ancestor, and then a third class C that com-posits A & B. Finally, a template class that fills in the ... | Redeclare method r as pure virtual in C:
struct C : A, B {
void q(){
r(); // the problem is here.
}
virtual void r()=0;
};
|
4,283,943 | 4,284,016 | Getting the backtrace from the catch block | I am using backtrace to get the information from where the exception is thrown. In the constructor of my exception, I am storing the backtrace in a std::string, and in the catch block for exceptions of this type, I am printing this backtrace.
But I was wondering, is it possible to somehow get the same backtrace in the ... | I don't think so. When executons stops in catch block the stack is unwound, and all that has happened before is not in stack anymore.
|
4,284,049 | 4,284,241 | Binary Search C++ STL | I have a vector of unordered_map which is sorted based on the comparer function I defined. I would like to use binary search to look for one of the value using the comparer function as well. However, binary search only return bool and I need the index / iterator of the result. What could I do?
| #include <algorithm>
using namespace std;
//!!!!! a must be sorted using cmp. Question indicates that it is.
it = lower_bound(a.begin, a.end(), value, cmp);
//Check that we have actually found the value.
//If the requested value is missing
//then we will have the value before where the requested value
//w... |
4,284,089 | 4,292,542 | How do I get the current directory of a konsole kpart | Exactly what it says on the tin.
Also is there any way to tell what is running inside the shell?*
I suppose I could do this by looking up finding process with matching parent pids* but is that portable to windows? And how would you look up current directory of a process given pid*.
*(most to least preferable) qt or kde... | It looks like TerminalInterfaceV2 might be exactly what I need, any extra info about it would be appreciated.
|
4,284,132 | 4,284,200 | Sorting struct based on one of each property in C++ | I am a Java and C# programmer. Recently, I am working on C++ project. I am having a problem of how to write the sample code following in C++. The sample code following is to sort a property of a struct:
public struct Person
{
public string name;
public int age;
}
Add some Persons to a list and sort by the age:... | Given the Person type :
struct Person
{
Person(int age_, const std::string &name_)
: age(age_), name(name_)
{}
int age;
std::string name;
};
int main()
{
std::list<Person> persons;
persons.push_back(Person(10, "Jane"));
persons.push_back(Person(13, "Jack"));
persons.push_back(P... |
4,284,319 | 4,284,529 | Inheriting from template class | #include <iostream>
#include <math.h>
using namespace std;
template<template<short,short,short,int> class Derived>
struct AllocFactor_Core
{
private:
static long double factor_;
stat... | Your base class expects a template template parameter, but you are passing it a concrete class. Use e.g. the following instead:
using AllocFactor_Core< ::AllocFactorScientific >::getFactor;
Note that the following doesn't work either because of the class name injection:
using AllocFactor_Core< AllocFactorScientific >:... |
4,284,363 | 4,284,396 | how to get a window's direct child ( not any grandchildren) in win32? | just the direct child, not grandchildren.
| GetWindow(hwnd,GW_CHILD); seems to be the trick.
|
4,284,406 | 4,284,449 | Why adding a number to an associative container's iterator is not possible? | I have an std::set and I wanted to iterate trough the element pairs in the set so I wrote 2 for loops like this:
for(std::set<T>::iterator i=mySet.begin();i!=mySet.end();++i)
{
for(std::set<T>::iterator j=i+1;j!=mySet.end();++j)
{
// do something
}
}
The compiler told me that I can't add numbers to... | you can do this only with random access iterator, so the reasons are the same as for not having an indexoperator on containers when it would be slow. See also Why isn't there an operator[] for a std::list?
|
4,284,537 | 4,284,572 | C++ : Array of struct as function parameter | I have a struct:
typedef struct
{
int nNum;
string str;
}KeyPair;
Let's say I initialize my struct:
KeyPair keys[] =
{ {0, "tester"},
{2, "yadah"},
{0, "tester"}
};
I want to use the initialized values in a function. How do I pass this array struct as a function parameter?
I have: ... | Should be
// Definition
void FetchKeys( KeyPair *pKeys, int nKeys)
{
//get the contents of keys[] here...
}
// Call
FetchKeys(keys, sizeof(keys)/sizeof(keys[0]));
|
4,284,621 | 4,285,065 | Some questions about using CComPtr (when use Release()? Can I return CComPtr?, ...) | I writing add-on for Internet Explorer(BHO) and I'm using CComPtr smart pointers. I wonder:
When should I use CComPtr.Release() function?
In this this link it's used to release
browser object. Where else should I use it? In 'normal' use (with my own classes) I don't need it. Should I use it in this situation:
I ... | To the first question. CComPtr::Release() has the same effect as assigning a null pointer to the object. You can call Release() (or assign a null pointer) if for whatever reason you want to release the object before the pointer goes out of scope. For example:
CComPtr<ISomeInterface> pointer;
HRESULT hr = firstProvider-... |
4,284,733 | 4,284,801 | Preprocessor token expansion | My mental model of how the preprocessor works is apparently incomplete, and this is driving me crazy.
I want to concatenate two tokens, but the second token should be expanded first.
#define ANSWER 42
#define FOO foo_ ## ANSWER
Here, FOO expands to foo_ANSWER, but I want it to be foo_42. So I define a MERGE macro in ... | Read the answer to your question here:
The problem is that when you have a
macro replacement, the preprocessor
will only expand the macros
recursively if neither the stringizing
operator # nor the token-pasting
operator ## are applied to it. So, you
have to use some extra layers of
indirection, you can u... |
4,284,877 | 4,284,964 | Macro errors with member function | I'm having fun with macros (not)
#include <iostream>
using namespace std;
#define DEF_ATTRIBUTE(type, name) type name;\
typedef void (*type_name_t)(CLASS_NAME*);\
type_name_t ptr_type_name;\
void type_name(){( ptr_type_name = &CLASS_NAME::type_name);}\
class Test
{
public:
#define CLASS_NAME ... | The function pointers aren't equivalent.
void (*type_name_t)(Test*)
is not the same as
&Test::type_name
Your function pointer is of type: a pointer to a function that takes one argument, a Test pointer, and returns no value.
What you want is a pointer-to-member-function, specifically, a pointer to a member function t... |
4,284,913 | 4,285,080 | Force crash an application | I'm currently testing an application that my company wrote. One of the scenarios was to see what happens to the system state if that application was to crash. Is there an application out there that could force crash my application? I'd rather not write a crash into the code itself (ie. null pointer dereference). Using ... | Assuming Windows, see Application Verifier.
It can do fault injection (Low Resource Simulation) that makes various API calls fail, at configurable rates. E.g. Heap allocations, Virtual Alloc, WaitForXxx, Registry APIs, Filesystem APIs, and more.
You can even specify a grace period (in milliseconds) when no faults will ... |
4,284,984 | 4,285,105 | C++ Inheritance problem | I have a class as follows:
Class A
{
virtual int doSomethingCool() = 0;
};
Class B : public A
{
int doSomethingCool();
};
Now the problem likes , I have a set of classes whcih are dependent on A as interface. I need to change the prototype of the function for one of the derived classes. i.e. i need to pass it a ... | No, you don't need to add it to the base class.
class A
{
public:
virtual int doSomethingCool() = 0 {}
};
class B : public A
{
public:
int doSomethingCool() {return 0;}
};
class C: public A
{
private:
int doSomethingCool(); // hide base class version!
public:
int doSomethingCool(int param) {return param;}
};
... |
4,285,008 | 4,305,273 | MsiEnumRelatedProducts Invalid Parameter | Attempting to use MsiEnumRelatedProducts with various input is constantly returning only ERROR_INVALID_PARAMETERS for me. The documentation doesn't give any details on what the source of the invalid parameter could be but I've tried many different options. Currently I have this code below to demonstrate the problem. ... | Try enclosing your upgrade code in curly brackets so it looks like {GUID}.
|
4,285,021 | 4,285,073 | C++::GET & SET in a header file | I am trying to implement the get() inside a header file of C++:
For example: this is the file: test.hpp
class A {
public:
A(std::string f, int id):file(f), index(id){};
std::string getFile(){return file;};
int getIndex(){return id;};
private:
std::string file;
int index;
};
}
But then I get a problem:
undefined... | int getIndex(){return id;};
There is no member named 'id', so this line should be
int getIndex(){return index;};
Then you have a closen brace too much. Also note that there is no need for a semicolon after the curly braces. In addition, class members which do not modify the object should always be declared as const, ... |
4,285,298 | 4,285,329 | Will call to function which calls assert will be removed in Release ver of a program? | If I have something like:
static long double calcFactor_(const short mantissa, const short exponent,const short base = Derived::internals_.base_)
{
assert(mantissa > 0);
assert(mantissa < NumericLimits<short>::max);
assert(exponent < NumericLimits<short>::max);
... | Yes, assert won't make it to the release build but the calls to your Assert function will remain. At best, your compiler might detect an empty function and suppress the call, but I wouldn't count on it. If you really want to remove these calls from the release build, you could surround them with some #ifdef / #endif.
R... |
4,285,346 | 4,285,377 | Threading in BHO/ATL/COM. Winapi or something else? | I writing IE add-on and I'm using ATL for it. I need to create background worker thread so UI thread will be unblocked as soon as possible.
My question is, should I use the lowest possible way of creating thread which is Winapi, CreateThread etc.
Or is there other proffered way of creating worker thread in BHO/ATL/COM ... | There is no need to use low-level APIs unless you need the level of control they offer.
With ATL you already have CWorkerThread, but you could also use other libraries like Boost.Thread if you prefer.
|
4,285,389 | 4,285,407 | Header for MAXDOUBLE | In what header is max value for double defined?
| There is cfloat, which gives you DBL_MAX.
|
4,285,572 | 4,285,615 | is c++ source code portable to linux when it successfully compiles within Visual Studio 2010 | I would like to use Visual Studio 2010 to create a C++ application that will eventually run on Linux
Are there any compatibility/version issues that I should be aware of?
Which compiler should I use on Windows and on Linux?
| The compiler is unimportant as long as you use standard C++ and no platform specific extensions. If you need system specific facilities (networking, filesystem...), try to use an abstraction layer such as boost.
|
4,285,666 | 4,286,260 | Interlocked ops vs XXX::atomic on Win32 | What are the advantages and disadvantages of using Interlocked winapi functions instead of any library provides atomic operations on Win32 platform?
Portability is not an issue.
| If portability is not a concern then you're basically down to deciding whom you trust more to get this right. A library is generally designed to provide portability. It otherwise has a tough time competing with an OS provided implementation that's been battle-hardened for over 15 years.
Check this thread to see an ex... |
4,286,029 | 4,286,070 | configuring gdb to change the display of objects | In GDB, objects typically display with lots of tripe due to included template objects.
There's a lot of useless std::char_traits ...
Is there a way to filter this stuff out? Basically, I'd like to know if I can configure .gdbinit to display the text only for a std::string, and perhaps the first few elements for a vect... | Yes, there are such things about! It's a bit limited but you can do it.
Look here and also here.
|
4,286,058 | 4,286,123 | Stack overflow while allocating from heap | What exactly is happening here?
#include <boost/array.hpp>
#include <boost/assign/list_of.hpp>
struct Toy {
int m_data[100000];
};
struct Box {
Box()
: m_toys( boost::assign::list_of( Toy() )( Toy() )( Toy() ) )
{}
boost::array<Toy,3> m_toys;
};
void main()
{
Box* box = new Box; // T... | The problem is the Toy() objects being passed to boost::assign::list_of(). These are temporary objects which are created on the stack before being copied to the Box object (which will be on the heap)
to avoid creating them on the stack, you could do this:
Box() : m_toys()
{
Toy* t = new Toy;
for (int i = 0; i < 3... |
4,286,169 | 4,286,231 | date-time string to boost::gregorian::date | I have the following std::string '2010-08-10T23:59:00' and I need to convert it to a boost::gregorian::date object.
I know I should use boost::date_time::date_input_facet, but I just cannot seem to figure out how to do it.
Can someone please assist me as to how to do this conversion?
| boost's posix_time module supports a direct conversion from that form (which unless I'm confused is the ISO time format?). Take a look at:
boost::posix_time::from_iso_string
You just need to strip the formatting marks first.
posix_time::time_from_string
may work for you as well.
You should them be able to convert the... |
4,286,190 | 4,286,207 | Why does copy constructor hide the default constructor in C++? | #include <iostream>
#include <conio.h>
using namespace std;
class Base
{
int a;
public:
Base(const Base & b)
{
cout<<"inside constructor"<<endl;
}
};
int main()
{
Base b1;
getch();
return 0;
}
This gives an error. no matching function for call to `Base::Base()' ... | The default constructor is only generated if you don't declare any constructors. It's assumed that if you're defining a constructor of your own, then you can also decide whether you want a no-args constructor, and if so define that too.
In C++0x, there will be an explicit syntax for saying you want the default construc... |
4,286,199 | 4,286,458 | Associative container - exception rather than default-construct in C++ | I'm looking for an associative container in C++, where rather than requiring it's elements to be default-constructible, will throw an exception where a key is requested that isn't found - edit: in the appropriate functions, obviously not all of them require default-construction. This is basically because I'm replacing ... | The simplest answer for an std::map, is not using operator[]. Use insert to create the new elements and find to locate an existing element. If you do not use operator[] the contained type does not need to be default constructible, and you can decide to throw and exception if find does not locate the object.
|
4,286,223 | 4,286,790 | How to get a list of video capture devices (web cameras) on windows? (C++) | So we have a simple C++ win32 console app. All we want is to print list of web cameras and other video capture devices that are avaliable. We want to use windows apis as much as possible - no external libs - after all - all we want is to print out a a list - not to fly onto the moon!) How to do such thing?
My own reser... | From the examples shown, copy the following code into dev.c. Then open the command line with all the SDK variables set. At the command line link to ole32.lib and oleaut32.lib. It will then show you all the devices.
cl dev.c ole32.lib oleaut32.lib
dev.exe will give out the list on the command line.
#include <windows.h>
... |
4,286,535 | 4,286,548 | if without condition? | I just found this "C++" today and i cannot make sense of it:
if(array[i][j]) {--i;--j;}
can anyone explains to me how this work? I just don't get it. What is the condition here? It seems like it would be true every time, but when i got rid of the IF (so only this {--i;--j;} left.) it doesn't work the same.
I'm quite ... | assuming array is an array of int (or other integral types) the condition will be false if and only if array[i][j] == 0
|
4,286,670 | 4,286,924 | What is the preferred/idiomatic way to insert into a map? | I have identified four different ways of inserting elements into a std::map:
std::map<int, int> function;
function[0] = 42;
function.insert(std::map<int, int>::value_type(0, 42));
function.insert(std::pair<int, int>(0, 42));
function.insert(std::make_pair(0, 42));
Which of those is the preferred/idiomatic way? (And i... | First of all, operator[] and insert member functions are not functionally equivalent :
The operator[] will search for the key, insert a default constructed value if not found, and return a reference to which you assign a value. Obviously, this can be inefficient if the mapped_type can benefit from being directly initi... |
4,286,686 | 4,286,745 | "Static plugin" system (via build system) in C++ | I am working on a C++ product currently. It was designed to have a fair amount of flexibility and has grown bigger and bigger. Now we are planning to cooperate in a project where we would like to contribute parts of the product: some parts as source code, some parts as static link libraries, some parts not at all.
I wo... | There's an interesting article series from Dr Dobbs that you might want to check out. I seem to remember that it supports static linking of plugins in addition to the usual dynamic linking. Check out Building Your Own Plugin Framework.
Good luck!
|
4,286,845 | 4,296,345 | hash function for boost_unordered, no default possible? | I have an class which has list of items (an instance of a class called ItemList).
This ItemList class has functions such as:
ItemIndexType AddItem(...);
void DoSomething(ItemIndexType index, ...);
ItemIndexType acts as some kind of "smart iterator", and has the member variables
myIter (iterator to a multimap in the It... | You need an equality predicate and a hash function for your key datatype, see Equality Predicates and Hash Functions. You can build your hash function by combining the hash functions of simple types with boost::hash_combine
|
4,286,863 | 4,286,948 | Having trouble with a memory leak - rebinding keys in std::map | void filename_changed(string originalfilename, string newfilename) {
auto it = file_source_map.find(originalfilename);
if (it == file_source_map.end())
return;
file_source_map.insert(std::pair<const string, string>(newfilename, it->second));
file_source_map.erase(originalfilename);
}
I replaced... | Except for the simpler (probably replaced while investigating the memory leak)
file_source_map.insert(std::make_pair(newfilename, it->second));
file_source_map.erase(it);
and a check that both filenames are not the same (which would not leak, but actually erase the entry), there is nothing obvious wrong with the code.... |
4,286,934 | 4,287,070 | Warning C4996: This function or variable may be unsafe -- compared to GCC on POSIX | I notice that MS compilers give "deprecated" warnings for cstdlib functions like getenv. MS has invented its own standard such as _dupenv_s.
Question 1
AFAIK the main "unsafe" thing is about reentrancy *. Since MS's CRT is marked as "multi-threaded" (/MT), why don't they just replace getenv with the reentrant, thread-s... |
In a sane world, the answer would be "of course not, that would be stupid!" In this world, though, it seems there is no end of gut-wrenchingly poorly thought out undocumented behavior upon which people will stoop to depending upon. Raymond Chen has a great collection of such anecdotes (anecdon'ts?) in his blog. Such a... |
4,287,032 | 4,287,198 | Block outgoing TCP connection to a given host or IP? | Is it possible to intercept an outgoing TCP connection to a given host or IP in Windows and block that connection on the TCP level, i.e. at the connect(...) layer? Or prevent connection to a specific IP in the first place?
Or do I need to write a packet filter to intercept traffic to a certain address?
| It's probably best to simply use the system's firewall API. On Windows:
http://msdn.microsoft.com/en-us/library/aa366449(v=VS.85).aspx
Otherwise you are going to be writing drivers and such... complete hassle considering the functionality is built into the OS these days.
|
4,287,044 | 4,287,150 | Algorithms for traversing a collection in sorted order without modifying the collection? | Let us say we have a collection like the following: {12, 10, 4, 5, 7}
I'd like to preserve the order of the collection so the indices will remain consistent but traverse the collection in a sorted order like so {12, 10, 7, 5, 4}.
What I've thought of is to make another collection of pointers to the elements and then so... | If you want to maintain both orders as an ongoing thing, while elements are added and removed, then you could use boost multi-index:
http://live.boost.org/doc/libs/1_34_0/libs/multi_index/doc/tutorial/basics.html#multiple_sort
This example from that page is pretty much what you want, except sorted in the opposite order... |
4,287,055 | 4,287,192 | Debugging CMake based application in Netbeans | I have converted a CMake based application to Netbeans project on Ubuntu. The problem is that, although I can run the application, I am unable to debug the code (something for which I did the whole thing). I have tried to reset the "Console Type" and "Terminal Type" properties in Properties->Run tab. Although it works ... | Have you set the build type in CMake to be Debug?
|
4,287,189 | 4,287,512 | Is there a way to check if its safe to copy or assign an object in C++? | I have the following problem. I'm using the C library igraph (http://igraph.sourceforge.net/) in a program I must do in c++. So I found a c++ wrapper of this C library (http://code.google.com/p/igraphhpp/) that provides some nice interface I wanted to use, in a class called Graph.
I have the following class in my prog... | Check the source of Graph, see whether the copy constructor calls this function:
http://igraph.sourceforge.net/doc/html/ch04s02s01.html#igraph_copy
There's no general way - the C++ language itself knows nothing about "deep copies" or "shallow copies", so copy constructors are all the same to it as far as that's concern... |
4,287,230 | 4,289,336 | Extra allocations and magical space reduction in the STL - using rvalue references | I replaced the Standard allocator with an allocator that will "phone home" about how much memory it consumes. Now I'm going through some of my code, wondering why the hell it allocates and then deallocates so many entries.
Just for reference, I'm not trying to pre-optimize my code or anything, I'm mostly curious, excep... | I ran your code in VS 2010, and I believe that the allocations you see are only Visual Studio STL debugging facilities as all the 8 bytes allocations are issued from _String_val constructor :
In release (_ITERATOR_DEBUG_LEVEL == 0), the constructor is trivial
In debug (_ITERATOR_DEBUG_LEVEL != 0), it allocates a _Cont... |
4,287,299 | 4,290,960 | boost::serialization of boost::unordered_map | I've moved one of my member variables from a std::map to a boost::unordered_map for the performance benefits on insertion. However, this has broken my use of boost serialization for export/importing from an archive.
I've tried looking but can't find it anyway, I was wondering if there was a header I could include that ... | Have a look at unordered_map_serialization.h in my distributed opening book learning project. It should be what you're looking for.
|
4,287,428 | 4,287,447 | Error: has initializer but incomplete type | I am having the problem: has initializer but incomplete type while using struct:
in a hpp file:
class A
{
private:
struct videoDT;
};
in a cpp file:
struct A::videoDT
{
videoDT(int b) : a(b){}
int a;
};
void test()
{
struct videoDT test(1);
}
Then I have the problem:
Error: has initializer but incomplete ... | I think the problem is that test() doesn't have access to A's private types.
This compiles for me:
class A
{
private:
friend void test();
struct videoDT;
};
struct A::videoDT
{
videoDT(int b) : a(b){}
int a;
};
void test()
{
A::videoDT test(1);
}
|
4,287,612 | 4,287,620 | How does this code work? | I am looking at c++ for dummies and found this code
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int nextStudentId = 1000; // first legal Student ID
class StudentId
{
public:
StudentId()
{
value = nextStudentId++;
cout << "Take next student id " << value << endl;
}
// int cons... | The ++ is the post-increment operator: it first reads the value (and assigns it to a variable), and only then increments it.
Contrast this with the pre-increment operator:
value = ++nextStudentId;
This would have the behavior you expect.
Take a look at this question for more information: Incrementing in C++ - When to ... |
4,287,701 | 4,298,798 | QMessageBox in initializeGL calls initializeGL one more time | void MyGlWidget::initializeGL() {
try {
throw std::exception();
} catch(...) {
QMessageBox::critical(this, tr("Exception"),
tr("Exception occured"));
}
}
in catch() messagebox is shown and execution goes into initializeGL() again, and shows a second message box
I'm ... | Here is the solution:
http://labs.qt.nokia.com/2010/02/23/unpredictable-exec/
void MyGlWidget::initializeGL() {
try {
throw std::exception();
} catch(...) {
getExceptionMessage(&exception_msg_);
QMessageBox *msgbox = new QMessageBox(QMessageBox::Warning,
... |
4,287,806 | 4,287,825 | variable 'fstream grabpass' has initializer but incomplete type | I'm getting an error reading from a file using fstream, on line 37 (fstream grabpass("passwords.txt");) but doesn't seem like I'm doing anything wrong.
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int i,passcount,asterisks;
char replace, value, newchar;
string username,password,stored... | You need to add #include <fstream>. At a guess, <iostream> is probably including a declaration of fstream (most like via <iosfwd>), but not a definition, so it has incomplete type when you try to define an object of that type.
|
4,288,030 | 4,288,087 | C++ Objects: When should I use pointer or reference | I can use an object as pointer to it, or its reference. I understand that the difference is that pointers have to be deleted manually, and references remain until they are out of scope.
When should I use each of them? What is the practical difference?
Neither of these questions answered my doubts:
Pointer vs. Referenc... | A reference is basically a pointer with restrictions (has to be bound on creation, can't be rebound/null). If it makes sense for your code to use these restrictions, then using a reference instead of a pointer allows the compiler to warn you about accidentally violating them.
It's a lot like the const qualifier: the la... |
4,288,190 | 4,288,864 | Constant class members, assignment operator and QList | Please conform if I am correct and tell me whether there is a better solution:
I understand that objects with constant members like int const width; can not be handled by the synthetic assignment operator that is implicitly created by the compiler. But QList (and I suppose std::list, too) needs a working assignment ope... | I'll try to bundle the answers in short:
The main problem is that QList requires the assignment operator to be present because they internally use assignment. Thus they mix implementation with interface. So although YOU don't need the assignment operator QList won't work without it. source
@ 3. There is std::List but i... |
4,288,348 | 4,288,392 | Does C++ standard dictate whether these two methods of accessing the array are identical or different? | Considering following array and two series of assignments:
char charArray[3];
charArray[0]='a';
charArray[1]='b';
charArray[2]='c';
char & charRef1=charArray[0];
charRef1='a';
char & charRef2=charArray[1];
charRef2='b';
char & charRef3=charArray[2];
charRef3='c';
Does C++ standard dictate whether these two series of... | No, the standard makes no requirements that the implementation details must be the same. 1.9/1:
The semantic descriptions in this
International Standard define a
parameterized nondeterministic
abstract machine. This International
Standard places no requirement on the
structure of conforming
implementations... |
4,288,367 | 4,295,217 | How to rotate and then move on that direction? | Hy, I am currently trying to make a first person game.what i was able to do was to make the camera move using the function gluLookAt(), and to rotate it using glRotatef().What I am trying to to is to rotate the camera and then move forward on the direction i have rotated on, but the axes stay the same,and although i ha... | This requires a bit of vector math...
Given these functions, the operation is pretty simple though:
vec rotx(vec v, double a)
{
return vec(v.x, v.y*cos(a) - v.z*sin(a), v.y*sin(a) + v.z*cos(a));
}
vec roty(vec v, double a)
{
return vec(v.x*cos(a) + v.z*sin(a), v.y, -v.x*sin(a) + v.z*cos(a));
}
vec rotz(vec v,... |
4,288,383 | 4,288,406 | Stringstream to string logic C++ | header.h
#include <iostream>
#include <vector>
class CombatLine{
std::stringstream Line;
std::vector<std::string> TokenLine;
void SetLine(std::string s){
Line<<s;
}
public:
void SetTokenLine(){
int i=0;
while(i<5){
Line>>TokenLine[i];
i... | You cannot write directly into TokenLine[i] since it's initialized as an empty vector in your CombatLine constructor. You won't need the resize if you build the vector up as you read each line.
Try this:
void SetTokenLine(){
int i=0;
string nextLine;
while(i<5){
Line>>nextLine;
... |
4,288,439 | 4,288,479 | Problem using a compare function inside of a class for sort() | If you take a look at my function CardCompare inside of the class... It doesn't work! But, if I instead use the function where it is commented out in Hand.cpp, it works perfectly fine. Why is this?
Also, I am wondering if keeping the CardCompare function in my hand class makes less sense than keeping it in the Card cla... | You are trying to pass a pointer to a member function, so sort can't use it because it doesn't have this pointer. In your case you can just change the function to be static:
static bool CardCompare (Card i, Card j) {return ( i.RankInt() < j.RankInt() ); }
If you do need it be a non-static member function in the future... |
4,288,828 | 4,288,868 | Zero-length C-array binds to pointer type | I recently wrote a function template which takes a reference to a C-array:
template <class T, size_t N>
void foo(T(&c_array)[N]);
Assuming T is a char, the length of the C-string is N - 1 due to the null-terminator. I realized I should probably handle the edge-case where N == 0, because then N - 1 would be std::numer... | As arrays must have greater than zero length, if your compiler erroneously accepts a definition of a zero-sized array then you're "safely" outside of the scope of the language standard. There's no need for you to handle the edge case of N == 0.
This is true in C++: 8.3.5 [dcl.array]: If the constant-expression (5.19) i... |
4,288,935 | 4,288,984 | Visual C++ 2008; add library to compilation process? | I have a project that needs the fmod library, and I need to have the compiler search the directory I installed it in for the source code. This is pretty much my first time interacting with the C++ compilation process, so I'm completely lost. What settings do I use to tell it where the library is?'
Edit: to be clear, I'... | To include extra third-party libraries:
right click the project in Solution Explorer and select Properties
add the library to the list in Configuration Properties -> Linker -> Input -> Additional Dependencies
add the library path to Configuration Properties -> Linker -> General-> Additional Library Directories
|
4,288,995 | 4,289,022 | how to check for an array update | I have an array of some data type (int, string, or even user defined class objects) and several threads in my program. I want to be able to find if the array has been updated after it was initialized with some values. One idea is to associate the hash of values in the array and whenever I want to check if the array has... | You could encapsulate the array in a class template that provides a facade for whatever read and write ops you need, and also marks the array dirty when it's updated - reset the dirty flag on each inspection.
Not sure how you make this reliable across multiple reader/writer threads but I guess it depends on access pa... |
4,289,013 | 4,289,078 | What software is helpful when designing/planning a large new personal project? | I have a large and challenging C++ project that I plan to undertake, one that will take maybe 6-18 months to get to the first release. It makes sense if I'm to invest that much of my time into this, that I plan it out in detail first.
But it's also just me working on it, so the usual morass of waterfall design tools ar... | When doing development on my own I try to keep it as simple as possible, while still having some kind of structure to it.
I think that the tools-part of the Joel test catches the most important things:
Do you use source control?
Can you make a build in one step?
Do you have a bug database?
Do you fix bugs before writ... |
4,289,077 | 4,289,097 | How do I plot multiple Y values for a single X value in a single Gnuplot window? | I'm using C++ to plot graphs using Gnuplot. In the C++ program, I popen() a Gnuplot process file, and keep writing to it to plot my graphs. Specifically, I write "plot '-' using 1:2 with points", and then continue with writing the X-Y coordinates. For just two columns, it works fine.
Now I have modified my program to g... | I can think of two ways, but they both involve iterating through your data multiple (5) times. First, multiple plots can be separated by commas like such:
plot '-', '-', '-', '-', '-'
You'll then fprintf(...) an 'e' after each set of data.
Additionally, since you're just plotting points (not lines), you could just ke... |
4,289,083 | 4,289,112 | Capture single image from webcam | What would be the best way using the best library to quickly capture a single image from a webcam with c++?
EDIT:
Although the faq example showed how to capture a stream of frames, I morphed it a little to do what I need. Thank you.
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
int main() {
CvCaptur... | OpenCV has C and C++ APIs, is cross-platform, and is very easy to use. There is an example in Learning OpenCV on page 26-27 which covers capturing a single frame from a webcam. There is also an example in the OpenCV FAQ:
http://opencv.willowgarage.com/wiki/CameraCapture
|
4,289,377 | 4,289,537 | Embeddable FileSystem? | Do you know some library/framework/embeddedEngine for storing data in one binary file? Something like file system in one file. It also must support tools for fragmentating data after removing/updating. Prefer languages C++ or C#. Platform Windows.
Thank you for any advice!!!
| ESENT, you can check out my framework for C#.
Unlike SQLite, it's OK to hold 1GB of data in a single field.
|
4,289,506 | 4,289,576 | C++ Win32 Replace Strings in an Executable | I'm looking for a good way to replace several strings inside a native win32 compiled exe. For example, I have the following in my code:
const char *updateSite = "http://www.place.com"
const char *updateURL = "/software/release/updater.php"
I need to modify these strings with other arbitrary length strings within the... | I would not mess around the the EXE itself, if you really need 1 file, then do the old zip append trick and put your configs in there.
Could look like this:
> BINARY DATA
> ZIP FILE DATA
> 32bit unsigned int which's value is the size of the appended zip file
Pros:
easy to extend / maintain
you don't mess with the e... |
4,289,585 | 4,289,618 | Template Metaprogramming for This? | struct findCategoryByName
{
string name;
bool operator()(const category& a)
{
return (a.name == name);
}
};
struct findEntryByName
{
string name;
bool operator()(const entry* a)
{
return (a->name == name);
}
};
Is there a way to do this using template metaprogramming ... | Creating a generic findByName template is as simple as replacing the specific type with a template parameter:
template<class T>
struct findByName
{
string name;
bool operator()(const T &a)
{
return (a.name == name);
}
};
(This assumes the parameter is passed by reference, but you could change ... |
4,289,612 | 4,289,647 | Getting array from std:vector | What is the easiest way of getting a char array from a vector?
The way I am doing is getting a string initialized using vector begin and end iterators, and then getting .c_str() from this string. Are there other efficient methods?
| This was discussed in Scott Meyers' Effective STL, that you can do &vec[0] to get the address of the first element of an std::vector, and since the standard constrains vectors to having contiguous memory, you can do stuff like this.
// some function
void doSomething(char *cptr, int n)
{
}
// in your code
std::vector<... |
4,289,613 | 4,289,660 | Should I use XML in my c++ game | Is XML something required to use in modern games? Sense I'm trying to make game that will be programmed like a professional programmer did it, So should i use XML in my game or it is just an optional thing, Why and Why not?
| There's nothing wrong with using XML if it solves your problem. There's nothing wrong with not using XML if it isn't the best option for solving your problem.
If you want to store data in an a format which is easy to query, then XML is not a bad option. If you're look for space efficiency, XML is not a good option. If ... |
4,289,899 | 4,289,913 | Advantages of using initializer list? |
Possible Duplicate:
Benefits of Initialization lists
I was wondering if there was an advantage to initializing members with the initializer list over putting these in the constructor. Certain things have to use the initialize list but for the majority of things that don't, is there a difference? I prefer the latter ... | If you don't use the initializer list, the member or base class gets default constructed before the opening curly brace.
So, your calls to set it later will add an operator=() call.
If you use the initializer list, the member or base class has the proper constructor called.
Depending on your classes, this might be req... |
4,290,148 | 4,290,160 | Clarification on Operators | I've been reading up on class operators and came across the following example:
class Array {
public:
int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
private:
int data[100];
};
Does this mean I can replace [ and ] with whatever I want? For example, could I use parentheses?
Also, what is... |
Does this mean I can replace [ and ] with whatever I want?
Nopes! Not all operators can be overloaded.
For example, could I use parentheses?
You can but you shouldn't.
Also, what is the significance of the ampersand in int& operator[]?
It means you are returning a reference to an int variable.
EDIT: On a sli... |
4,290,173 | 4,290,275 | Is Vala a sane language to parse, compared to C++? | The problems parsing C++ are well known. It can't be parsed purely based on syntax, it can't be done as LALR (whatever the term is, i'm not a language theorist), the language spec is a zillion pages, etc. For that and other reasons I'm deciding on an alternative language for my personal projects.
Vala looks like ... | C++ is one of the most complex (if not the most complex) programming language to parse in common use. Of particular difficulty is it's name lookup rules and template instantiation rules. C++ is not parsable using a LALR(1) parser (such as the parsers generated by Bison and Yacc), but it is by all means parsable (after ... |
4,290,192 | 4,290,255 | How to set alignment for virtual functions? | I'm developing plug-in for Win32 using mingw and crosscompilation from linux. Although my plugin successfuly loaded by application and I even got an com-interface from app, I cant call functions from there - app is crashed. I think that this is due to wrong vtable alignment of interface implementation in mingw (this wo... | VTable alignment (in fact, the entire VTable system at all) is completely implementation dependent. You have to use the same compiler, compiled with the same switches/settings, in order to have a workable program after linkage.
You can't link msvc generated binaries against MinGW generated ones for this reason. Even if... |
4,290,351 | 4,290,418 | Why does VC++ 2010 compiler crash when compiling simple code? | I encountered a very strange symptom. Who can tell me what the root cause is?
My VC++ compiler version is latest: "Microsoft Visual C++ 2010 : 01019-532-2002102-70860"
Steps to reproduce:
Create an empty win32 console project
Add a new cpp file named main.cpp
Paste the following code into main.cpp
Compile
The compiler... | Have you tried any type of troubleshooting yourself?
I can reproduce the crash using the above source code as you describe. Of course, I get a couple of warnings:
"IntelliSense: no instance of overloaded function "f" matches the argument list"
"IntelliSense: too few arguments in function call"
both referring to this ... |
4,290,374 | 4,337,979 | Visual c++ 6.0 Application size bigger than visual studio 2010 application size | I am currently editing a c++ application (only using plain api ),When i compiled it with 2010 (release configration )the size was 28 kb but when i did this with vc++ 6 it was 42 kb.
why is this
I cant use 2010 version for release because my bit defender says its a virus (my software is a self extracting exe uses lzma... | Different file sizes after compilation might be because the newer VisualStudio uses newer c-runtimes which add some runtime-checks to the code that weren't existing at VS 6 times.
Dont't know about the virus thing - maybe you have different output paths with the one from VS 2010 being in a directory watched by BitDefen... |
4,290,473 | 4,290,483 | compiler doesn't complain about function not returning value | I have the following function:
bool Server::ServerInit()
{
// bool listenResult = socket.Listen( (const uint8 *)_LOCAL_HOST, m_iPort );
// if( true == listenResult )
// cout << "Server passive socket listening\n";
// else
// cout << "Server passive socket not listening\n";
//
// return listenResult;... | Try compiling with -Wall option (gcc)[ -Wreturn-type to be more precise]. You'll a get a warning something like "Control reaches end of a non-void function" or something like "no return statement in function returning non-void"
Example:
C:\Users\SUPER USER\Desktop>type no_return.cpp
#include <iostream>
int func(){}
in... |
4,290,509 | 4,290,525 | Operator delete causing heap corruption while operator new working fine | I have got operator new working but as soon as I call delete, it crashes at the free (ptr) line. Can any one tell what I am doing wrong when overloading operator new and delete in this Base class? Hint: I am not asking about design issues.
class Base {
private:
int i;
public:
Base () : i (10) {
}
s... | This works for me:
#include <cstdlib>
using namespace std;
class Base {
public:
void * operator new(size_t size) {
if (size == 0) size = 1;
return malloc (size);
}
void operator delete (void *ptr, size_t size) {
if (ptr == NULL) return;
free (ptr);
}
};
int main()
{
Bas... |
4,290,562 | 4,290,781 | c++ CALLBACK function type | I'm trying to create something like MsgProc in Win32. When they declare the MsgProc function they have the CALLBACK type before it. So, all I'm trying to is create my own messsage function that calls my function to process the messages. It is basically the same thing when messages getting sent and processed. My que... | Other than the classics function pointers and function objects you may be interested by the new C++0x lambdas.
Here's an example of passing a lambda to a timer function.
#include <windows.h>
#include <iostream>
#include <functional>
void onInterval(DWORD interval, std::function<void ()> callback) {
for (;;) {
Sl... |
4,290,609 | 4,290,769 | How to capture video from WDM to MPEG format using DirectShow? | I wanna capture video from video source and encode it into MPEG format by using DirectShow. How to design Capture Graph and How to set the video properties for MPEG format (e.g. bitrate, framerate, resolution, etc.)
| My approach (which I used in production of VideoPhill recorder) was to use DirectShow.net only for capturing the frames, then using SampleGrabber filter to create a queue of frames which is later fed into the encoder - I use StandardMPEG for this.
My wish was to stay in managed most of the time - and using that approac... |
4,290,611 | 4,290,630 | Determining program runtimes on core i5/7 architecture | When determining accurately how fast an algorithm runs in my programs, I've always used QueryPerformanceCounter() in conjunction with QueryPerformanceFrequency(), however what happens when I'm using a core i5/7 architecture?
Is it possible that turbo boost would suddenly kick in half way through my algorithm and sudde... | To put it simply, Yes, anything can happen. Modern CPU's just plain make estimating real world performance to damn hard to do. This is not limited to just the latest Intel x86-64 cpus, it applies equally to 8bit PIC microcontrollers, and everything inbetween.
The only reasonable thing to do about it is to just test m... |
4,290,727 | 4,290,796 | Initializing a large global constant object | How do you use a file to initialize a global const object that is too large to be created in the stack? This is my attempt so far:
// test.h
#pragma once
#include <boost/array.hpp>
typedef boost::array<int,100000> bigLut_t;
extern const bigLut_t constLut;
// test.cpp
#include <fstream>
#include <boost/filesystem.hpp... | How did you use shared_ptr ? Try the following :
// test.h
#pragma once
#include <boost/array.hpp>
typedef boost::array<int,100000> bigLut_t;
extern const bigLut_t constLut;
// test.cpp
#include <fstream>
#include <boost/filesystem.hpp>
#include "test.h"
boost::shared_ptr<bigLut_t> initializeConstLut()
{
if( bo... |
4,290,834 | 4,290,867 | How to get a list of video capture devices (web cameras) on linux ( ubuntu )? (C/C++) | So all I need is simple - a list of currently avaliable video capture devices (web cameras). I need it in simple C or C++ console app. By list I mean something like such console output:
1) Asus Web Camera
2) Sony Web Camera
So It seems simple but I have one requirement - use of native OS apis as much as possible - no ... | This is a code snippet I had laying around. Probably from a book. I guess you could just iterate over all /dev/videoN nodes and get the info.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/videodev.h>
int main(){
int fd;
struct video_capability video_cap;
s... |
4,290,870 | 4,290,997 | Texture Mapping C++ OpenGL | I have read around on this, including Nehe and here for solutions, but I cant find a specific answer.
I am trying to load a a photo, called stars.jpg. I want to make this my background of the scene, by mapping it using uv coordinates, doing it by
glBegin(GL_QUADS);
glTexCoord2f(0,0);
glVertex2f(0,0);
However I am jus... | Here's a step by step tutorial on loading textures
http://www.nullterminator.net/gltexture.html
Its important to remember that OpenGL is a state machine, so you have to tell it "I'm going to talk about textures now" that's where the glActiveTexture(); comes in.
Also keep in mind that you will have to load in pixel b... |
4,290,994 | 4,291,200 | Visual studio C++: How to make parts of code not be seen by the windows compiler? | So jenerally I have small C++ project based on OpenSource crossplatform libs. So it probably would compile under linux. So I hited the point when I need to implement some defenatly platform specific class functions.
I have a class header with all functions declarations and cpp file with realisations. So first: how to ... | Take a look at http://predef.sourceforge.net/ for an extensive list of pre-defined macros various compilers provide to distinguish between operating systems, compilers, and processor architectures. They will allow you to distinguish between more than just Win32 and Linux if necessary.
|
4,291,062 | 4,291,122 | another win32 problem | Having a problem here with creating a child window with c++ and win32 api.
If i check the getLastError function its returning "87" but i dont know what that means.
For what i know my code does not contain errors, can someone take a look at my code and help me figure out whats wrong with it.
(This is in the WinProc WM_C... | 87 = Invalid Parameter - be aware that you can use FormatMessage to get a string message from an error code.
|
4,291,166 | 4,291,295 | appending an existed array | I have some question about arrays, I'm reading some book about Java, and now I was reading about class StringBuilder, I was taught that this class saves my string in array with current capacity, in the case that the capacity is not sufficient, this class automatically increases capacity capacity = 2*(capacity + 1), whe... |
why can't I just find out how much memory do I need and then to do
capacity = capacity + homMuchDoINeed()
Because then you need to allocate new memory with each insertion, so a single insertion takes linear time, and n insertions take quadratic time. If, on the other hand, you grow by a constant factor like x2 or x1.... |
4,291,205 | 4,291,274 | When does a new __LINE__ start? | I do not understand the output of the following program:
#include <iostream>
#define FOO std::cout << __LINE__ << ' ' \
<< __LINE__ << '\n';
int main()
{
FOO
std::cout << __LINE__ << ' ' \
<< __LINE__ << '\n';
}
The first output is 7 and 7, indicating that the expansion of... | Because
1: #include <iostream>
2:
3: #define FOO std::cout << __LINE__ << ' ' \
4: << __LINE__ << '\n';
5: int main()
6: {
7: FOO // the first two __LINE__s come from here, that's one line of code
8:
9: std::cout << __LINE__ << ' ' \ // 3rd __LINE__ comes from here
10: ... |
4,291,253 | 4,291,464 | Does this const initialization through const_cast have undefined behaviour? | According to my small tests this code works. But, does it have undefined behaviour? Modifying the const object through the use of const_cast resulted in run-time access violations in my previous tests, but I can't remember how they were different. So, is there fundamentally something wrong here or not?
// test.h
#pragm... | You modify an object defined as const. It doesn't matter when you do it, during initialization or not, it's still undefined behavior. Removing constness with const_cast is defined only if the const pointer was obtained from a non-const pointer to that object at some earlier stage. That's not your case.
The best thing y... |
4,291,271 | 4,291,343 | Opengl Vertex attribute stride | Hey.
I new to OpenGL ES but I've had my share of experience with normal OpenGL.
I've been told that using interlaced arrays for the vertex buffers is a lot faster due to the optimisation for avoiding cache misses.
I've developed a vertex format that I will use that looks like this
struct SVertex
{
float x,y,z;
... | If you have a structure like this, then stride is just sizeof SVertex and it's the same for every attribute. There's nothing complicated here.
If this didn't work, look for your error somewhere else.
For example here:
surface->GetIndexCount()/3
This parameter should be the number of vertices, not primitives to be sent ... |
4,291,476 | 4,291,497 | Case insensitive std::set of strings | How do you have a case insensitive insertion Or search of a string in std::set?
For example-
std::set<std::string> s;
s.insert("Hello");
s.insert("HELLO"); //not allowed, string already exists.
| You need to define a custom comparator:
struct InsensitiveCompare {
bool operator() (const std::string& a, const std::string& b) const {
return strcasecmp(a.c_str(), b.c_str()) < 0;
}
};
std::set<std::string, InsensitiveCompare> s;
You may try stricmp or strcoll if strcasecmp is not available.
|
4,291,526 | 4,291,561 | how do I link a .rc (resource) file when compiling a win32 app with gcc through command line? | I have been following the forgers win32 tutorial, specifically this section as of this moment, and was wondering how you would link the .rc(resource) file when compiling a win32 program? (I'm compiling through command line).
I was reading this article which says you could do something like this windres chocolate-doom-r... | You're missing the MENU resource type. You should write:
#include "resource.h"
IDR_MYMENU MENU
BEGIN
.
.
.
END
|
4,291,583 | 4,291,668 | RAW pointer container wrapper | I have a raw pointer which points to an array of data. I would like to wrap this pointer into a container with STL container semantics (e.g. std::vector). Does the STL have any feature which allows this?
e.g.
class my_class
{
public:
std::some_container<char> get_data() { return std::some_container(my_data, my_data... | STL doesn't, boost does:
boost::iterator_range<char*> get_data() {
return boost::iterator_range<char*>(my_data, my_data+my_data_size);
}
|
4,291,596 | 4,291,611 | Need full example on this topic: QtWebKit Bridge | I am new to Qt and currently I am doing some stuff on this topic: http://doc.qt.io/archives/qt-4.7/qtwebkit-bridge.html
What I am trying to do is:
create a JS object that maps to a C++ class with many properties and functions.
this C++ class could return any JS data types to JS environment.
this C++ class could accept... | Check out this blogpost: http://labs.qt.nokia.com/2010/11/16/some-webkit-hybrid-stuff/
There are some explanations, and a complete example is linked.
|
4,291,778 | 4,291,836 | C++ smart linear container | Let me explain my problem together with the background, so it would be easier to understand why I'm asking for this specific type of thing. I'm developing an instant messenger. Most of the architecture is outlined by my teacher, however implementation detail may vary. There is an "Engine" class, EventManager, which reg... |
If you remove something from the middle of a vector it will move all the following elements one position towards the beginning. It will not reallocate. You don't have to consider reallocations at all because they are amortized to give O(1) time per insertion.
deque is not much better than vector. Removing from the be... |
4,291,847 | 4,291,975 | Convert PCCERT_CONTEXT to openssl use - X509 struct or ASN1 | how can i convert this microsoft PCCERT_CONTEXT structure containing certificate to valid struct X509 or ASN1 which can be used with open SSL. THX
| It's in the pbCertEncoded member of that structure.
|
4,292,013 | 4,292,215 | Internal error during IncrCalcPtrs - does not recur when I run the code the 2nd time | The project holding the code has all default MSVS2008 settings.
Consider the following code using which I am familiarizing myself with various offerings of STL:
#include <vector>
#include <iostream>
#include <numeric>
using namespace std;
template <class T> void print(const vector<T>& l)
{ // A generic print functi... | This is a known problem in the linker for VS2008 SP1. Fixed in VS2010, the feedback report is here.
I've seen this myself a few times, it only happens when it actually links incrementally. For me it always resolved itself by forcing a full build through Build + Rebuild so that the .ilk file is deleted and re-created.... |
4,292,085 | 4,292,134 | Type inference in Visual C++ 2008 | Is there some vendor-specific type inference mechanism in Microsoft Visual C++ 2008, similar to the standardized auto or decltype in C++0x?
| No, nothing like that, standard nor vendor specific nor addon. You'll have to upgrade to VS2010, it implements auto.
|
4,292,089 | 4,292,098 | c++ passing by reference : error: no matching function for call | I have this code :
bool Port::add_app_from_wlist(App* a){
stringstream namesurn;
string name, surname;
namesurn << a->get_name();
namesurn >> name >> surname;
return add_application(a->get_id(),name,surname,a->arrived_at_port_by(),a->arrived_by(),a->is_luxury_class());
}
I get this error :
air_classes.cpp:153:
e... | The method add_application accepts 3 strings, but you specify only 2 of them in your call.
|
4,292,352 | 4,292,391 | MSVC - stop warnings in headers | I'm using MSVC with a CMaked project. As a result, I've enabled many of the flags on MSVC which were enabled for gcc and clang. However, the /Wall warning level is giving me some pain; it warns me about all kinds of things in included headers, like stdio.h and boost headers. Is there a way to stop MSVC from warning me ... | /Wall is very pedantic. /W4 is probably all you really need. To answer your question, you can disable specific warnings around your headers with:
#pragma warning(disable:xxxx)
#include <yourheader.h>
#pragma warning(default:xxxx)
Or change the warning level with:
#pragma warning(push,3)
#include <yourheader.h>
... |
4,292,507 | 4,304,426 | GtkVBox Qt equivalent | In GTK, I used to have a window to which I gtk_container_add()'d a GtkVBox. Then I could pack widgets I wanted to the GtkVBox to have them appear in the window.
Now I've decided to try out Qt, but I can't seem to figure out how to do this in Qt.
Right now what I've done is create a QMainWindow, but I found that you can... | In fact, here is the recommended solution provided by the Qt documentation.
You should create a QVBoxLayout and add the widgets you want in it. After that, you set the layout on another empty widget and then you set this widget as the central widget of the QMainWindow subclass. Here is an example in code:
QWidget* widg... |
4,292,734 | 4,292,751 | How to debug in visual studio 2008 | I keep getting these line numbers for errors in the external libraries cpp files, i have no way of knowing which part of my code it makes this error. Sometimes it even shows assembly code piece where it crashed...
How do i get the line where my own code caused this error? Or at least a clue which part of my code makes ... | Use breakpoints at the line of code where you want to "pause" program execution. That way you will be able to see the program state (the values of variables, etc, etc).
Here you have a series of tutorials on how to setup everything, to get debugging.
The Concepts
Debugger Setup
Using Breakpoints
Running the program ... |
4,292,849 | 4,292,918 | C++ Pointers & Arrays | Below is some code from a C++ procedure. The original can be found here;
https://code.ros.org/trac/opencv/browser/trunk/opencv/modules/imgproc/src/grabcut.cpp
My perspective is that I am a C# rather than C++ programmer so this code is a bit of a mystery to me even though I ran it through a code converter and it came o... | When you declare an array like this:
int my_ints[10];
my_ints is an array. But in C++ my_ints can also be evaluated as a pointer to the first item in the array. So code like this:
int* the_first_int = my_ints;
...is legal and valid, not to mention very common. You can also use the_first_int as if it were also an a... |
4,293,254 | 4,293,477 | opengl vbo dma array | I am creating an array of positions to draw and I am stuck when I am using dma for the array
if I declare the size of the array and populate I can get it to work but if I do
float *datac;
datac=NULL;
datac = new float[12];
datac[0] = 0;datac[1] = 0;datac[2] = 0;
datac[3] = 0;datac[4] = 100;datac[5] = 0;
datac[6] = 10... | It's C++, so you can use std::vector and make your life easy:
std::vector<float> datac(12);
datac[0] = 0;datac[1] = 0;datac[2] = 0;
datac[3] = 0;datac[4] = 100;datac[5] = 0;
datac[6] = 100;datac[7] = 100;datac[8] = 0;
datac[9] = 100;datac[10] = 0;datac[11] = 0;
glBufferData(GL_ARRAY_BUFFER, datac.size()*sizeof(float)... |
4,293,323 | 4,293,510 | Finding Implicit Communication in Classes | I am currently refactoring a very useful but poorly designed class in C++, and I'm running into a problem with the design: rather passing data around using arguments to methods, the data is passed around by setting private state variables in the class. This makes it very difficult for me to diagram out how data moves t... | Given the clarification in the question my "are you sure it's not just that you don't like the other programmer's style" comment dies a death ;)
Personally I'd just refactor normally. That is, with 78 data members and lots of bits that are related but not in a class of their own I'd start by grouping the related data a... |
4,293,343 | 4,293,377 | Coding iterator function for STL Class | I am working through some C++ code from "Financial Instrument Pricing Using C++" - a book on option pricing using C++. Following code is a small snippet stripped of many details which basically attempts to define a SimplePropertySet class that is intended to contain a name and list.
#include <iostream>
#include <list>
... | As indicated by the compiler, you must replace :
template <class N, class V>
SimplePropertySet<N,V>::iterator SimplePropertySet<N,V>::Begin()
with :
template <class N, class V>
typename SimplePropertySet<N,V>::iterator SimplePropertySet<N,V>::Begin()
See this link for an explanation on dependent names.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.