question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,358,398 | 2,478,893 | Templates - Exercises | As I mentioned in my yesterday's post, I'm trying to teach myself templates from the book: Templates: The Complete Guide. And although I'm finding this book very nicely presented and material there is explained really well there are no exercises attached after each chapter to test your knowledge, like it is in The C++ ... | C++ Template Metaprogramming; Concepts, Tools, and Techniques from Boost and beyond - this book really rocks.
|
2,358,516 | 2,358,540 | Iterator vs. Reference vs. Pointer | I have a class that spawns an arbitrary number of worker object that compute their results into a std::vector. I'm going to remove some of the worker objects at certain points but I'd like to keep their results in a certain ordering only known to the class that spawned them. Thus I'm providing the vectors for the outpu... | If an iterator is invalidated, it would also invalidate a pointer/reference that the iterator was converted into. If you have this:
std::vector<T>::iterator it = ...;
T *p = &(*it);
T &r = *p;
if the iterator is invalidated (for example a call to push_back can invalidate all existing vector iterators), the pointer an... |
2,358,524 | 2,358,557 | Why does this separate definition cause an error? | Challenge:
I have this code that fails to compile. Can you figure out what's wrong? It caused headache to me once.
// header
namespace values {
extern std::string address;
extern int port;
}
// .cpp file
std::string ::values::address = "192.0.0.1";
int ::values::port = 12;
It looks correct on the fi... | One error:
std::string values::address = "192.0.0.1";
is the proper form, otherwise the parse is
std::string::values::address = "192.0.0.1";
and there is no member "values" with a member "address" inside "string"...
it will work for builtin types, as they cannot ever contain members.. so int::values is an unambigo... |
2,358,799 | 2,415,794 | Mapping a class and a member function | Can someone suggest me a way to map a template classes with a set of member functions from another class? Whenever i call one of the function inside a template class, it should call the associated member function of the other class.
Updating with a use-case
template<int walktype>
class Walker
{
Node* node;
bool... | I found a way to do it using boost::mpl::map. I need to create a type out of the function and use that type as a template parameter for the class and associate this class with the original class using boost::mpl::map.
Thanks,
Gokul.
|
2,359,019 | 2,359,052 | C++: Avoiding dual maintenance in inheritance hierarchies | When creating a C++ inheritance structure, you have to define member functions exactly the same in multiple places:
If B is an abstract base class, and D, E, and F all inherit from B, you might have this:
class B
{
virtual func A( ... params ) = 0;
};
class D : public B
{
func A( ... params );
};
/* ... etc... ... | Actually, the biggest problem with changing an interface usually is all the code that uses it, not the code that implements it. If it's easy to change it for the implementer, it would probably make life harder for the users.
|
2,359,344 | 2,359,509 | google-test: code coverage | Is it possible to get code coverage done by tests using google test framework?
| Yes, I've successfully used both free (gcov) and commercial (CTC++) tools. No special steps are needed, just follow the documentation.
More details can be found in this blog
http://googletesting.blogspot.dk/2014/07/measuring-coverage-at-google.html
|
2,359,413 | 2,360,541 | Equivalent for TzSpecificLocalTimeToSystemTime() on win2k? | One of our developers used this call:
TzSpecificLocalTimeToSystemTime() but unfortunately we cannot keep it as the code must work on Win2K as well.
What alternatives are there for similar functionality?
| There is no equivalent, not even with WINE. It relies on timezone info stored in the registry, retrieved with GetTimeZoneInformation(). Note how the WINE code ends up in find_reg_tz_info(). That info is just missing in Win2k.
You'd have to create your own timezones table.
|
2,359,585 | 2,361,295 | Lining up Qt GroupBox labels | Is there an easy way to ensure that controls in different groupboxes on a Qt dialog line up correctly using layouts? If not, is there a way to line them up using code in the dialog's constructor?
For example, here is a form with two groupboxes containing controls that are laid out using a grid:
alt text http://lh3.ggp... | I don't think there is an easy solution since you have to separated and not connected layouts. What you could do is after you set up the layouts is iterating over all label strings and measure their size with QWidget::fontMetrics() on their label widget, remeber the maximum value and call QWidget::setMinimumWidth(). Th... |
2,359,626 | 2,360,025 | Answer to a practice interview question | I'm just going through a bunch of C++ interview questions just to make sure there's nothing obvious that I don't know. So far I haven't found anything that I didn't know already, except this:
long value;
//some stuff
value &= 0xFFFF;
The question is "what's wrong with this code?" And hints that it's something to do wi... | This problem with this code is that it does a bit-wise operation on a signed value. The results of such operations on negative values vary greatly for different integer representations.
For example consider the following program:
#include <iostream>
int main(void)
{
long value;
value = -1; // Some stuff
va... |
2,359,811 | 2,359,993 | Working with GNU regex functions in C or C++ | Can anyone give me complete example program how to work with GNU regex functions in gcc C or C++ (http://docs.freebsd.org/info/regex/regex.info.GNU_Regex_Functions.html), with
re_pattern_buffer, re_compile_fastmap?
For example, translate this small Python program:
import re
unlucky = re.compile('1\d*?3')
nums = ("13"... | Okay, before delving into the code, I should mention that you may want to use a higher-level library. You did say C++, so that opens you up to Boost.Regex and the like. Even if you want to stay with C, there are better options. I find the POSIX functions somewhat cleaner, not to mention more portable.
// Tell GNU to... |
2,359,820 | 2,359,873 | How do I make a custom system wide mouse cursor animation? | I write software for the disabled. One of the problems is difficulty tracking the mouse pointer. I want to have the mouse cursor glow (or similar effect. Maybe water like ripples around it) when the user needs to locate it. How is this done? I know it's possible because it's used in a variety of software.
| Have a look at Realworld Cursor Editor found here.
Edit: As the OP pointed out, the OP was looking for a way of creating an animated cursor programmatically, using Win32API. AFAIK it cannot be done or is long-winded way of doing it, the 'LoadCursor' function can load the cursor from an embedded resource or a file on di... |
2,360,048 | 2,360,052 | Using STL's list object | I want to create a list of queues in C++ but the compiler gives me some cryptic messages:
#include <list>
#include <queue>
class Test
{
[...]
list<queue> list_queue;
[...]
}
Output:
error C2143: syntax error : missing ';' before '<'
error C4430: missing type specifier - int assumed. Note: C++ does not sup... | queue is a template class as well, so you'll need to specify the element type contained in your queues. Also, - is not a legal identifier character in C++; perhaps you meant _?
std::list<std::queue<SOME_TYPE_HERE> > list_queue;
|
2,360,063 | 2,360,329 | PCRECPP (pcre) extract hostname from url code problem | I have this simple piece of code in c++:
int main(void)
{
string text = "http://www.amazon.com";
string a,b,c,d,e,f;
pcrecpp::RE re("^((\\w+):\\/\\/\\/?)?((\\w+):?(\\w+)?@)?([^\\/\\?:]+):?(\\d+)?(\\/?[^\\?#;\\|]+)?([;\\|])?([^\\?#]+)?\\??([^#]+)?#?(\\w*)");
if(re.PartialMatch(text, &... | The problem is that your code contains ??( which is a trigraph in C++ for [. You'll either need to disable trigraphs or do something to break them up like:
pcrecpp::RE re("^((\\w+):\\/\\/\\/?)?((\\w+):?(\\w+)?@)?([^\\/\\?:]+):?(\\d+)?(\\/?[^\\?#;\\|]+)?([;\\|])?([^\\?#]+)?\\??" "([^#]+)?#?(\\w*)");
|
2,360,116 | 2,360,186 | How to prevent paging for one program / process? | I have a program that requires much memory, like 2/3 of all the physical ram. After some runtime my operating system begins to swap the program to hdd. But I need the program to respond very fast all the time, so I need to prevent paging for that process.
How can you prevent the OS to swap one process?
Thanks for any h... | At the start of the program, call:
mlockall(MCL_CURRENT | MCL_FUTURE);
(If you do not have the source to the program, you'll have to debauch the process with ptrace to do this).
Be aware that this will increase the chances of memory allocations made by the process failing.
|
2,360,305 | 2,360,469 | Noob at C++: how to do an associative array of object => value? | I'm trying to create a global (singleton) class that can associate any type of object with an integer value. I was thinking of using a map<T*, int> variable, but was wondering if there was any other way to do it.
UPDATE: Here is a prototype of my class. Let me know what I'm doing wrong ! It compiles and work fine, but... | You should use a base class.
struct PortPin {
int port;
int pin;
bool is_valid;
PortPin() { is_valid = false; }
void associate( int in_port, int in_pin ) {
port = in_port;
pin = in_pin;
is_valid = true;
}
};
class A : public PortPin {
public:
A() {}
};
class B... |
2,360,563 | 2,360,575 | Why exception with this regular expression pattern (tr1::regex)? | I came accross a very strange problem with tr1::regex (VS2008) that I can't figure out the reason for. The code at the end of the post compiles fine but throws an exception when reaching the 4th regular expression definition during execution:
Microsoft C++ exception: std::tr1::regex_error at memory location 0x0012f5f4... | You need to double-escape your backslashes - once for the regex itself, a second time for the string they're in.
The one that starts with S works because \S is a valid regex escape (non-whitespace characters). The one that starts with N does not (because \N is not a valid regex escape).
Instead, use "\\\\SchemeVersion:... |
2,360,588 | 2,360,600 | C++ const iterator C2662 | Having problems iterating. Problem has to do with const correctness, I think. I assume B::getGenerate() should be const for this code to work, but I don't have control over B::getGenerate().
Any help is greatly appreciated.
Thanks in advance,
jbu
Code follows:
int
A::getNumOptions() const
{
int running_total = 0;
... | Well, if getGenerate is non-const, your iterator must be non-const. And if that's the case, your getNumOptions will also have to be non-const.
If getGenerate isn't under you control, there isn't anything else you can do. But if that method could be const, bring it up with whoever implemented that method; tell them it s... |
2,360,597 | 2,360,673 | C++ Exceptions questions on rethrow of original exception | Will the following append() in the catch cause the rethrown exception to see the effect of append() being called?
try {
mayThrowMyErr();
} catch (myErr &err) {
err.append("Add to my message here");
throw; // Does the rethrow exception reflect the call to append()?
}
Similarly, if I rewrite it this way, will bit ... | In both cases, since you catch by reference, you are effectively altering the state of the original exception object (which you can think of as residing in a magical memory location which will stay valid during the subsequent unwinding -- 0x98e7058 in the example below). However,
In the first case, since you rethrow ... |
2,360,649 | 2,365,474 | GC with C# and C++ in same solution | I have a solution consisting of a number of C# projects. It was written in C# to get it operational quickly. Garbage collections are starting to become an issue—we are seeing some 100 ms delays that we'd like to avoid.
One thought was to re-write it in C++, project by project. But if you combine C# with unmanaged C+... | I work as a .NET developer at a trading firm where, like you, we care about 100 ms delays. Garbage collection can indeed become a significant issue when dependable minimal latency is required.
That said, I don't think migrating to C++ is going to be a smart move, mainly due to how time consuming it would be. Garbage co... |
2,361,040 | 2,361,057 | Calling member level functions from a dynamic link library using pinvoke in C#? | How would I use DLLImport pinvoke to invoke a function i wrote in a class in an unmanaged DLL?
It always throws that the entry point doesn't exist in the dll.
EX:
class Foo
{
int __declspec(dllexport) Bar() {return 0;}
};
Bar is in the Foo class.
when I use pinvoke as:
[DLLImport("Test.dll")]
public static extern in... | Not easily...
To call a member function, the first "hidden" argument has to be a pointer to the C++ class who's member function you are calling.
And C++ functions are name mangeled, so you need to find the name mangeled name of the function you are calling.
In short: It is easier to create a C++/CLI wrapper of your C++... |
2,361,223 | 2,364,938 | crash - adding to a map and set STL - c++ | I have a cd , dvd. book media program. Currently, i am trying to add book information to a set. I am getting a nasty crash.
error: Unhandled exception at 0x00449d76 in a04xc.exe: 0xC0000005: Access violation reading location 0x00000014.
So, obviously its trying to access memory its not suppose to? just not sure why or... | The correct answer is to change the map to contain set objects, rather than pointers, as JonM says.
However, if you are constrained to store pointers, then you will need to manually create a new set when it's needed. For a new author, using allBooksByAuthor[author] will insert a new entry with a null pointer, which you... |
2,361,258 | 2,361,268 | Unable to open file from C++ DLL | I have an application for which GUI is written in C# and the logic is written in C++ DLL. The DLL should open a file to read data from it. I have the data.txt file in the same folder as the DLL. When I call
fopen("data.txt","r")
the value returned is NULL. What could be the problem? Please help me in this regard.
Tha... | The location of the dll file is not relevant. The path of your open must contain the complete path or the file will be opened to your applications current working directory.
|
2,361,290 | 2,361,489 | Moving objects from one Boost ptr_container to another | I want to move certain element from a to b:
boost::ptr_vector<Foo> a, b;
// ...
b.push_back(a.release(a.begin() + i)));
The above code does not compile because the release function returns boost::ptr_container_detail::static_move_ptr<...>, which is not suitable for pushing back.
How should I proceed?
EDIT: I found out... | boost::ptr_vector<Foo> a, b;
// transfer one element a[i] to the end of b
b.transfer( b.end(), a.begin() + i, a );
// transfer N elements a[i]..a[i+N] to the end of b
b.transfer( b.end(), a.begin() + i, a.begin() + i + N, a );
|
2,361,388 | 2,362,467 | How to workaround gcc-3.4 bug (or maybe this is not a bug)? | Following code fails with a error message :
t.cpp: In function `void test()':
t.cpp:35: error: expected primary-expression before '>' token
t.cpp:35: error: expected primary-expression before ')' token
Now I don't see any issues with the code and it compiles with gcc-4.x and MSVC 2005 but not with gcc-3.4 (which is st... | As mentioned elsewhere, that seems to be a compiler bug. Fair enough; those exist. Here's what you do about those:
#if defined(__GNUC__) && __GNUC__ < 4
// Use erroneous syntax hack to work around a compiler bug.
t4=translate(s.c_str()).template str<TheChar>();
#else
t4=translate(s.c_str()).str<TheChar>();
#endif
GC... |
2,361,517 | 2,361,543 | Problem with Visual C++ program-- can't find the Debug CRT | I have a friend who's taking over a Visual C++ project from me and is having trouble running it. It's a graphics application and it uses the Qt GUI library. The reason I mention this is because of the error below.
He can build and link the program using Visual Studio 2010, but when he runs it this message comes up in ... | If your friend doesn't have VS2005 installed, he will not have the debug runtime libraries for it. They're not part of the redistributable runtimes and IIRC, Microsoft prohibits you from distributing them yourself so you have to have VS2005 installed in order to get them.
I would suggest that he'd rebuild the affected ... |
2,361,523 | 2,361,535 | string to PCWSTR -> strange return(C++) | i'm really new to C++-programming and i've got an a problem with writing into a xml document.
I'm using a slightly changed example of xml outputter from msdn (http://msdn.microsoft.com/en-us/library/ms766497(VS.85).aspx).
HRESULT CreateAndAddTestMethodNode(string name)
{
HRESULT hr = S_OK;
IXMLDOMElement* pElement = N... | The result of c_str() gets destroyed along with the result string (when it goes out of scope). You will need to explicitly allocate memory for it.
|
2,361,530 | 2,361,550 | Error in compiling C++ code? | This is my test.cpp:
#include <iostream.h>
class C {
public:
C();
~C();
};
int main()
{
C obj;
return 0;
}
When I compile it using the command g++ test.cpp, I get this error message:
In file included from /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/backward/iostream.h:31,
from test.cpp:1:
... | You have declared the existence of the C constructor and destructor, but have not provided implementations. Try:
class C {
public:
C() {}
~C() {}
};
And, for C++ programs, use g++ to compile (as in your first attempt).
|
2,361,717 | 2,361,928 | Adding member functions to a Boost.Variant | In my C++ library I have a type boost::variant<A,B> and lots of algorithms getting this type as an input. Instead of member functions I have global functions on this type, like void f( boost::variant<A,B>& var ). I know that this can also be achieved with templates, but this is not suitable for my design.
I am very fin... | Another possibility: Use aggregation. Then you do not directly expose the boost.variant to the users of the library, giving you way more freedom for future improvements, and may simplify some debugging tasks by a significant amount.
General Advice:
Aggregation is less tightly coupled than inheritance, therefore better... |
2,361,750 | 2,362,744 | BOOST_FOREACH implicit use of reference? | I am wondering if there is any benefit to getting a reference to a vector prior to calling
BOOST_FOREACH or whether a method call which returns a reference will be automatically used? For example which of the two following loops will be equivalent to the third loop?
vector<float>& my_method();
void main()
{
// LO... | Looking through BOOST_FOREACH metaprogramming madness I see that the collection gets copied if it's
an rvalue,
a "lightweight proxy", which you can define for your types by specializing boost::foreach::is_lightweight_proxy.
Hence, lvalue is not copied. Instead, its pointer is taken as a temporary.
Crucial bit is this... |
2,361,873 | 2,362,206 | Forward declare a global type inside a namespace | I want to use an 3rd party library without using its header file. My code resides in its own namespace, therefore I can't use conventional forward declaration as I don't want to pollute the global namespace. Currently I have something like that:
3rd-party-library.h----
typedef struct {...} LibData;
void lib_func (LibD... | For a forward declaration to work, you need to forward declare an object in the proper namespace. Since the original object resides in the global namespace, you need to forward declare it in the global namespace.
If you don't like that, you can always wrap the thing in your own structure:
namespace foo {
struct libDat... |
2,361,927 | 2,361,940 | Pointer to [-1]th index of array | How does a pointer points to [-1]th index of the array produce legal output everytime. What is actually happening in the pointer assignment?
#include<stdio.h>
int main()
{
int realarray[10];
int *array = &realarray[-1];
printf("%p\n", (void *)array);
return 0;
}
Code output:
manav@work... | Youre simply getting a pointer that contains the address of that "imaginary" location, i.e. the location of the first element &realarray[0] minus the size of one element.
This is undefined behavior, and might break horribly if, for instance, your machine has a segmented memory architecture. It's working because the com... |
2,361,934 | 2,361,990 | Unable to write to console screen from C++ DLL | I want to print messages onto the console screen from a C++ DLL. The front end for this application is in C#. I used AllocConsole() fundtion to create a console from the C++ DLL. The window is being created but no messages were being printed when I try to print a message. Please help me fix this problem.
Thanks,
Rakesh... | You need to redirect your output stream to the newly created console.
freopen("conin$", "r+t", stdin);
freopen("conout$", "w+t", stdout);
freopen("conout$", "w+t", stderr);
|
2,361,944 | 2,365,834 | How to Save custom DockWidgets | I want to save my custom DockWidgets (inherited from QDockWidget) with the saveState() / restoreState() function my MainWindow provides.
I have two questions:
1. How can I save and restore my Dockwidgets?
- I already tried registering my custom DockWidgets as a QMetaType and implementing the default Constructor, copy C... | Did you read the QMainWindow::saveState documentation?
Are your objects uniquely named? (QObject::setObjectName)
As a side note, QObjects should NOT have a copy constructor, see Q_DISABLE_COPY
|
2,362,097 | 2,362,117 | Why is the size of an empty class in C++ not zero? |
Possible Duplicate:
C++: What is the size of an object of an empty class?
Why does the following output 1?
#include <iostream>
class Test
{
};
int main()
{
std::cout << sizeof(Test);
return 0;
}
| The standard does not allow objects (and classes thereof) of size 0, since that would make it possible for two distinct objects to have the same memory address. That's why even empty classes must have a size of (at least) 1.
|
2,362,152 | 2,362,179 | Assigning char value in one array to char value in another array | Sounds easy, but I've got a bug and I'm not sure what's causing it?
nopunccount = 0;
char *ra = new char[sizeof(npa)];
while (nopunccount <= strlen(npa)) {
ra[nopunccount] = npa[strlen(npa) - nopunccount];
nopunccount++;
}
ra never gets a value into it and I have verified that npa has char values to provide ... | nopunccountstarts as 0, so in the first iteration of the loop the character assigned to ra[0] is npa[strlen(npa)]. This is the terminating '\0' of that string. So the resulting string in ra starts with a '\0' and is therefore considered to be ending at that first byte by the usual string functions.
|
2,362,454 | 2,362,490 | Checking if an iterator references an item in a list | i just want to check, if the iterator points on an object in a list.
What's the cmd?
Thank you. :)
SkyThe
EDIT:
Hmm,.. ok i tried it.
Now there is a Error: "Expression: list iterators incompitable"
Maybe some code:
#include <list>
list<obj> list;
list<obj>::iterator it;
if(it != list.end()){ //here the error pops up w... | if (it!=collection.end()) std::cout << "Iterator points to data" << std::endl;
else std::cout << "Iterator does not point to data" << std::endl;
|
2,362,694 | 2,362,957 | How to represent this "tree" data? | Ive got some data (not that the data actually exists until after I solved this...) I need to be able to manipulate within my program. However I cant work out a suitable structure for storing this in.
The data represents a set of paths and nodes. There is one input (which may in some cases no be present) then a number o... | Seems you should really need more freeform structure than a tree.
Each node can have a number of nodes connected to it; each connection has a direction. Any node can have input or output attached. Enforcing no circular connections and only one input would be up to you upon tree creation and update.
The structures could... |
2,362,797 | 2,362,818 | Converting a char array to something that can be appended to a ostringstream | std::ostringstream parmStream;
char parmName[1024];
THTTPUrl::Encode(parmName, pParm->Name().c_str(), 1024);
//I want to add the value of the paramName to the parmStream worked b4 when parmName was a string but obv not now
parmStream << "&" << parmName + "=";
Gives me the following ..
error: invalid operands of t... | Try
parmStream << "&" << parmName << "=";
I haven't check your code but it looks like the error is pointing to the fact you are trying to add the "=" to a standard C string.
|
2,362,905 | 2,363,340 | How to build a static C++ library using Xcode? | I am trying to create a static library in Xcode using C++ ( All my files are .h or .cpp ).
I tried deleting main.cpp and then adding a target to my project to build a "Static" library. Since I'm not using Cocoa, I assumed that I needed to add a BSD Static Library, but I have tried other static library options with no a... | Are your source files checked against the new target?
Otherwise, open the Build window, unfold the messages pane so you can see what the compiler is actually doing and where it places the .a file (if at all). That might help you to track down what's going on.
|
2,363,219 | 2,363,514 | vector assignation on uninitialized memory chunk and similar issues | vector<vector<string> > test for example.
g++, you can do
test.reserve(10);
test[0] = othervector;
test[9] = othervector;
It doesn't crash. Theory says you shouldn't do it like that because you are assigning a vector to a chunk of memory that believes it is a vector.
But it works just like the next one:
#include <st... | "Are there more cases like this one in the rest of the containers?"
Tons. And I'm not kidding. I can come up with literally thousands of them, all over the standard.
For instance, almost all functions that take an iterator range can break in nasty ways if you pass in two unrelated iterators. They might also "work" sile... |
2,363,225 | 2,363,744 | Controlling USB Access of Windows CE6 | I am looking to find a way to programatically (C++) control/secure access to the USB ports on a Windows CE device that will only have a single login, and then be left running a real-time application.
Ideally, being able to have a password entered into the running application, which then opens up/enables USB functionali... | You need to modify the USB host driver to ask for the authenticaion from the user (or better yet have it coordinate with some authentication app/servce). You could then make it as complex as you'd like, associating users with device classes, device vendors or even down to a device serial number.
The driver source ship... |
2,363,284 | 2,514,216 | IHostAssemblyStore::ProvideAssembly causes exception "The located assembly's manifest definition does not match the assembly reference" | PostSharp 2.0 includes a CLR host and implements IHostAssemblyStore::ProvideAssembly.
From managed code, I invoke:
Assembly.Load("logicnp.cryptolicensing, Version=3.0.0.0, Culture=neutral,
PublicKeyToken=4a3c0a4c668b48b4")
My implementation of IHostAssemblyStore::ProvideAssembly receives the following... | The question has been answered on http://social.msdn.microsoft.com/Forums/en/clr/thread/93efa20f-5423-4d55-aa3d-dadcc462d999.
Basically, it is a documentation bug:
Instead of returning ERROR_FILE_NOT_FOUND from IHostAssemblyStore::ProvideAssembly (as specified in documentation), the host implementation should return CO... |
2,363,332 | 2,363,349 | No match for call to '(std::pair<unsigned int, unsigned int>) (unsigned int&, unsigned int)' | I don't know what's wrong with the follwing code, it should read numbers and put their value with the position together in a vector of pairs and then sort them and print out the positions. I removed the part with sort - i thought the problem was there, but i received an error on compilation again.
#include <iostream> ... | The problem is temp(t, i+1);
You need to set the first and second manually
temp.first = t;
temp.second = i + 1;
Alternatively you can declare temp inside the loop (probably what I'd do).
for(i=0;i<n;i++)
{
cin >> t;
pair<unsigned int,unsigned int> temp(t, i+1);
v.push_back(temp);
}
Or a second alter... |
2,363,363 | 2,363,447 | Calling virtual functions inside member functions | I'm reading Thinking in C++ by Bruce Eckel. In Chapter 15 (Volume 1) under the heading "Behaviour of virtual functions inside constructor", he goes
What happens if you’re inside a
constructor and you call a virtual
function? Inside an ordinary member
function you can imagine what will
happen – the virtual call... | You are wrong - a further derived class could override some of the virtual functions, meaning that a static call would be wrong. So, to extend your example:
class C : public B
{
public:
// Not overriding B::add.
void subadd() { std::cout << "C::subadd\n"; }
};
A *a = new C;
a->add();
This dynamically calls B:... |
2,363,436 | 2,363,466 | Why can't I create a std::stack of std::ifstreams? | Why does the following not work:
#include <iostream>
#include <fstream>
#include <stack>
std::stack<std::ifstream> s;
-PT
| std::stack (like all STL containers) requires that its contained type be "assignable". In STL-speak, that means that it must have a copy constructor and an operator=. std::ifstream has neither of these.
You can imagine why you would not want to be able to copy and assign I/O streams; the semantics of what should happen... |
2,363,500 | 11,921,312 | Does anyone have an easy solution to parsing Exp-Golomb codes using C++? | Trying to decode the SDP sprop-parameter-sets values for an H.264 video stream and have found to access some of the values will involve parsing of Exp-Golomb encoded data and my method contains the base64 decoded sprop-parameter-sets data in a byte array which I now bit walking but have come up to the first part of Exp... | Exp.-Golomb codes of what order ??
If it you need to parse H.264 bit stream (I mean transport layer) you can write a simple functions to make an access to scecified bits in the endless bit stream. Bits indexing from left to right.
inline u_dword get_bit(const u_byte * const base, u_dword offset)
{
return ((*(base +... |
2,363,715 | 2,363,738 | Questions Regarding the Implementation of a Simple CPU Emulator | Background Information: Ultimately, I would like to write an emulator of a real machine such as the original Nintendo or Gameboy. However, I decided that I need to start somewhere much, much simpler. My computer science advisor/professor offered me the specifications for a very simple imaginary processor that he create... | Parse the original code into an array of integers. This array is your computer's memory.
Use bitwise operations to extract the various fields. For instance, this:
unsigned int x = 0xfeed;
unsigned int opcode = (x >> 12) & 0xf;
will extract the topmost four bits (0xf, here) from a 16-bit value stored in an unsigned int... |
2,363,736 | 2,365,555 | How do I store the value of a register into a memory location pointed to by a pointer? | I have the following code:
void * storage = malloc( 4 );
__asm
{
//assume the integer 1 is stored in eax
mov eax, storage //I've tried *storage as well but apparently it's illegal syntax
}
/* other code here */
free(storage);
However, in the code, when I dereference the storage pointer ( as in *(int *)storag... | Are you sure you know what you really need? You requested the code that would store the register value into the memory allocated by malloc ("pointed to by a pointer"), i.e. *(int*) storage location, yet you accepted the answer that stores (or at least attempts to store) the value into the pointer itself, which is a com... |
2,363,810 | 2,363,841 | Does anyone know what the "-FC" option does in gcc g++? | Does anyone know what the "-FC" option does in g++?
I have it in my SConstruct script that builds the command line g++ command, I have searched google
| You know, if all fails, read the manual :-).
Fdir
Add the framework directory dir to the head of the list of directories to be searched for header files. These directories are interleaved with those specified by -I options and are scanned in a left-to-right order.
[...]
Source: http://gcc.gnu.org/onlinedocs/gcc-4.... |
2,363,888 | 2,363,923 | If I allocate memory in one thread in C++ can I de-allocate it in another | If I allocate memory in one thread in C++ (either new or malloc) can I de-allocate it in another, or must both occur in the same thread? Ideally, I'd like to avoid this in the first place, but I'm curious to know is it legal, illegal or implementation dependent.
Edit: The compilers I'm currently using include VS2003,... | Generally, malloc/new/free/delete on multi threaded systems are thread safe, so this should be no problem - and allocating in one thread , deallocating in another is a quite common thing to do.
As threads are an implementation feature, it certainly is implementation dependant though - e.g. some systems require you to l... |
2,363,899 | 2,364,242 | Is there a way to get an event from windows on every new process that is started? | I want to get a notification each time a new process is started by the operating system.
Note that I need to that in native code (I know it can be done in managed code using System.Management members).
Extra points if there is a way to get it before the process starts running :) (i.e in during its initialization)
Tha... | The problem with using a driver is that you will require permission to install it, but otherwise I think is the safest method.
In user space you can try to create a window hook which will work if such application uses a windows, but is otherwise quite obnoxious.
On the other hand you can try to use WMI, which is the un... |
2,364,077 | 2,364,874 | serialize in .NET, deserialize in C++ | I have a .NET application which serializes an object in binary format.
this object is a struct consisting of a few fields.
I must deserialize and use this object in a C++ application.
I have no idea if there are any serialization libraries for C++, a google search hasn't turned up much.
What is the quickest way to acco... | If you are using BinaryFormatter, then it will be virtually impossible. Don't go there...
Protocol buffers is designed to be portable, cross platform and version-tolerant (so it won't explode when you add new fields etc). Google provide the C++ version, and there are several C# versions freely available (including my o... |
2,364,312 | 2,364,750 | Fast 64 bit comparison | I'm working on a GUI framework, where I want all the elements to be identified by ascii strings of up to 8 characters (or 7 would be ok).
Every time an event is triggered (some are just clicks, but some are continuous), the framework would callback to the client code with the id and its value.
I could use actual stri... | Are you sure this is not premature optimisation? Have you profiled another GUI framework that is slow purely from string comparisons? Why are you so sure string comparisons will be too slow? Surely you're not doing that many string compares. Also, consider strcmp should have a near optimal implementation, possibly ... |
2,364,412 | 2,364,473 | Executing a command from C++, What is expected in argv[0]? | I am using execv() to run commands from /bin/ such as 'ls', 'pwd', 'echo' from my c++ program, and I am wondering what value I should provide in argv[0];
const char * path = getPath();
char ** argv = getArgs();
execv(path,argv);
| argv[0] is supposed to be the program name. It's passed to the program's main function. Some programs differentiate their behavior depending on what string argv[0] is. For example the GNU bash shell will disable some of its features if called using sh instead of bash. Best give it the same value that you pass to path. ... |
2,364,574 | 2,364,652 | Receiving response(s) from N number of clients in reply to a broadcast request over UDP | I am implementing a kind of IP finder for a particular type of network multimedia device.
I want to find out all the alive devices of that type in the LAN, with their IP address and other details.
The device has its own way of device discovery.
It works as follows:
A client sends a broadcast request over the LAN via... |
How many times will I have to call recvfrom()?
When will I come to know that I have handled the response from all the devices/servers?
If you don't know the number of devices/servers, you cannot know how many times you will need to call recvfrom() or when you've handled all the responses.
You might consider using... |
2,364,662 | 2,364,680 | For how long the iterator returned by std::set.find() lives? | I need to keep track of std::set element by saving the iterator returned by set.find().
My questions is does insertion and removing other elements invalidates the obtained iterator? From a simple test I did I can see it is not, but I'd like to ensure this feature is by design.
| It never invalidates iterators or pointers/references to the elements. Only if you remove the element itself does the iterator or pointer/reference become invalid.
23.1.2/8:
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only itera... |
2,364,774 | 2,372,507 | Why do I need to compile DateTime in boost if I am not using to_string or from_string? | When compiling a Visual Studio 2005 project that references a mix of c++ managed/unmanaged code, I get the following error:
1>LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc80-mt-1_42.lib'
I have followed the Getting Started Guide. Of relevance is this snippet:
"Boost.DateTime has a binary compon... | Project compiles and links cleanly after the following troubleshooting:
I defined BOOST_LIB_DIAGNOSTIC - to see what diagnostic output I could get from the auto linker. Not too informative:
1>Linking to lib file: libboost_date_time-vc80-mt-1_42.lib
1>LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc80... |
2,365,031 | 2,366,070 | Does Hinnant's unique_ptr implementation incorrectly fail to convert derived-to-base in this case? | I'm currently trying to use Howard Hinnant's unique_ptr implementation, and am running into a compile error. Here is some sample code:
struct Base {};
struct Derived : public Base {};
void testfun(boost::unique_ptr<Base>);
void test()
{
unique_ptr<Derived> testDerived;
unique_ptr<Base> testBase(move(testDer... | Further research has lead me to this note, leading me to believe that this is a known limitation of the implementation:
3 of the tests currently fail for me (fail at compile time,
supposed to compile, run and pass). These are all associated with the
converting constructor specified in [unique.ptr.single.ctor]. When
the... |
2,365,156 | 2,365,275 | adding string objects to an array via loop | What i'm trying to do is create a template array class that will store values of a data type into an array. I have it working fine with int values, however working with string objects things start to break down.
I've taken out the block of code and tried it on it's own and I do get the same error. I'm sure I've learnt ... | string s[stringSize]; is illegal because stringSize is not a constant. You must either use dynamic memory (i.e. string* s = new string [stringSize];), include stringsize as a template argument (don't do this, it doesn't actually solve the problem), use a fixed size value, or use an existing structure (I'd suggest vect... |
2,365,180 | 2,393,158 | Socket connect() always succeeds (TCP over ActiveSync) | I'm using TCP/IP over ActiveSync to connect from Windows CE device to Windows XP desktop.
The WinSock connect() function always succeeds, no matter whether desktop server application is actually running.
The following simplified code demonstrates this issue:
#include "stdafx.h"
#include <Winsock2.h>
int _tmain(int arg... | So, I did not find the way to check if this is 'real' connection, other than to ignore this issue and try to use this connection. If it is not 'real', the communication will fail.
|
2,365,212 | 2,365,270 | Cannot explain why std::istream_iterator set std::ios_base in error state | I am trying to conert a vector into a stream and back.
While the first part works without issues, the last line of the following code put std::ios_base is an error state. Have you got any idea why it is so?
Apparently myVecOut is equal to myVec after the code executes....
std::vector<double> myVec( 3 );
std::st... | It's set into fail state, because copy does not know how many items to read. It reads as long as the stream is in a .good() non-.fail() state. While skipping the last space, it hits the end, and sets both eof (because it tried to read beyond the end) and fail (because it could not read the double it wanted to).
Call .... |
2,365,531 | 2,365,780 | Can C++ projects use T4 in Visual Studio 2010? | T4 did not work for C++ projects in Visual Studio 2008 since it did not use msbuild for C++ projects. (Yes there were workarounds) In Visual Studio 2010, C++ projects uses MsBuild, so do anyone know if C++ projects can use T4 in the same way as C# or VB?
| The main integration mechanism for T4 in C# and Visual Basic projects is the TextTemplatingFileGenerator custom tool. Although in Visual Studio 2010 C++ projects now use MSBuild, they still don't support custom tools. As a workaround, you could use T4 Toolbox, which allows you to put a .tt file in a C# or Visual Basic ... |
2,365,599 | 2,365,928 | C++: High speed stack | As far as I assume, std::stack and all such 'handmade' stacks work much slower than stack which is applications one.
Maybe there's a good low-level 'bicycle' already? (Stack realization).
Or it's a good idea to create new thread and use it's own stack?
And how can I work directly with application stack? (asm {} only?)
| The only way in which std::stack is significantly slower than the processor stack is that it has to allocate memory from the free store. By default, it uses std::deque for storage, which allocates memory in chunks as needed. As long as you don't keep destroying and recreating the stack, it will keep that memory and not... |
2,365,612 | 2,370,831 | Qt C++ WebKit windowCloseRequested Signal | I am trying to connect QWebpage::windowCloseRequested() to a slot that just prints out a debug message. When I call window.close(); in JavaScript it doesn't bubble the signal up or call the slot...
connect(webView->page(), SIGNAL(windowCloseRequested()),this, SLOT(windowCloseRequested()));
The slot is setup, it is in ... | Attaching an onclick to an <a> tag is ... questionable. Use a span, and blammo, it works. This is why you should take breaks when coding, or else you make really dumb mistakes that waste time.
|
2,365,624 | 2,365,645 | Should I delete the string members of a C++ class? | If I have the following declaration:
#include <iostream>
#include <string>
class DEMData
{
private:
int bitFldPos;
int bytFldPos;
std::string byteOrder;
std::string desS;
std::string engUnit;
std::string oTag;
std::string valType;
int idx;
public:
DEMData();
DEMData(const DEMDat... | Your destructor only has to destroy the members for which you allocate resources. so no, you don't "delete" strings.
You delete pointers you allocate with new
Your destructor doesn't have to be more than
~DEMData()
{
}
|
2,365,663 | 2,429,591 | Run time determination of compilation options | I need to be able to determine at run time what compilation options were use to build the executable. Is there a way to do this?
EDIT: I'm particularly interested in detecting optimization settings. The reason is that I'm writing commercial software that must run as fast as possible. While I am just modifying and testi... | To do this right you will need to create an additional configuration called, say "SuperOptimised". You now have the standard configurations ("Debug" and "Release") and a third "SuperOptimised". The problem with this is that it makes the configuration management of the project much harder, to change a common setting bet... |
2,365,900 | 2,365,937 | C++: create betwen-startups relevent functor list | I create something like a list of functors (functions pointers). Then I write them in binary form into file. The problem is, that, functor - is a simple function pointer. (correct me if I'm wrong.) But the address of function is different from one run to another.
So, the question - is there any way to create list of fu... | I'd recommend some kind of paired data structure with an identifier on one side and the function pointer on the other. If there are enough of them something like a map:
typedef void (*fptr_t)(); // or whatever your function pointer type is
std::map<std::string, fptr_t> fptr_map;
Your application should build this map ... |
2,366,067 | 2,366,085 | Is there a difference in declaring instances of inherited classes in these different ways? | If I have a class called "Animal", and a derived class "Bird : public Animal", I can create a Bird these two ways:
Animal *sparrow = new Bird;
Bird *sparrow = new Bird;
Both compile fine and work as expected. Are they equivalent? Should I prefer one over the other?
| The line, in itself, doesn't demonstrate the difference. However, assume Bird declares a method Fly that doesn't exist on Animal. You wouldn't be able to do:
Animal* a = new Bird;
a->Fly();
on the other hand, this is legal:
Bird* b = new Bird;
b->Fly();
The distinction here is a result of the fact that C++ is a stati... |
2,366,072 | 2,366,112 | How do I use a manipulator to format my hex output with padded left zeros | The little test program below prints out:
And SS Number IS =3039
I would like the number to print out with padded left zeros such that the total length is 8. So:
And SS Number IS =00003039 (notice the extra zeros left padded)
And I would like to know how to do this using manipulators and a stringstream as show... | Have you looked at the library's setfill and setw manipulators?
#include <iomanip>
...
lTransport << "And SS Number IS =" << std::hex << std::setw(8) ;
lTransport << std::setfill('0') << i << '\n';
The output I get is:
And SS Number IS =00003039
|
2,366,461 | 2,366,533 | STL Structures in Static Memory 'Losing' Data Across Threads | I'm writing a multi-threaded demo program using pthreads, where one thread loads data into an STL queue, and another thread reads from it. Sounds trivial, right? Unfortunately, data pushed into the queue is vanishing. I'm not new to multithreading, nor am I unfamiliar with memory structures - however, this has me st... | Header guards protect from multiple inclusion per translation unit. However, different translation units will re-include them.
In your case, it seems they are each getting their very own static queue and mutex. Also, consider even if you were correct: Without re-including the header, the translation unit would have no ... |
2,366,468 | 2,366,514 | SetWindowsHookEx() , the hook is not maintained? (possibly) | I am trying to learn the Windows API. Currently I am having a lot of trouble trying to get hooks to work. I have some sample code I have been messing around with for a few days - it has a GUI written in C# or something, and a dll in C++. The dll has this function externalized:
bool __declspec(dllexport) InstallHook(){
... | I suspect this is because you have console application and system does not send notifications about activating, creating, moving, etc. of console windows. Try to make it normal windows application.
|
2,366,690 | 2,366,725 | storing a pointer to a member function | I'm wrapping an existing C API to make it easier to use in my VS2008 C++ program. The C API is expecting an array of "TABLE_ENTRY" structures that include a function pointer as in the code below.
But, I'm having difficulty storing a pointer to a member function in the function pointer.
Can anybody point out what I may... | boost::bind creates a functor, i.e. an instance of a class that implements operator(). This is not interchangeable with plain C function pointers.
|
2,366,739 | 2,366,788 | Create files from file names in another file C++ | I am working on sorting several large files in C++. I have a text file containing the names of all the input files, one on each line. I would like to read the file names in one at a time, store them in an array, and then create a file with each of those names. Right now, I am using fopen and fread, which require charac... | As Don Knuth said, premature optimization is the root of all evil.
Your filenames are definitely not the bottleneck! Just use std::string for them.
You'd need to replace fp = fopen(tempfname[i], "w"); with fp = fopen(tempfname[i].c_str(), "w"); however.
|
2,366,879 | 2,366,998 | operator new overloading and alignment | I'm overloading operator new, but I recently hit a problem with alignment. Basically, I have a class IBase which provides operator new and delete in all required variants. All classes derive from IBase and hence also use the custom allocators.
The problem I'm facing now is that I have a child Foo which has to be 16-byt... | This is a possible solution. It will always choose the operator with the highest alignment in a given hierarchy:
#include <exception>
#include <iostream>
#include <cstdlib>
// provides operators for any alignment >= 4 bytes
template<int Alignment>
struct DeAllocator;
template<int Alignment>
struct DeAllocator : virtu... |
2,367,171 | 2,367,255 | SIMD Sony Vector Math Library in OS X with C++ | I'm currently writing a very simple game engine for an assignment and to make the code a lot nicer I've decided to use a vector math library. One of my lecturers showed me the Sony Vector Math library which is used in the Bullet Physics engine and it's great as far as I can see. I've got it working on Linux nicely but ... | Which compiler are you using on OS X ? There are 4 to choose from in the standard Xcode 3.2 install and the default is gcc 4.2. You might be better off trying gcc 4.0.
|
2,367,180 | 2,367,201 | Change the address of a member function in C++ | in C++, I can easily create a function pointer by taking the address of a member function. However, is it possible to change the address of that local function?
I.e. say I have funcA() and funcB() in the same class, defined differently. I'm looking to change the address of funcA() to that of funcB(), such that at run ... | No. Functions are compiled into the executable, and their address is fixed throughout the life-time of the program.
The closest thing is virtual functions. Give us an example of what you're trying to accomplish, I promise there's a better way.
|
2,367,202 | 2,367,232 | C++ Pointer in Function | I know that technically all three ways below are valid, but is there any logical reason to do it one way or the other? I mean, lots of things in c++ are "technically valid" but that doesn't make them any less foolish.
int* someFunction(int* input)
{
// code
}
or
int *someFunction(int *input)
{
// code
}
or... | All are equivalent. Choose the flavor that suits you best. Just be sure whichever you chose, you apply that choice in every case. Where your stars and curly braces go is far less important than putting them in the same place every time.
Personally, I prefer int* someFunction(int* input);, but who cares?
|
2,367,293 | 2,367,374 | turning a std::vector of objects in to an array of structures | I have a VS2008 C++ program where I'm wrapping a C API for use in a C++ program. The C API is expecting an array of TABLE_ENTRY values as shown below.
Other than copying the data from each of the MyClass structures in to a new TABLE_ENTRY structure in MyClassCollection::GetTable(), is there a way to get the functionali... | I'd go for copying to a vector<TABLE_ENTRY> and pass &entries[0] to the C API.
And, I would not store the TABLE_ENTRYs in your C++ class. I'd only make them just as you call the API, and then throw them away. That's because the TABLE_ENTRY duplicates the object you copy from, and it is storing a direct char* pointer to... |
2,367,395 | 2,367,415 | Global function header and implementation | how can I divide the header and implementation of a global function?
My way is:
split.h
#pragma once
#include <string>
#include <vector>
#include <functional>
#include <iostream>
void split(const string s, const string c);
split.cpp
#include "split.h"
void split(const string& s, const string& c){
...
}
main.cpp
/... | In header file use std:: namespace qualifier - std::string
|
2,367,487 | 2,367,546 | Why isn't copy constructor being called like I expect here using map? | I am having problems using my custom class with a std::map. The class dynamically allocates memory for members, and I do not want to use pointer in the map because I want to ensure that the class takes care of deleting all allocated memory. But the problem I am having is after I add item to map, when that block of co... | myClass needs a custom assignment operator, in addition to the copy constructor. So when you make an assignment, you'll leak the original value on the left, and eventually double delete the value on the right.
|
2,367,521 | 2,367,576 | SendInput (C++) is not working | The return value is 4 and I'm running Visual Studio in administrative mode so permissions should be ok. I don't see anything typed out though. Any help? I'm using Windows 7 x64.
INPUT input[4];
input[0].type = INPUT_KEYBOARD;
input[0].ki.wVk = 0;
input[0].ki.wScan = 'a';
input[0].ki.dwFlags = KEYEVENTF_SCANCODE;
input... | You need to send both KeyDown and KeyUp events for each key.
To send a KeyUp event, set dwFlags to KEYEVENTF_KEYUP.
Also, you need to use wVk instead of wScan. (wScan is only used with KEYEVENTF_UNICODE)
|
2,367,597 | 2,367,679 | Null checking the null object pattern | The main goal of the Null Object Pattern is to ensure that a usable object is provided to the client. So we want to replace the following code...
void Class::SetPrivateMemberA() {
m_A = GetObject();
}
void Class::UseA() {
if (m_A != null) {
m_A.Method();
} else {
// assert or log the error... | You're correct that, if you're sure you're never returning nulls, just skip the null check before calling the method in your first implementation. Likewise, if you do need to do something special in the case that UseA() needs to do something differently on a null object, that you need to explicitly check for a null ob... |
2,367,891 | 2,367,920 | adding to a set STL - C++ | I have a media program. i am adding CD,dvd,book info. I managed to get the book info added to the set. I am now adding the CD info. I have most of the Cd info added but i have a seperate function for adding band members. thats where i need help!
I am getting a cast error: error C2440: 'type cast' : cannot convert from ... | In Library::addBandMember you're trying to cast a pointer to a class type
you need to cast to CD* not CD
And you probably don't want the 2 const in
const Item* const musicCD
since you want to modify the musicCD !
finally your CD::addBandMember method doesn't seem to add a band member but replace it.
|
2,367,911 | 2,368,021 | Multithreaded application concept | I have a small architecture doubt about organizing code in separate functional units (most probably threads?). Application being developed is supposed to be doing the following tasks:
Display some images on a screen (i.e. slideshow)
Read the data from external device through the USB port
Match received data against t... | A lot of this depends on how much is involved in performing 3 (Do some data analysis.) and 4 (Plot analyzed data.)
My instincts would be:
Definitely have a separate thread for reading the data off the USB. Assuming for a moment that 3 is dependent on reading the data, then I would do 3 in the same thread as reading the... |
2,367,969 | 2,367,978 | What would the evaluation order of x = x++ + ++x; be? |
Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
In Java the evaluation order is specified to be left-to-right. Is this the case for C and C++ as well, or is it implementation dependent? I do remember that the evaluation order is unspecified for function arguments,... | It is unspecified which of the arguments to + is evaluated first - but that doesn't even matter, because in C and C++, modifying the same object twice without an intervening sequence point is completely undefined behaviour.
Here you're modifying x three times without an intervening sequence point, so you're well into h... |
2,368,231 | 2,368,258 | makefiles and using eclipse for Linux programs and C++ | can anyone point me in the direction of a good tutorial on how makefiles work and also how to start a basic program from scratch using eclipse? I am using eclipse version 3.4.1 for fedora and C++. Thanks in advance.
| CDT is the plugin used in eclipse for C++ development. Follow the link for a quick project creation tutorial. The same link has some information on how Eclipse uses makefiles.
|
2,368,424 | 2,368,438 | Sorting a vector using threads | Are the vectors defined in the C++ STL re-entrant or thread safe?
Can I use two threads and work(in this case sort) on two halfs of a vector without using a mutex?
For example:
int size = (Data_List.size())/2;
Thread A()
{
................ // Do we need to lock Data_list with a mutex
sort(Data_List.begin(),Data_List... | As long as the threads are working on different regions of memory and your comparison function only works with that memory and local variables, you should be ok. Essentially, you are "locking" each half of the table by dividing the work between the threads and only letting the thread work on its half of the data.
|
2,368,679 | 2,368,770 | Using a std::string iterator to find the start and end of it's string | Given just a std::string iterator, is it possible to determine the start and end points of the string? Supposing that I don't have access to the string object and so cannot call string.begin() and string.end(), and all I can do is increment or decrement the iterator and test the value.
Thanks,
Phil
| The short answer is no. The long answer is, because iterators aren't expected to know about the containers or ranges that are iterating over, they are only expected to
Be able to jump to the next element (inc or dec to next or prev)
Dereference themselves so as to reveal a reference to the value they are pointing to
A... |
2,368,728 | 2,368,794 | Can normal maps be generated from a texture? | If I have a texture, is it then possible to generate a normal-map for this texture, so it can be used for bump-mapping?
Or how are normal maps usually made?
| Yes. Well, sort of. Normal maps can be accurately made from height-maps. Generally, you can also put a regular texture through and get decent results as well. Keep in mind there are other methods of making a normal map, such as taking a high-resolution model, making it low resolution, then doing ray casting to see what... |
2,368,772 | 2,368,938 | How to lock Queue variable address instead of using Critical Section? | I have 2 threads and global Queue, one thread (t1) push the data and another one(t2) pops the data, I wanted to sync this operation without using function where we can use that queue with critical section using windows API.
The Queue is global, and I wanted to know how to sync, is it done by locking address of Queue?
I... | One approach is to have two queues instead of one:
The producer thread pushes items to queue A.
When the consumer thread wants to pop items, queue A is swapped with empty queue B.
The producer thread continues pushing items to the fresh queue A.
The consumer, uninterrupted, consumes items off queue B and empties it.
Q... |
2,369,288 | 2,370,374 | Image conversion : RGBA to RGB | assuming i had RGBA (32 bits) output from frame-grabber, with alpha channel unused (values retained while filled by frame-grabbers), is there any effective conversion method to RGB (24 bits) ?
I am dealing with 5 MegaPixels streaming images so speed does matter too.
keep in mind that data in alpha channel can be discar... | Just copy the data and skip the unused alpha bytes.
If speed is important for you, you may want to use SSE or MMX and use the built-in bit-shuffling instructions. That is usually a bit faster than ordinary c-code.
5 megapixels doesn't sound like that much of data unless you have to do it at 100fps though.
|
2,369,387 | 2,369,391 | Tinyxml to print attributes | I'm trying to get std::string from attribute's value with TinyXml.
The only thing I can get is a const char * val, and I can't find any way to convert from const char * to a std::string.
so two possible answers to that:
1. How to get a string of an attribute with TinyXml?
2. How to convert const char * val to string va... | std::string has a constructor that takes char const*. You don't need a char* for that.
std::string str = data->Attribute("some_name");
However, be aware that std::string doesn't like NULL values, so don't give it any.
|
2,369,392 | 2,369,479 | Inheriting both abstract class and class implementation in C++ | I hope this is a simple question.
Can I inherit both an abstract class and it's implementation? That is, can the following be made to work?
class A {
virtual void func1() = 0;
}
class B {
void func1() { /* implementation here */ }
}
class C : public A, public B {
}
I've tried a few variations, and am gettin... | As Kirill pointed out: Your premise is wrong.
Class B in your example does not inherit class A (it needs to be declared to do that first).
Thus, B.func1() is something entirely different to A.func1() for the compiler. In class C it is expecting you to provide an implementation of A.func1()
Somebody above posted somethi... |
2,369,416 | 2,369,442 | Creating a Cross-Platform C++ Library | I wanted to create a cross-platform 2D game engine, and I would like to
know how to create a cross-platform project with Makefile, so I can compile it to the platforms I choose with custom rule for any platform.
I'm working on the windows enviroment with Visual C++ Express 2008, so it would be nice
if I can use Visual ... | Don't use make, use a cross-platform tool like cmake, it will take care of the platform-specific generation for you. Like on Windows, it will generate the project files to use Visual Studio; on Linux, it will generate the GNU make files for you. You can set it up to find the right versions of the right libraries and ... |
2,369,431 | 2,369,709 | What is the use of a C++ class containing an "implementation" and "interface" pointer to itself? | I'm studying some source codes and I'm just wondering why a class (or classes) is often implemented this way:
class EventHandler
{
...
EventDispatcher* m_Dispatcher;
virtual bool ProcEvent( EventHandler* Sender, int Task, int Event, void* Param );
...
};
class ClassA: public EventHandler
{
...
ClassA* m_I... | I am afraid the names used do not have the usual meaning, so without examples of what is put in or how they are used, it's going to be difficult to guess.
There are 2 design patterns that you should check, that make heavy use of this kind of self-recursion (at class level*):
The Decorator Pattern
The Composite Pattern... |
2,369,525 | 2,369,772 | how to tell if a stream is closed in C before calling fclose() | I have a failing C program, and i've narrowed it down to a fork()ed child trying to close stdout and stderr, which were closed by its parent process before calling fork() - i assume those streams were passed on to the child process.
how can i tell if a stream is closed in C before attempting to close it using something... | C programs on UNIX expect to have a file descriptors 0, 1 and 2 open when they are started. If you do not want them to go anywhere, open /dev/null and dup it to those file descriptors.
|
2,369,541 | 2,369,593 | Where is `%p` useful with printf? | After all, both these statements do the same thing...
int a = 10;
int *b = &a;
printf("%p\n",b);
printf("%08X\n",b);
For example (with different addresses):
0012FEE0
0012FEE0
It is trivial to format the pointer as desired with %x, so is there some good use of the %p option?
| They do not do the same thing. The latter printf statement interprets b as an unsigned int, which is wrong, as b is a pointer.
Pointers and unsigned ints are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems beco... |
2,369,545 | 2,369,632 | Can I catch an exception relating to a .DLL file not been found | I have a 3rd party component that includes a .LIB and .DLL file. In order to use the component I link the .LIB into my C++ program, and distribute the .DLL with application. The functionality provided is very specific, and only relevent to a small sub-set of my users, but distributing the .DLL incurs a license fee.
O... | There is no way to stop the binding after linked with the dll.
The only way that youo have is if you dynamically load the
dll during runtime.
Dll resolving is done before your exe starts running.
Code could look somehow like that.
If this does not work for your third party dll you could write an own dll that wrapps th... |
2,369,553 | 2,369,605 | iphone compiler inherited templated base classes with passed through type not being expanded in time (just look) | Try this out:
template <typename T>
class Base
{
public:
int someBaseMember;
};
template <typename T>
class Test: public Base<T>
{
public:
void testFunc()
{
someBaseMember = 0;
}
};
In vc++ and the psp compiler (and an... | The error that you are getting is correct (the other compilers should not accept the code and are doing so erroneously); the variable someBaseMember depends on the template instantation of Base<T>, but this dependence has not been expressed in your usage, and hence the compiler is correct in attempting to resolve it in... |
2,369,629 | 2,369,649 | An unhandled win32 exception occurred in MyApp.exe | WinXP used. When I click the default cross icon to close my application. The win form of my application disappeared, but MyApp process still alive in the processes list when I open the task manager window. About 5 seconds later, throw out the unhandled win32 exception error.
Where can I set the break point? I don't kn... |
Attach your Vc to the program.
Enable catch of all exeptions.
Close your application and see where it stops.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.