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,189,682 | 4,189,688 | Calling an "external" function from a class method | I have a function that I want to call from within a class method. The function is in a file called mergeSort.cpp. Here is a snippet of the .cpp file that the class is implemented in:
// other includes
#include "mergeSort.cpp"
// other methods
void Servers::sortSites() {
mergeSort(server_sites.begin(), server_sites.en... | You have to use the "::" external namespace resolutor:
::mergeSort(...);
This tells the compiler to look for the function in the outer namespace. If this particular function is defined in another namespace or class, you have to specify it explicitly:
Namespace::mergeSort(...);
If you don't want to have to resolve the... |
4,189,762 | 4,189,795 | using template classes as method parameters | I've two template classes: Class1< S > and Class2< T >. In Class2< T >, there's a method that has as parameter a pointer to an object of Class1< S >. Should I then re-define class2< T > to class2< S, T >? or is there any other best solution?
The problem, is that I might have new methods referring to objects of other te... | The type of object that Class2::doSomething acts upon should not have to be part of Class2's type. So make Class2::doSomething() a Member Function Template:
template < class T >
class Class2{
public:
...
template<class S> Class2<T> * doSomething(Class1<S> * );
...
private:
...
}... |
4,189,885 | 4,190,046 | Why is explicitly returning 0 from main() considered good practice? |
Possible Duplicate:
return statement vs exit() in main()
I've just read the first chapter of Accelerated C++ (seems like an awesome book), and at the end the author says
However, explicitly including a return from main is good practice.`
Why is this considered good practice? In C99, I always omitted the return 0, ... | In C99 and in C++ if execution of the program reaches the closing brace of the main() function then an implicit return 0; is executed. That wasn't the case in C90 - reaching the end of main() without an explicit return would result in an indeterminate value being returned (strictly speaking, the behavior is undefined)... |
4,189,919 | 4,190,487 | Mix C-string and fortran-string in one file | I have one question with mixing C-string and fortran-string in one file.
Supposed I am playing with the name string with fixed length 9, I define a length Macro like
#define NAME_LEN 9
in a .c file.
There is an existing fortran-function, let's name it fortran_function(char* name)
Now I have to call this fortran f... | There's one more gotcha here, if I remember correctly. Fortran does not use null-terminated strings; instead, it pads the right end of the buffer with 0x20 (space). So, if you have access to the Fortran source, I would modify the function signature to take the length of the passed-in string as an argument. Otherwise... |
4,189,945 | 4,200,397 | Templated class specialization where template argument is a template | I wondering if something similar to this is possible. Basically, I have a templated class that occasionally takes objects of templated classes. I would like to specialize it (or just a member function)for a specific templated class, but the 'generic' form of that class.
template<typename T, typename S>
class SomeRa... | It's possible to specialize the class like this
template <>
template <typename T,typename S>
class MyTemplateClass <SomeRandomClass<T,S> >
{
void DoSomething(SomeRandomClass<T,S>& t) { /* something */ }
};
It's not possible to specialize just the member method, because the specialization is on the class as a whole... |
4,190,214 | 4,190,254 | Good starting cross platform ide | I'm hoping to write an open source IDE for a programming language I'm designing. I was wondering if anyone knew of any lightweight IDE's written in C++, that I could use as a starting place. Ideally I want to use something BSD licensed, however I'm willing to consider other licenses if it is required.
Thank you in adva... | Eclipse is the best way to go. However you might want to check
Code::Blocks or
KDevelop
|
4,190,246 | 4,190,327 | How to make a getter function for a double pointer? | I am needing to modify an open source project to prevent reusing code (more efficient just to create a GetGameRulesPtr() function than to keep going into the engine to retrieve it. The problem is, it is stored as void **g_pGameRules. Ive never really grasped the concept of a pointer to a pointer, and I am a bit confuse... | You want to return a void*, and do the casting back to the appropriate SomeType** within implementation code. This is because void** has strange semantics (which I can't find on google right now). It also tells more info to the user than they really need. The whole point of using void* to begin with was to avoid giv... |
4,190,437 | 4,190,606 | BitBlt draws a blank image | I'm using MFC, and I'm trying to draw an image to the screen. I've got the following OnDraw function:
void CgraphicstestView::OnDraw(CDC* pDC)
{
CgraphicstestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
m_Bitmap.LoadBitmap(IDB_WALL); // m_Bitmap is a CBitmap member of CgraphicstestView
... | I would have to guess that the problem is that your image is somehow invalid. Because I tested it and it works fine. LoadBitmap returns an HBITMAP, so you could test it like this:
HBITMAP hresult = m_Bitmap.LoadBitmap(IDB_WALL);
assert(hresult);
|
4,190,467 | 4,190,616 | SSE2 instructions not working in inline assembly with C++ | I have this function which uses SSE2 to add some values together it's supposed to add lhs and rhs together and store the result back into lhs:
template<typename T>
void simdAdd(T *lhs,T *rhs)
{
asm volatile("movups %0,%%xmm0"::"m"(lhs));
asm volatile("movups %0,%%xmm1"::"m"(rhs));
switch(sizeof(T))
{
... | I've found that inline assembly support isn't reliable in most modern compilers (as in, the implementations are just plain buggy). You are generally better off using compiler intrinsics which are declarations that look like C functions, but actually compile to a specific opcode.
Intrinsics let you specify an exact seq... |
4,190,499 | 4,190,540 | C/ObjC - parameter size. Using a pointer vs value | at what point should I be passing a pointer to data in my functions/methods, rather than just passing the value?
Obviously there's the cases where I want the function to operate on the given data, but what if I'm just passing the value for info/copying purposes?
For example, foo as a basic type:
void setFoo(int foo);
.... | When on embedded systems, I think it's good practice to pass pointers (or references) for anything that's not a primitive type. This way your struct can grow and add members as needed without affecting the amount of data that is copied. Needless copying is a good way to slow down your system, so avoid it when you can... |
4,190,619 | 4,191,558 | using the qsort() function | I'm a student & i looked up this function in a book. It works as it should but i don't quite understand the inner workings of the sortFunction() which is passed to the qsort() function. If some one could explain it in detail, please do. Thanks in advance.
#include<iostream>
#include<stdlib.h>
using namespace std;
//f... | If you look at the actual call to qsort...
qsort((void*)table, tableSize, sizeof table[0], sortFunction);
...you'll see it provides:
a void* address and the size (in bytes) of the entire data array to be sorted, then
the size of one data element in that array, then
a pointer to the comparison function "sortFunction"... |
4,190,703 | 4,190,737 | Is it safe to delete a NULL pointer? | Is it safe to delete a NULL pointer?
And is it a good coding style?
| delete performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete (helps avoiding double deletion and other similar memory corruption problems).
I'd also love if delete by default was setting the parameter to NULL like in
#def... |
4,190,727 | 4,190,780 | C++ Pointers and References Clarification | This is basically just to help me understand pointers better, so if you guys can confirm/deny/explain anything it looks like I don't understand properly I would be most appreciative. The examples of using mailboxes, and aunts, and streets, and all that crap is just confusing.
int a = 5;
int b = &a; // b will be the me... | I'll take things one by one:
int b = &a; // b will be the memory address of 'a'
No. The compiler (probably) won't allow this. You've defined b to be an int, but &a is the address of an int, so the initialization won't work.
int *c = a;
No -- same problem, but in reverse. You've defined c to be a pointer to an int, bu... |
4,190,882 | 4,190,891 | How do you delete (or fill with specific values) a static n-dimension array? | const int ROWS = 3;
const int COLUMNS = 4;
void fillArray(double a[ROWS][COLUMNS], double value);
void deleteArray(double a[ROWS][COLUMNS]);
int main () {
double a[ROWS][COLUMNS];
fillArray(a, 0);
deleteArray(a);
}
|
In C++, how do you delete (or fill with specific values) a static n-dimension array?
In C++ we generally do not use arrays. We use std::vector.
You can use memset or std::fill to fill the array with specific values.
BTW you can use delete on dynamically allocated arrays not on static ones.
memset( a, 0 ,ROWS * COLUM... |
4,191,089 | 4,191,318 | How to unit test function writing to stdout / std::cout | I am studying unit testing. From what I've seen, almost all unit tests use return value or an output parameter as the expected value in their test case.
What would be the expected value for a function that has no return value or output parameter?
Example:
void unit_test()
{
cout << "Hello" << endl;
}
Sure, this func... | If you are writing a function that you know should be tested, then you should design it to be testable in your framework. Here, if your testing is done at a process level where you can verify the process output, then writing to std::cout is fine. Otherwise, you may want to make the output stream a parameter to the fu... |
4,191,228 | 4,191,288 | What should I do to extend output values in c++ | This program converts Celsius degrees to Fahrenheit degrees and Kelvin.
When I run this code in Dev C++ I get Celsius values going from 2 to 300. How do I get the code to output Celsius values starting from -300 and ending at 300?
I clearly set cels = -300 in the for loop. So why does the output start from 2?
#includ... | I think the output is scrolling as has too many lines to hold in the buffer on the screen (tried on VS 2010/XP). The final output has lines only from 2 onwards to 300.
Don't worry, the output is printing but unforunately not seen in the final window on Windows at least.
Try logging the output to an output file instead.... |
4,191,253 | 4,191,350 | udp packet fragmentation for raw sockets | Follow-up of question packet fragmentation for raw sockets
If I have a raw socket implemented as such:
if ((sip_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
{
cout << "Unable to create the SIP sockets."<< sip_socket<<" \n";
return -3;
}
if ( setsockopt(sip_socket, IPPROTO_IP, IP_HDRI... | Yes, you need to prepare two packets, each with their own IP header.
If you put 1480 bytes of data in the first packet and 276 in the second, then the IP headers should be identical, except for these fields:
Fragment Offset: set to 0 in the first packet, and 1480 in the second;
Total Length: set to 1480 plus the heade... |
4,191,465 | 4,191,501 | How to Run Only One Instance of Application | I have a application which uses socket connection to send and receive data from another application. While creating socket it uses the port 4998 .
That is where my problem lie. Once I start my application the socket starts using port 4998. So if I want to execute the application again then I get socket binding error.
S... | You may used named mutex.
Code sample from the article:
WINAPI WinMain(
HINSTANCE, HINSTANCE, LPSTR, int)
{
try {
// Try to open the mutex.
HANDLE hMutex = OpenMutex(
MUTEX_ALL_ACCESS, 0, "MyApp1.0");
if (!hMutex)
// Mutex doesn’t exist. This is
// the first instance so create
... |
4,191,624 | 4,191,664 | function pointer with known arguments | I have a lot of legacy code that uses a function pointer as an argument of the form double (*f)(double). Now I have a requirement where I need to call this function from a class but function definition uses member variables. What do I do to solve this issue? For example,
void legacy_function(double (*f)(double)) { ....... | There's no clean way to solve this problem. It has no elegant solution within the bounds of the standard language.
One thing you can do is to provide a global or static variable that will serve as this pointer for the intermediate callback wrapper function (see below), and write a static intermediate callback wrapper f... |
4,191,639 | 4,191,652 | Simple boolean operators for bit flags | I am attempting to learn more about this to implement in my project.
I currently have got this basically:
unsigned char flags = 0; //8 bits
flags |= 0x2; //apply random flag
if(flags & 0x2) {
printf("Opt 2 set");
}
Now I am wishing to do a little more complex things, what I am wanting to do is apply three flags l... |
And the remove two from it? I thought
I could do something like this:
flags &= ~(0x1 | 0x2);
to remove those two flags, but
apparently they remain there or
something either way.
That is the correct way to remove flags. If you printf("%d\n", flags) after that line, the output should be 4.
I also do not know h... |
4,191,853 | 4,191,876 | How Can I bring my application to the Top of windows |
If I have two applications running simultaneously , App1.exe and App2.exe , I want to bring App2.exe when a button in App1.exe is pressed.
| Use FindWindow to retrieve the window-handle of your app2.exe window and then use BringWindowToTop on that handle.
You can find an (VB) example here: http://support.microsoft.com/kb/186431
|
4,191,920 | 4,193,258 | How to modify context menu of internet explorer using IDocHostUIHandler::ShowContextMenu? | I am trying to implement a custom menu for Internet Explorer 7.0. For this i have to use IDocHostUIHandler::ShowContextMenu only. Till now i am able to implement a basic context menu with two options. The problem is that they are disabled by default. The sample code for the same is:
HRESULT CWebEventHandler::ShowContex... | I think i have solved the problem. After getting the hwnd object in if (SUCCEEDED(pWnd->GetWindow(&hwnd))) install your own CALLBACK for context menu. In the callback
if ((uMsg == WM_INITMENUPOPUP) && (wParam == (WPARAM) menu)) {
return 0;
}
otherwise let the original handler process it.
once done ... |
4,192,021 | 4,192,066 | Question about Windows API and C/C++ run-time library function | When I write C/C++ code for Windows platform, I usually use Windows APIs as necessary. But when it comes to multi-threading, I read the following quotaion from < Windows via C/C++ >
The CreateThread function is the
Windows function that creates a thread.
However, if you are writing C/C++
code, you should never c... | Of course it's possible to use the Windows API's CreateThread directly.
But that leaves the runtime library uninformed about the new thread.
For the multi-threading support in the runtime library (and that includes functions that rely on static storage, e.g. I imagine it includes strtok) you need to keep the runtime li... |
4,192,058 | 4,215,425 | How to address C4191 warning around calls to GetProcAddress with FARPROC? | Recently I tried to use /Wall Visual C++ option to enable all warnings and found that the following code:
typedef BOOL ( WINAPI * TIsWow64ProcessFunction )( HANDLE, BOOL* );
TIsWow64ProcessFunction isWow64ProcessFunction = reinterpret_cast<TIsWow64ProcessFunction> (
::GetProcAddress( kernel32DllHandle, "IsWow64Proc... | You are casting a FARPROC (function pointer with no args) to a function pointer with args. Normally this is a hugely dumb thing to do that will probably result in stack corruption.
Now it turns out that GetProcAddress() doesn't really return a FARPROC and you do actually know what you're doing -- but the compiler do... |
4,192,110 | 4,192,418 | How did C++ change with the different editions of TC++PL? | (In case you do not know, "TC++PL" stands for "The C++ Programming Language", a book written by the inventor of C++, Bjarne Stroustrup.)
I only have the third edition and was just wondering how C++ looked in the first and second editions. Obviously the third edition is the only one to cover ISO standard C++, but what a... | Let Bjarne Stroustrup explain in his own words: A History of C++: 1979−1991
|
4,192,170 | 4,192,182 | What exactly is One Definition Rule in C++? | What exactly does One Definition Rule in C++ say? The only trustworthy occurence I can find is in The C++ Programming Language, 3rd. ed., P. 9.2.3. Is there any official definition of the rule except that?
| The truth is in the standard (3.2 One definition rule) :
No translation unit shall contain more
than one definition of any variable,
function, class type, enumeration type
or template.
[...]
Every program shall contain exactly
one definition of every non-inline
function or object that is used in
that progr... |
4,192,216 | 4,192,238 | c++ thread division into microprocessor | I have a question... I need to build an app multi-thread and my question is: if I have a 2cpu processor, is automatically that my 2 threads are separately one by processor?
and if I have 4 threads and my pc have 4cpu, are again 1 per processor? and if I have 4 processor and 2 cpus, how is divided??
thanks in advance
| This is not really a question which can be answered unless you specify the operating system at a minimum.
C++ itself knows nothing of threads, they are a service provided by the OS to the execution environment, and depend on that OS for its implementation.
As a general observation, I'm pretty certain that Linux schedul... |
4,192,225 | 4,192,249 | Benefits of ternary operator vs. if statement | I'm browsing through some code and I found a few ternary operators in it. This code is a library that we use, and it's supposed to be quite fast.
I'm thinking if we're saving anything except for space there.
What's your experience?
| Performance
The ternary operator shouldn't differ in performance from a well-written equivalent if/else statement... they may well resolve to the same representation in the Abstract Syntax Tree, undergo the same optimisations etc..
Things you can only do with ? :
If you're initialising a constant or reference, or worki... |
4,192,598 | 6,865,013 | libavcodec, how to transcode video with different frame rates? | I'm grabbing video frames from the camera via v4l, and i need to transcode them in mpeg4 format to successively stream them via RTP.
Everything actually "works" but there's something I don't while re-encoding: the input stream produces 15fps, while the output is at 25fps, and every input frame is converted in one singl... | Most simple solution would be to use two threads. First thread would do all the things outlined in your question (decoding, scaling / color-space conversion, coding). Partially transcoded frames would be written to intermediate queue shared with second thread. Maximum length of this queue would be in this particular ca... |
4,193,043 | 4,193,106 | select() on a pipe in blocking mode returns EAGAIN | The man pages for select() do not list EAGAIN as possible error code for the select() function.
Can anyone explain in which cases the select() can produce EAGAIN error?
If I understand select_tut man page, EAGAIN can be produced by sending a signal to the process which is blocked waiting on blocked select(). Is this co... | select() will not return EAGAIN under any circumstance.
It may, however, return EINTR if interrupted by a signal (This applies to most system calls).
EAGAIN (or EWOULDBLOCK) may be returned from read, write, recv, send, etc.
|
4,193,185 | 4,193,640 | C++ and GetAsyncKeyState() function | As it gives only Upper case letters, any idea how to get lower case??
If the user simultaneously pessed SHIFT+K or CAPSLOCK is on,etc, I want to get lower cases..
is it possible in this way or another??
Thanks,
| As you rightly point out, it represents a key and not upper or lower-case. Therefore, perhaps another call to ::GetASyncKeyState(VK_SHIFT) can help you to determine if the shift-key is down and then you will be able to modify the result of your subsequent call appropriately.
|
4,193,327 | 4,193,976 | a good-design approach for making a geometry library (regarding using union or not)? | i am making a geometry library and i am confused, what should be the return type of a function which calculates the intersection of a segment with another segment. The returned value would sometimes be a point and sometimes be a segment (overlap case) and sometimes be an empty set. As per my thinking there could be 3 w... | My suggestion is to create a specialized Intersection class that can handle all the cases.
You can return an instance of that class then. Internally the class could have for example the vector representation (with same endpoints if the intersection is one point, as you suggested) and could have methods for determining ... |
4,193,430 | 4,193,449 | Is there a quick way to create a set? | Currently I'm creating a new set like this:
std::set<A> s;
s.insert(a1);
s.insert(a2);
s.insert(a3);
...
s.insert(a10);
Is there a way to create s in one line?
| You can look into Boost.Assign, which allows you to write things such as :
const std::list<int> primes = boost::assign::list_of(2)(3)(5)(7)(11);
|
4,193,476 | 4,193,503 | Is using #pragma warning push/pop the right way to temporarily alter warning level? | Once in a while it's difficult to write C++ code that wouldn't emit warnings at all. Having warnings enabled is however a good idea. So it is often necessary to disable warnings around some specific construct and have them enables in all other pieces of code.
I've seen two ways of doing that so far.
The first one is to... | The first method is the best way to do it, IMO. I know of no problems with it.
Simply bear in mind that a #pragma is compiler specific so don't expect it to work on every compiler out there :)
|
4,193,639 | 4,193,698 | Inline function linkage | I can't make sense of the following behavior: one header with some basic types, and another header in which I use these types in several functions. Afterward I started constructing classes based on my defined types and functions. In the function header if I leave the following signature:
void whateverFunction(parameter... | When the function in the header is not inline, then multiple definitions of this function (e.g. in multiple translation units) is a violation of ODR rules.
Inline functions by default have external linkage. Hence, as a consequence of ODR rules (given below), such multiple definitions (e.g. in multiple translation units... |
4,193,678 | 4,194,815 | Sharing an object between instances of a C++ DLL | Good morning all,
Forgive me if the title is not too clear, I'll try to explain more here:
I am currently working with the ASI for VBS2. VBS2 executes functions from a VBS2 DLL plugin. I have my own application which I want to use to modify variables within that plugin whilst it is being used, to change what is being e... | You need to use linker flags to tell the linker to place that segment in sharable memory.
See http://msdn.microsoft.com/en-us/library/ms933104.aspx
I belive you need to add something like
#pragma comment(linker, "/SECTION:.testseg,RWS")
to your program.
I'm not sure, this may only work in a DLL...
|
4,193,982 | 4,194,010 | Delete a pointer to pointer (as array of arrays) | I have this in my code:
double** desc = new double* [size_out];
for (int i = 0; i < size_out; i++)
desc[i] = new double [size_in];
How do I delete this desc?
Should I do:
delete [] desc;
or
for (int i=0; i<size_out; i++)
delete [] desc[i];
delete [] desc;
or
for (int i=0; i<size_out; i++)
delete []... | Simple rules to follow:
for each allocation, there has to be a deallocation (ex1 is therefore wrong)
what was allocated using new should be freed using delete, using new[] should be deallocated using delete[] and using malloc should be deallocated using free (ex3 is therefore wrong)
Conclusion, ex2 is OK.
|
4,194,087 | 4,207,704 | Address already in use with boost asio acceptor | I wrote a server that is listening for incomming TCP connections and clients connecting to it. When I shut down the server and restart it on the same port, I sometimes get the error message EADDRINUSE when calling bind(...) (error code: 98 on Linux). This happens even though I am setting the option to reuse the socket.... | These were originally a comment to the question.
does your server fork child processes? Also, are you sure the socket is in TIME_WAIT state? You might want to grab the netstat -ap output when this happens
|
4,194,136 | 4,194,175 | What to do with students after templates were explained? | I'm having a C++ seminar in 30 minutes :-)
Because I incorporated most of the examples I usually do on the seminar into the lecture I don't have anything to do with my students. I just gave them a broad overview of templates (from basics to advanced topics).
Any tips what to do?
It can be something that I will explain ... | Replicate containers - like a list or a vector.
|
4,194,179 | 4,194,294 | How To register a Windows Class and Find the Window using registered class | I am creating an MFC application which will be launched on click on Explorer Context (Rightclick) menu.
But I need to launch only single instance of the application. For that I have to use FindWindow and AfxRegisterClass
I tried to register the class in my MFC app as below:
BOOL CNDSClientDlg::InitInstance()
{
//R... | FindWindow finds window instances not window classes. In your app which registers the class you need to actually create a window so that the extension can find that window.
(Finding the window by class name is fine; the problem is you haven't actually created anything to find.)
Also, I suspect if you try to create a wi... |
4,194,191 | 4,194,398 | C++: type_info to distinguish types | I know that compilers have much freedom in implementing std::type_info functions' behavior.
I'm thinking about using it to compare object types, so I'd like to be sure that:
std::type_info::name must return two different strings for two different types.
std::type_info::before must say that Type1 is before Type2 exclus... | After a quick look at the documentation, I would say that :
std::type_info::name always returns two different strings for two different types, otherwise it means that the compiler lost itself while resolving types and you shouldn't use it anymore.
Reference tells : "before returns true if the type precedes the type of... |
4,194,270 | 4,194,368 | C++: Boost local time is one hour behind | I am living in the Netherlands, when I run this code:
boost::local_time::local_date_time t = boost::local_time::local_sec_clock::local_time(boost::local_time::time_zone_ptr());
std::cout << "\nDate Time: " << t.to_string() ;
The "Date Time" returned is one hour behind. It is UTC but it should be GMT+1 or UTC+1 for my... | boost::local_time::time_zone_ptr zone_GMT1(new boost::local_time::posix_time_zone("GMT+1"));
boost::local_time::local_date_time t =
boost::local_time::local_sec_clock::local_time(zone_GMT1);
I found out to use the timeZone.
It works fine for me
Thanks!
|
4,194,468 | 6,232,820 | Replace vector and hash table with Boost.Bimap | I'm looking to replace a vector<string> and a boost::unordered_map<string, size_t> mapping string to indices in the former with a boost::bimap.
What instantiation of bimap should I use? So far, I've come up with
typedef bimap<
unordered_set_of<size_t>,
vector_of<string>
> StringMap;
but I'm not sure if I've re... | To get a bimap between size_t and std::string where you have ~constant (up to the cost of hashing and any potential clashes) you need to use unordered_set_of:
#include <boost/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include <string>
#include <iostream>
#include <typeinfo>
int main(int argc, char* argv[]... |
4,194,626 | 4,194,680 | C++: How to iterate over a text in a std::string line by line with STL? | I have a text in a std::string object. The text consists of several lines. I want to iterate over the text line by line using STL (or Boost). All solutions I come up with seem to be far from elegant. My best approach is to split the text at the line breaks. Is there a more elegant solution?
UPDATE: This is what I was l... | Why do you keep the text in your source file? Keep it in a separate text file. Open it with std::ifstream and iterate over it with while(getline(...))
#include <iostream>
#include <fstream>
int main()
{
std::ifstream fin("MyText.txt");
std::string file_line;
while(std::getline(fin, file_line))
{
... |
4,194,675 | 4,265,227 | How do I read boot time events on Windows 7? | I am trying to use the ETW functions without success to read the file:
C:\Windows\System32\winevt\Logs\Microsoft-Windows-Diagnostics-Performance%4Operational.evtx
In order to capture boot time events.
I have tried various functions -
OpenTrace gives an error 161
EvtQuery gives an error 15000
Does anyone have a nativ... | I got this working as follows -
LPWSTR pwsPath = L"Microsoft-Windows-Diagnostics-Performance/Operational";
LPWSTR pwsQuery = L"Event/System[EventID=100]";
hResults = EvtQuery(NULL, pwsPath, pwsQuery,
EvtQueryChannelPath | EvtQueryReverseDirection);
The channel name can be found by going to Propert... |
4,194,734 | 4,195,454 | Declare a C++ class without defining it in the current translation unit | It is possible to declare a class without defining it (forward declaration) as long as it is defined later on within the translation unit. In the case of functions, one can declare a function without defining it within the translation unit, and the linker will link it to its definition in a different translation unit. ... | It is possible to forward-declare a class, but only pointers and references to forward-declared classes can be used. You can't use an actual object of a forward-declared class because the compiler doesn't know enough about it; in particular it doesn't know how large the object is or what its members are. Trying to forw... |
4,194,755 | 4,195,206 | Use std::vector to construct a object and use it | I need to avoid the additional cost of copying and destructing the object contained by a std::vector caused by this answer.
Right now I'm using it as a std::vector of pointers, but I can't call std::vector::clear() without deleting each object before nor I can use std::auto_ptr with std containers.
I wanted to do somet... | Almost there:
vector<MyClass> MyVec;
MyVec.push_back(MyClass()); // Any decent compiler will inline this, eliminating temporaries.
MyClass &item = MyVec.back();
|
4,194,821 | 4,194,841 | Are there differences between explicit type conversion "operators" in case of basic types? | Simple thing: I would like to "convert" e.g. a float into a double. Now there are three ways known to me:
float v = 4.2f;
double u = (double)v;
double u = double(v);
double u = static_cast<double>(v);
double u(v); Edit: Just thought about this as a fourth option!
Are these identical or are there any subtle differenc... | double u = (double)v; and double u = static_cast<double>(v); are equivalent because for both cases a standard conversion is used. However double u = double(v); creates a temporary double object (which can be optimized away anyway) which is then used to initialize u. But since a temporaty is created anyway, using all t... |
4,195,021 | 4,195,083 | How can one avoid duplicating class template specification for each member function? | If I have a template class specification like so,
template <typename T>
class MyClass {
public:
void fun1();
// ...
void funN();
};
template <typename T>
void MyClass<T>::fun1() {
// definition
}
// ...
template <typename T>
void MyClass<T>::funN() {
// definition
}
If I change the class templat... | To me, the benefits of using a macro here are far overshadowed by the drawbacks. Yes, if you use a macro then if you ever need to add an additional template parameter, you'll only need to make a single modification. But anyone else reading your code is probably going to vomit.
I mean, are you going to do this for e... |
4,195,494 | 4,195,585 | Using GCC to find unreachable functions ("dead code") | I was looking for a way of finding statically unreachable functions in a (very) big C++ project. I had tried using doxygen and other static analysis tools suggested here but it seemed that the project is too complicated for them to handle. Finally i decided that using GCC tools (g++, gprof, gcov, etc.) is the safest op... | Dead code optimization is typically done by the linker - the compiler doesn't have the overview. However, the compiler might have eliminated unused static functions (as they have internal linkage).
Therefore, you shouldn't be looking at GCC options, but at ld options. It seems you want --print-gc-sections. However, not... |
4,195,611 | 4,195,743 | Getting a list of values from a map | Is there an stl way to get a list of values from a map?
i.e, I have:
std::map<A,B> myMap;
and I would like a function that will return just the list of values, i.e, std::list<B> (or set for that matter.
Is there a built-in stl way to do this?
| A map element is defined as a map::value_type, and the type of it is a pair<A,B>. first is the key and second is the value. You can write a functor to extract second from a value_type, and copy that in to a vector (or a list, or whatever you want.) The best way to do the copying is to use transform, which does just... |
4,195,691 | 4,195,755 | To use shared_ptr, is it safe ? | I have got some confused about shared_ptr.
Say, I have classes:
class foo {
int _f;
};
typedef std::shared_ptr<foo> fooptr;
class bar {
int _b;
};
typedef std::shared_ptr<bar> barptr;
class foobar : public foo, public bar {
int _fb;
};
int main () {
foobar *fb1 = new foobar();
foobar *fb2 = new... | A shared_ptr<base> can safely take ownership of a derived*, even if base does not have a virtual destructor.
However, this only works if shared_ptr knows what the most derived type of the object is when it takes ownership of it. If you were to remove the casts
fooptr f(fb1);
fooptr b(fb2);
then you'd definitely be ... |
4,195,764 | 4,195,959 | Is there a warning free template function to convert basic types to string | I want to provide a templated function that converts most basic types to string.
The best I have come up with so far is the following:
template<typename T> inline std::string anyToString(const T& var) {
std::ostringstream o;
o << var;
return o.str();
}
The function can e.g. be used for the following:
class Time... | It seems you'd get such a message from a scenario like this:
#include <sstream>
#include <string>
#include <iostream>
struct Y {};
struct X
{
operator Y() const {return Y(); }
};
std::ostream& operator<< (std::ostream& os, X) { return os << "X"; }
std::ostream& operator<< (std::ostringstream& os, Y) { return os <... |
4,195,951 | 4,195,983 | What does 'char x[]' mean? | I have a struct like this:
struct A
{
char x[];
};
What does it mean? When I do something like:
A a;
a.x = "hello";
gcc throws an error saying:
error: incompatible types in assignent of 'const char [6]' to 'char [0u]'
| This is a C99 "flexible array member".
See here for gcc specifics: http://www.delorie.com/gnu/docs/gcc/gcc_42.html
|
4,195,958 | 4,196,775 | How do I scale down numbers from rand()? | The following code outputs a random number each second:
int main ()
{
srand(time(NULL)); // Seeds number generator with execution time.
while (true)
{
int rawRand = rand();
std::cout << rawRand << std::endl;
sleep(1);
}
}
How might I size these numbers down so they're always ... | If you are using C++ and are concerned about good distribution you can use TR1 C++11 <random>.
#include <random>
std::random_device rseed;
std::mt19937 rgen(rseed()); // mersenne_twister
std::uniform_int_distribution<int> idist(0,100); // [0,100]
std::cout << idist(rgen) << std::endl;
|
4,196,153 | 4,196,187 | find how many seconds past since 1/1/1970 | I am looking for a function in C++ that calculates how many seconds have past from 1/1/1970 until today.
| #include <time.h>
time_t seconds_past_epoch = time(0);
Available on most operating systems.
|
4,196,201 | 4,196,745 | Where are C/C++ main function's parameters? | In C/C++, the main function receives parameters which are of type char*.
int main(int argc, char* argv[]){
return 0;
}
argv is an array of char*, and points to strings. Where are these string located? Are they on the heap, stack, or somewhere else?
| It's actually a combination of compiler dependence and operating system dependence. main() is a function just like any other C function, so the location of the two parameters argc and argv will follow standard for the compiler on the platform. e.g. for most C compilers targeting x86 they will be on the stack just abo... |
4,196,431 | 4,196,475 | Passing the caller __FILE__ __LINE__ to a function without using macro | I'm used to this:
class Db {
_Commit(char *file, int line) {
Log("Commit called from %s:%d", file, line);
}
};
#define Commit() _Commit(__FILE__, __LINE__)
but the big problem is that I redefine the word Commit globally, and in a 400k lines application framework it's a problem. And I don't want to use a speci... | So, you're looking to do logging (or something) with file & line info, and you would rather not use macros, right?
At the end of the day, it simply can't be done in C++. No matter what mechanism you chose -- be that inline functions, templates, default parameters, or something else -- if you don't use a macro, you'll ... |
4,196,552 | 4,196,656 | How to check if a process has elevated privileges in windows 7 using native C++? | How can I check if a process has elevated privileges in Windows 7 (using native C++, not C#/C++.net) ?
I've been looking for an answer for quite sometimes, but all I can find are the answers that use the .NET framework.
| The simplest approach is to call the IsUserAnAdmin function. If you need more precision you can also use GetTokenInformation but in most cases that is overkill.
|
4,196,824 | 4,196,869 | Creating an alias for an instantiated template | I originally had a number of signal processing filter classes that were identical apart from a few constants defining the filter characteristic, so I decided to change these to a template class for maintainability and extensibility. There are performance and memory management reasons for preferring a template over con... | Yes, typedef!
typedef cBoxcarFilter<8, 1, 3> cSpecialistBoxcarFilter;
|
4,196,854 | 4,197,085 | Row Background Color GtkTreeView Widget | I'm attempting to color disabled rows in a gtk tree view widget a light gray color. From what I've read, I'm supposed to set the background-gdk property of the corresponding cellrenderer and bind it to a model column. This sort of works.
Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
textR... | Could you set the background of the row to match the cell background or set the bakground of the tree view all together ? Or maybe the cell with cell-background-gdk ?
|
4,196,882 | 4,196,906 | difference when defining array under Linux or Windows | Here is a simple code of defining an array. I noticed this code will work(compile and run) under Linux(OpenSue,gcc compiler), but it will not work under Windows system. The compiler gave error prompt. Does anybody know the reason? Thanks!
#include <iostream>
using namespace std;
int main()
{
int N;
cin>>N;
... | The code isn’t valid C++ since C++ does not allow declaring a (stack-allocated) array with a variable size as you do. The reason for this is that C++ offers better mechanisms of declaring dynamically sized arrays, using the std::vector class from its standard library:
#include <iostream>
#include <vector>
using namesp... |
4,197,040 | 4,197,112 | C/C++: 2D animation library | I need to write an application that (among the other things) renders 2D animated images, let's suppose it's a videogame.
Figured out that videogame-like images can have a quite complex structure that depends very little on the program logic, mostly on the image itself:
It can have several animations (one for each stat... | SDL is excellent for games.
Check out http://www.sdltutorials.com/sdl-animation/
|
4,197,143 | 4,197,158 | Perform rounding on integral type, but not fractional type | In the following function I am looking for an expression to replace isIntegral<T>.
The intention is that when T is an integral type we add 0.5f before static_cast implictly floors the value (and so we obtain a rounded value), but when T is a fractional type we add nothing, and so the static_cast can only reduce the pre... | Use std::numeric_limits<T>::is_integer (it's in the <limits> header).
|
4,197,336 | 4,197,824 | Calling a windows common dialog from a command line application | Is it possible to call a windows common dialog and retrieve its output from within a command line application? I'd like to build most of my application to run from the console, since in my particular case it would SERIOUSLY reduce complexity; however, I would like to be able to pop up a folder selector dialog to let t... | #include <windows.h>
#include <shlobj.h>
#include <iostream>
int main() {
BROWSEINFO bi = {0};
bi.lpszTitle = "Pick a Directory";
LPITEMIDLIST pidl = SHBrowseForFolder (&bi);
if (pidl != 0) {
TCHAR path[MAX_PATH];
if (SHGetPathFromIDList(pidl, path)) {
std::cout << path << "... |
4,197,380 | 4,197,459 | Simple C++ write-to-file not working within Mac OS X App - why? (and why me?) | The code is simple enough:
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[] )
{
std::ofstream theStream;
theStream.open("trash.txt");
theStream << "some words" << std::endl;
theStream.close();
}
If I run it from the command line then I get the expected file in t... | Instead of "trash.txt", try to use the full path or change the current working directory.
|
4,197,454 | 4,244,970 | boost::program_options - does it do an exact string matching for command line options? | There seems to be a problem the way boost::program_options's options_description matching is done.
int main(int argc, char* argv[])
{
boost::program_options::options_description desc("CmdLine utility");
desc.add_options()
("hel", "hel message")
("help", "produce help message")
("helps","... | By default, program_option has allow_guessing style bit on, so a substring match is sufficient. The behaviour you observe, where an option is matching a prefix of the command line, even when there's a different option that matches fully, is a bug. It's fixed in 1.45.
|
4,197,697 | 4,197,730 | c++ ifstream function and field separators | For this program i have only used field separators from data files in shell script. But I am trying to use the standard library function ifstream() to read in from a data file. The only problem is I am getting the data like so
A:KT5:14:executive desk:
This is for a hash table, and I need to separate the values in the l... | getline gives you the option to specify a delimiter. You can then read the input from a stream as a sequence of string separated by _Delim:
template<class CharType, class Traits, class Allocator>
basic_istream< CharType, Traits >& getline(
basic_istream< CharType, Traits >& _Istr,
basic_string< CharTy... |
4,197,786 | 4,198,042 | find repeated words number in c++ | is there anyway to find out how many times a word repeated in a text .
the text is in character arrays (char[])
text = this is a book,and this book
is about book.
word = book
result = 3
| Because this is clearly homework and not tagged as such, I'll give you a solution you clearly can't submit as your assignment because your teacher will know you got it on the internet.
There were no requirements such as ignoring punctuation, so I've allowed myself to write a version that only works for clearly separate... |
4,197,971 | 4,198,085 | What does C++ iostreams have to offer in comparison with the C stdio library? |
Possible Duplicate:
Which I/O library do you use in your C++ code?
I asked this question in a comment to another question, and I was asked to make it a proper question instead.
Why do I want to use iostream instead of stdio? More specifically, what do std::getline have to offer over the C equivalent?
Please, no lang... | There are several advantages, mostly with the << and >> operators. Getting a line isn't all that different, although being able to read it into a std::string is a considerable advantage.
C++ I/O has type safety. You don't write your parameter list as a quoted string, and then again as variables and such. You write w... |
4,198,022 | 4,198,067 | Issue when implementing a map-like iterator in C++ | I just finish to implement a generic skip list in C++ an I want to bring it an
STL map-like iterator.
The problem arise when overloading the "->" operator: it is required to return a reference to an iterator::value_type, which in my case is std::pair, with K being the key type and V the value type of my map-like contai... | value_type& operator->() { return value_type(inner->key, inner->value); }
Your return type is a reference to a value_type, but you return a locally-created instance, which would be destroyed at the end of the function/operator scope (i.e. the closing }.) So you return a garbage reference, which is why your compiler ha... |
4,198,062 | 4,219,701 | stlport compilation with Visual Studio 2008 SP1 (msvc9) on Windows 7 x64 doesn't work | I downloaded stlport from https://stlport.svn.sourceforge.net/svnroot/stlport/trunk/STLport and tried to compile it with Visual Studio 2008 SP1 on Windows 7 x64.
The readme says to use: configure -c msvc9 but -c is an unknown compiler option so I used: configure msvc9
This seems to work according to the output, but it ... | I found the solution:
I use "Visual Studio 2008 Command Prompt" (for the vars and paths) with the configure script from http://strongdc.sourceforge.net/download/STLPort.7z and I copy all the svn files over the files in this 7z
Then I replace every "_value" with "_stlvalue" in stlport\stlport\type_traits.
In the folder ... |
4,198,092 | 4,198,152 | Calling C++ function pointers from C libraries | I have a class that only has static members.
I would like to register one of its member functions (VerifyClean in the code below) to be called at exit, using the "atexit" library function.
The C++ FQA says that i must specify extern "C" for the function i want to register this way, like in the following example.
class ... | It is possible for a compiler to use different calling conventions for C and C++ code; however, in practice, this almost never occurs.
If you just want it to work and don't care about supporting obscure compilers, don't bother with extern "C". It's not necessary in any widely-used compiler.
If you want to be absolutely... |
4,198,404 | 4,198,733 | Reading integers from a memory mapped formatted file | I have memory mapped a large formatted (text) file containing one integer per line like so:
123
345
34324
3232
...
So, I have a pointer to the memory at the first byte and also a pointer to the memory at the last byte. I am trying to read all those integers into an array as fast as possible. Initially I created a spec... | std::vector<int> array;
char * p = ...; // start of memory mapped block
while ( not end of memory block )
{
array.push_back(static_cast<int>(strtol(p, &p, 10)));
while (not end of memory block && !isdigit(*p))
++p;
}
This code is a little unsafe since there's no guarantee that strtol will stop at the e... |
4,198,415 | 4,198,496 | Creating a vector of pointer to functions | How do I do this in C++?
I know how to create a pointer to a function but that requires having a name for that pointer.
What I actually need is to somehow create a pointer without naming it.
I know the syntax for array of ptr to functions. This might help:
out-type (*ptr[size])(parameters...)
| You should really use a boost/std::function<out_type(parameters)> instead. However, to answer the question at hand, you could use a typedef
typedef out_type(*typedef_name)(param_types);
std::vector<typedef_name> vec;
Or you can just supply the vector with the type directly.
std::vector<out_type(*)(param_types)> vec;
|
4,198,440 | 4,215,286 | Windows unbuffered I/O & NCQ | When using unbuffered I/O (CreateFile with FILE_FLAG_NO_BUFFER / FILE_FLAG_WRITE_THROUGH) and writing multiple sectors each call to WriteFile, is it possible that the sectors are written in a different orderer then first to last ?
int iSizeToAlloc = sector_size * 32;
char *pAlignedMemory = alloc(iSizeToAlloc)
// Her... | Short answer is "Yes, it is possible".
Longer answer is "it is not even guaranteed that consecutive 'sectors' of data will be written to adjacent disk sectors."
There could be all sorts of "system" caching going on. The file system might even be encrypted or compressed.
The question is "why do you care?" What p... |
4,198,593 | 4,198,787 | std::set and its front_insert_iterator | I know I can do this:
std::vector<double> vec;
std::back_insert_iterator<std::vector<double> > it( back_inserter(vec) );
it = 4.5;
But I'd like to do something similar (in syntax) to std::set (and use a front_insert_iterator instead of a reference to the set and use set::insert). Is it possible, or am I forced to use ... | You don't push_back or push_front to set, because (conceptually) a set is a sorted associative container. You can do this, though:
#include <cstdlib>
#include <set>
#include <iterator>
using namespace std;
int main()
{
typedef set<int> MySet;
MySet si;
insert_iterator<MySet> it(si, si.begin());
*it =... |
4,198,675 | 4,198,704 | String is not printing without new line character in C++ | I'm opening a file, and getting lines from it.
The first line should say how many variables there are, and what their names are.
The second line should be a logic equation using these variables.
The assignment is to have it print out a truth table for the variables and equation.
The first line the program is taking in ... | An std::ostream's output needs to be flushed. It is normally flushed automatically when a line-feed \n is written. If you want to force the stream to flush, you can use the std::flush manipulator like so:
std::cout << "foo" << std::flush;
Edit: Although my post clearly answers the question "Why does my line not show u... |
4,198,711 | 4,198,731 | C++: Class member reference validity? | Class A
{
A(int& foo) : m_foo(foo) {}
int& m_foo;
};
int main(void)
{
A* bar = 0;
{
int var = 5;
bar = new A(var);
}
std::cout << "Is m_foo still valid?:" << bar.m_foo << std::endl;
}
"m_foo" is a reference and "var" is a local variable which is given to the constructor. "var" gets out o... | m_foo is not valid when int var falls out of scope. The thing to which it refers has gone away.
|
4,198,770 | 4,208,215 | Core file complete nonsense or could this code really have thrown a SIGFPE? | My core file claims that a SIGFPE was thrown from
gcc-4.3.4/include/c++/4.3.4/bits/stl_iterator_base_funcs.h
on line 176. This is here:
template<typename _InputIterator, typename _Distance>
inline void
advance(_InputIterator& __i, _Distance __n)
{
// concept requirements -- taken care of in __... | In answer to my own question, what happened is that optimizer took code that looked like this:
int which = RANDOM % somecontainer.size();
std::advance(it, which);
and combined them. This is why it appears the signal was raised from inside std::advance. Following Oli's comment, SIGFPE can occur when you take the modu... |
4,198,952 | 4,199,402 | Qt - No matching function for call to? | Call this from a QWidget: Parser->xmlParser(_layout, xmlPath, comingFrom, mapCount);, but get two "No matching function for call to..." errors.
No matching function for call to QMap<QMap<QString, QString>, int>::insert
No matching function for call to QList<QMap<QString, QString>>::append
parser.cpp
#include "parser.... | I don't understand what you are doing exactly, but while inserting to a map, you have to specify both the key and the value. That is the reason for the first error you mentioned.
Also you have a mismatch in parameters, that is to say, you have a list of QMap (the mapList list), and you are trying to append QMap< QMap<... |
4,199,008 | 4,200,881 | Boost ASIO Buffering Not Working | I'm writing a networking application that uses ASIO/UDP to send and receive between a single remote/locale endpoint pair. I had used udp::socket::receive to receive data and everything in my code worked logically, but I was losing an enormous number of packets. What I discovered was that any packet received while not b... | The general idea here is that your program should spend the vast majority of it's time waiting on the socket to deliver something, either blocked in the UDP receive or waiting in the io_service for notification that the socket has asynchronously received something. The socket implicitly has a small buffer in the OS fo... |
4,199,180 | 4,235,859 | XSD : How to set attributes values in children element type? | In an xsd file I have this element base type :
<xs:complexType name="event" abstract="true" >
<xs:attribute name="move" type="aos:move_ref" use="required" />
<xs:attribute name="type" type="aos:event_type" use="required" />
</xs:complexType>
And I want to define the value of the type attribute in the children ... | To derive a type and fix a value, use a restriction:
<xs:complexType name="signal" >
<xs:complexContent>
<xs:restriction base="aos:event">
<xs:attribute name="type" type="aos:event_type" fixed="signal" use="required" />
<xs:attribute name="source" type="aos:signal_source" use="required" />
... |
4,199,185 | 4,199,198 | Socket API or library for C++? | I recently have been getting more into C++. I have done some (very minimal) socket programming with C, but have been interested in doing some work with C++. I have only been able to find reference/tutorials on C based socket implementations. Is there a reason for this? I know, or believe I know that you can use the C s... | Here I'm attempting to answer some of your specific, factual questions to which I have something to contribute.
Yes, you can use any C socket library in C++. If it doesn't work out-of-the-box because the linker reports an undefined reference for the library functions you want to use, then can fix it by editing the .h f... |
4,199,309 | 4,199,507 | how to deserialize network data into different primitives? | I'm sure this is a very common operation when doing any kind of network programming (or I/O with files) but I can't find the answer.
Basically I have a datagram packet coming in down the network which has a series of single precision floating point numbers (4 bytes each).
I have written some basic networking code which... | If they are really sending floats -- which I wouldn't recommend, if you have a choice -- then you have to do some bit hackery.
Here is a utility library I wrote to do just this kind of thing. It works on Windows (MSVC) and Linux (GCC). It might not work on other platforms! Use at your own risk.
/************** UTIL... |
4,199,556 | 4,199,613 | Usefulness of covariant return types in C++ clone idiom? | The usual clone idiom makes use of covariant return types:
struct Base {
virtual Base* clone();
};
struct Derived : public Base {
Derived* clone();
};
I've read things to the effect that covariant return types were a later addition to C++, and older compilers may not support them. In this case the Derived cl... | It's useful when you have a pointer to Derived and want to get a clone of it:
Derived *ptr = ...;
Derived *clone = ptr->clone();
without covariant return types you must do an explicit cast:
Derived *clone2 = (Derived*)ptr->clone();
Note that Derived may be a base class for even more derived classes, in that case it m... |
4,199,557 | 4,200,437 | threading in someone else's address space | I'm building a monitor app and am having some threading issues.
I have, using a cbt hook, injected a dll in to another processes memory. I am reading the memory of the other application at certain addresses. The trouble is I was using a loop to watch the process and basically the app being watched wasn't free to car... | One thing is sure: addresses to read and write are definitely not a DWORD type. From the code above, it seems that you pass an DWORD addr as the address to read from, then you start a thread to which you pass on the address of your local addr parameter. Most likely the thread proc is then attempting to read the address... |
4,199,629 | 4,199,834 | C++ multiple lines input | So I need to create a char buffer containing 4 lines of text (EN_us) like
first line
line with some number like 5
line 3
empty line
What is correct way of getting such char buffer from user and how to get its length?
| Instead of getting a buffer like that, it might be easier to read four lines into separate strings from the standard input using getline (use a loop if you prefer):
Then the total data length is the sum of the individual string lengths. Alternatively use this method to retrieve the data from the user and then concaten... |
4,199,739 | 4,199,774 | loading a lib from lua | when loading a .dll file from lua it gives me this error:
loop or previous error loading module 'wildcard'
whats wrong?
@edit:
@lhf: ive changed the filename but now its giving me these errors:
> dofile("_test.lua")
_test.lua:1: module 'wildcard' not found:
no field package.preload['wildcard']
no file... | Try
package.loaded.wildcard = false
See refman which describes the package table.
|
4,199,912 | 4,199,967 | array of maps help c++ / qt | I don't know if I'm doing this right, c++ is not a native language for me.
QMap < QString, QString > *mapArray;
QMap < QString, QString > map[10];
mapArray = map;
mapArray[0].insert("key1", "value1");
mapArray[0].insert("key1-1", "value1-1");
mapArray[1].insert("key2", "value2");
mapArray[2].insert("key3", "value3")... | No. You seem to be making things much more complicated than necessary. At least from the looks of things, you don't need a pointer or an array, just a QMap object:
QMap<QString, QString> map;
map.insert("Key1", "value1");
map.insert("Key1-1", "value1-1");
map.insert("key2", "value2");
QMap<QString, QString>::const_it... |
4,199,950 | 4,199,968 | Why does compiler allow you to "write" a const variable here? | Why can you kind of cheat compiler this way:
const int a = 5;
*((int*)&a)=5; // VC/armcc does not complain
when above is "abridged" equivalent of this:
const int *ptr2const = &a;
int *ptr = ptr2const; // as expected error is raised here
*ptr = 5;
| C-style casts allow you to cast away constness like in your example. In C++, you would normally use the new style casts such as static_cast<>, which don't allow you to cast away constness. Only const_cast<> allows you to do that.
|
4,200,004 | 4,200,055 | C++ adding Debugging code that only runs when Debugging | As the question explains: I would like to add some debugging code that only runs when the program is attached to the debugger. I would imagine that this flag or pre-processor variable would be different for every compiler...
In my case I am using Microsoft Visual Studio 2010 with C++.
I also use Eclipse on another com... | This question could mean 1 of 2 things:
Code that only runs based on the build configuration (e.g. Release vs. Debug)
Code that only runs when the debugger is attached
Based on build configuration
This can be solved by using the pre-processor macro relevant to your compiler (e.g. _DEBUG for the Win32 CRT).
Based on w... |
4,200,170 | 4,200,233 | Visual Studio 2010 Debugging "if (var == NULL)" not triggering | Solved - Problem with constructor
Matthew Flaschen and Michael Burr pointed out the problem of the overloaded constructor of Node(int) calling Node() which doesn't work because...
Thanks guys!
I have built a program (I am debugging it) and have run into a weird problem... A `if` statement is not getting triggered when... | 0xcdcdcdcd is not a NULL pointer - that value is used in the debug builds of MSVC for memory that has been allocated but not initialized.
See When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete? for more details.
The root of your problem might be in the constructor that takes an int ... |
4,200,177 | 4,200,366 | Where should I put my DECLSPEC for a namespace? | given the following namespace, where do I put my declspec (for dll export) i I want all the methods in said namespace to be exported into the DLL?
namespace AguiText {
void drawTextArea(AguiGraphicsManager *g, const AguiFont &font,const AguiRectangle &area,
const AguiColor &color, const std::vector<std::str... | There is no need to export a namespace. From a compiled code perspective, namespaces are meaningless. You cannot reference them in code, they just define scope.
Namespaces wind up becoming part of class/function names during the name mangling process. They are not separate entities once a source file is compiled.
If yo... |
4,200,183 | 4,331,966 | Aspect Oriented Programming in C++ - Current supported alternatives | I have used AspectJ before for Java, and I recently have thought about checking which possibilities exist for the C++ language.
I heard about AspectC++, but unlike AspectJ, AspectC++ seems to be abandoned in the sense that the latest release dates from 21.12.2005, according to their website.
I wonder if there are any m... | AspectC++ was a worthy try but university projects don't often continue because the products tend not to be robust, the original academics lose interest and the graduate students that build it move on. That appeared to be case when I wrote this answer in 2010. To my surprise in 2017, AspectC++ still seems to have act... |
4,200,190 | 4,200,751 | Does D have something akin to C++0x's move semantics? | A problem of "value types" with external resources (like std::vector<T> or std::string) is that copying them tends to be quite expensive, and copies are created implicitly in various contexts, so this tends to be a performance concern. C++0x's answer to this problem is move semantics, which is conceptionally based on t... | I believe that there are several places in D (such as returning structs) that D manages to make them moves whereas C++ would make them a copy. IIRC, the compiler will do a move rather than a copy in any case where it can determine that a copy isn't needed, so struct copying is going to happen less in D than in C++. And... |
4,200,199 | 4,200,237 | Dynamically allocating classes, with Inheritance issue | I am trying to dynamically allocate an array of base(Student) classes, and then assign pointers to derived(Math) classes to each array slot. I can get it to work by creating a single pointer to the base class, and then assigning that to a derived class, but when I attempt to assign to the pointer to a dynamically alloc... | studentList[0] is not a pointer (i.e. a Student *), it's an object (i.e. a Student).
It sounds a bit like what you need is an array of pointers. In which case, you should do something like:
Student **studentList = new Student *[numStudents];
Math *temp = new Math(name, l, c, q, t1, t2, f);
studentList[0] = temp;
In t... |
4,200,208 | 4,200,239 | Path that visual studio uses to look for a resource file | I am using visual studio 2005 to build a c++ project. This project contains a resource file (.rc) file which includes another resource file (also a .rc).
Building this complains
fatal error RC1015: cannot open include file 'WrappedGrid.rc'
Now , I have the directory this is located in the the c++-->Additional Include D... | There's a separate section named "Resources" in the project settings, which contains another "Additional Include Directories" setting.
|
4,200,477 | 4,200,606 | Problem compiling C++ program after adding one argument to a function | All I did was I added a single more argument (iterations) to this function:
/**
* saveImage : save the last image received.
* @param pName name of the file
*/
void GVMsample::saveImageLocal(const std::string& pName, const std::string& pImageFormat, const int &iterations) {
// Check that a video module has been re... | Ok. I have figured out the problem. I was editing the right file. But...
I was editing the file in Windows 7 in a folder shared with Ubuntu 10.10. I was then trying to compile the program in Ubuntu through VirtualBox.
The problem was for some reason I need to reboot the virtual machine or else the files in the shared f... |
4,200,504 | 4,200,546 | Using CTime & asctime to assign time to a string or vector string | I would like to use asctime to assign the time to a string.
time_t rawtime;
time ( &rawtime );
vector<string> TTime;
TTime.resize(10);
TTime = asctime(localtime ( &rawtime ));
I understand asctime is returning a pointer to a string. Would i have to create my own string and assign it the return value of asctime, or is ... | You can construct a string directly from a char *:
string str = asctime(localtime ( &rawtime ));
This doesn't make sense:
TTime = asctime(localtime ( &rawtime ));
You can't assign a single string to a vector of strings. What you can do is:
TTime[0] = asctime(localtime ( &rawtime ));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.