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,885,504 | 4,885,593 | After dragging a file on exe, ifstream fails to open file | I have have the following problem:
When I drag and drop a file to my tool (exe) when ifstream fails to open the file.
If I give it manually though the console it works!
I don't get where the diffenence is, because I am cutting the path and passing just the filename.
Have a look at the code:
int main(int argc, char* a... | I am guessing your current directory is wrong. Don't cut the path off. Anyway you should do error checking / debugging to see why it couldn't open the file. Diligent debugging is essential for solving problems without having to make blind guesses.
|
4,885,676 | 4,888,888 | Remove duplicates from a list<int> | Using STL algorithms (as much as possible) such as remove_if() and list::erase, is there a nice way to remove duplicates from a list defined as following:
list<int> l;
Please note that list::unique() only works if duplication occurs in consecutive elements. In my case, all duplicates have to be eliminated regardless of... | Using the list::remove_if member function, a temporary hashed set, and lambda expression.
std::list<int> l;
std::unordered_set<int> s;
l.remove_if([&](int n) {
return (s.find(n) == s.end()) ? (s.insert(n), false) : true;
});
|
4,885,854 | 4,885,942 | vector in function - how to do return | I've got a function that should read from file line by line, the reading stops when a line does not begin with '>' or ' '. It should store the lines in vector and return it. This is code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <vec... | If I understood you, your getseq() should return a vector of strings. Therefore you should change
string getseq(char * db_file)
to
vector<string> getseq(char * db_file)
And if you want to print it on main() you should do it in a loop.
int main() {
vector<string> str_vec = getseq(argv[1]);
for(vector<string>... |
4,885,903 | 4,886,039 | Why is clang not used more? | I've done a fair amount of programming in C/C++ before, but nowadays it only accounts for a small percentage of the programming I do (scripting languages are much better suited for a lot of the work I do). I worked on some C programming projects the last few days and was surprised how many little syntactical details I ... |
My question is why this tool is not used/mentioned more than it is?
It's probably because of history, and because how we humans generally behave.
Traditionally gcc has been the only real (free) compiler that can be practically used to compile C programs on atleast all the free *nix clones out there. It's what virtual... |
4,885,915 | 4,885,964 | Request for member ______ which is of non-class type | Good Day wonderful computer people of the planet Earth!
Here is the struct in a file called AudioQueue.h:
typedef struct AudioQueueBuffer {
const UInt32 mAudioDataBytesCapacity;
void * const mAudioData;
UInt32 mAudioDataByteSize;
void * ... | AudioQueueBufferRef is an AudioQueueBuffer pointer. mBuffers is an array of these. So when referring to members of elements of mBuffers, you should be using -> not .:
printf("%i\n", &mBuffers[i]->mAudioData );
(I'm guessing you probably don't want the & either - the address held by mAudioData seems a more useful thing... |
4,886,085 | 5,478,932 | How to set the C++ file extension to .cc in Eclipse for files created when starting a new project? | By default Eclipse (CDT) uses .cpp file extension for C++ files. I would like it to use .cc (and .hh) extensions instead but I cannot find such an option anywhere.
edit: To be precise, it creates a .cpp file when I start a new C++ project. Can this behaviour be changed to creating a .cc file?
I would have expected it u... | Was wondering the same and just found this:
How to change the default C++ file extension in Eclipse CDT when creating a new file?
|
4,886,348 | 4,907,028 | msbuild c++ : how do I supply desired version info as command line parameter? | I'm building a C++ application on a CruiseControl.Net buildserver.
The build itself is done by msbuild and through cruisecontrol.net I have the desired version available - but I can't get it to be stamped into the c++ output.
Below is my msbuild project file.
Any comments are appreciated,
Anders, Denmark
<Project xmlns... | In your buildscript, create a file (version.info) which will look like this:
#define BINVERSION 1,2,3,4
#define STRVERSION "1.2.3.4"
You might need to create a small utility to do that.
In your resourcefile, you will have a versioninfo rescource, the start will look like this:
VS_VERSION_INFO VERSIONINFO
FILEVERSION ... |
4,886,405 | 4,887,469 | C++ destructor problem | I have a strange 'destructor' Behavior in C++
Here is the code I call :
_log->OnCommit();
delete _log;
The problem is that when I call "delete _log;" it crash because the variable 'Entries' is invalid !!!!
Do you know why ?
Here is my class code :
struct TransactionLogEntry {
DependencyObject* Object;
bool IsA... | Are you storing naked pointers in the Entries map? If so, you should investigate using boost::shared_ptr (or tr1::shared_ptr if youve got that) instead. This greatly simplifies storage management (for example you can delete the for loop in TransactionLog::OnCommit(), and just call Entries.clear().
|
4,886,478 | 4,886,535 | Functions with class arguments are leaked from a namespace? | I have a small piece of code here for your consideration which puzzles me quite a lot. The strange thing is that it compiles on both Sun Studio and GCC even though I think it should not.
Consider this:
namespace name
{
class C
{
int a;
};
void f(C c);
void g(int a);
}
int main(int argc, char** arg... | It's called argument-dependent lookup (or Koenig lookup). In short, the compiler will look for the function in namespaces that are the namespaces of argument types.
|
4,886,733 | 4,886,898 | Defining own uniforms over re-using built-in OpenGL variables in GLSL. Why? | I am writing a 3D graphics engine.
I've heard that it is bad to use too much uniform variables in your shader program because it can cause slowdown.
On the other side, some say that re-using some built-in variables like gl_TextureMatrix is kind of bad practice.
How should I organize creating my shader programs ?
Shou... | I've never heard that uniforms can slowdown the shader, they are like compile time constants (or should be).
About using built-in variables, it's not recommended to use them, because they are deprecated in OpenGL 3.0 and with the OpenGL Core profile, they are not available. They were removed for sake of programmability... |
4,886,886 | 4,886,925 | Assigning a thread to specific CPU core | AFAIK, it is possible to assign a thread to a CPU core in Linux. (see this). But, my question is can I achieve this functionality using boost and if it is possible, then how? Please, also not that OS can decide which is better for me, but assume that I want to control this behavior in my design.
| Boost is meant to be a cross platform library while the question you linked to points toward a OS specific implementation which to my knowledge is the only way to do what you are asking.
|
4,886,900 | 4,887,475 | Integrating c++ alongside objective-c in iOS project | I've been tasked with adding some c++ code into an iOS project.
The c++ code comes in the form of several libs (.a), and header files with the extension .hpp
I have added these files into the XCode iOS project, and added the paths to the library and header search paths in the project settings, but I am getting compiler... | It could be that the Objective-C file that's including this header isn't in Objective-C++ mode. Usually you fix this by making your implementation a .mm file instead of .m since the latter is pure Objective-C.
|
4,886,978 | 4,887,049 | mouse coordinates in visual-c++ win32 application? | I have created a win32 application in visual-c++ but this programing not printing the mouse coordinates all other events working properly can any one tell me how to get mouse coordinates in visual-c++ win32 application ?
hoping for quick and positive response.
// ttt.cpp : Defines the entry point for the application.
/... | As I mentioned in the comment, the following code block 1) will never be reached, and 2) will not work even if you make it reachable:
case WM_MOUSEWHEEL:
MessageBox(hWnd,rwheel,mouse,MB_OK);
break;
char text[50]; // no case to get you here!
POINT p;
sprintf(text,"Mouse Position... |
4,887,048 | 4,891,255 | does any body know where to find free imap client c++ for windows (not libEtpen) | Im working with libetpen for the last 2 days and trying to compile it in VS express without any lack , does any body knows any good easy to use imap c++ free lib ?
| One of the oldest and most robust IMAP client libraries is UW's c-client. It's free. It provides the IMAP support for mailers like Pine and for platforms like PHP. The c-client library will almost certainly compile on your platform. It hasn't been updated much over the past 3 years, but IMAP has largely been static... |
4,887,061 | 4,889,037 | extract IP from a buffer of bytes | If I have a buffer containing these bytes:
510175126-94-51080
How can I extract the 75126-94-51 part from it(which is the IP) and print the correct IP?
for(int i = 0; i < bytes_recv; i++) { cout << static_cast<int>(temp[i]); } cout << endl;
edit: this is my output: 5 1 0 1 75 126 -94 -51 0 80
| A lot of information is missing from the question. So, you are reading the server reply from the SOCKS protocol. First, the buffer should not and will not have a fixed size of 10 bytes. It has 10 bytes if your address is IPv4 (which coincidently was exhausted a few days ago, time to think about IPv6). If the origin has... |
4,887,235 | 4,887,470 | Inner Workings of C++ Graphics Libraries | As you probably know, C++ has no standard graphics library. Most games use DirectX or OpenGL.
But how do those libraries actually work? In other words, how can the third-party libraries draw graphics if there's no mechanism for it in C++? Are they just written in another language?
| Specifically DirectX and OpenGL work by calling the operating system and/or the video hardware driver. The driver, in turn, does the actual drawing by interacting with the graphical device. The exact details of interaction vary from one video card to another.
Back in the DOS days, C++ programmers could work with the h... |
4,887,365 | 4,887,582 | Help with templatizing byteswapping function, performance hit? | template<int size>
inline void* byteswap(void* __x);
template<>
inline void* byteswap<2>(void* __x)
{
return (*(uint16*)__x >> 8) | (*(uint16*)__x << 8);
}
template<>
inline void* byteswap<4>(void* __x)
{
return (byteswap<4>(__x & 0xffff) << 16) | (bswap_16 (__x >> 16));
}
template<typename T>
inline T bytes... | This is how I'd code it:
#include <iostream>
typedef unsigned short uint16;
typedef unsigned int uint32;
template<typename T> T byteswap(T value);
template<>
uint16 byteswap<uint16>(uint16 value)
{
return (value >> 8)|(value << 8);
}
template<>
uint32 byteswap<uint32>(uint32 value)
{
return uint32(byteswap<... |
4,887,530 | 4,888,617 | Struggling With Vertex And Index Buffers In Direct3D | I've tried for many months to learn how IDirect3DVertexBuffer9 and IDirect3DIndexBuffer9 work. I've read multiple books, e-books and forums and I still can't get the hang of how they work. Can somebody help me understand how they work and how they link together?
PS: I've tried searching through the related questions bu... | IndexBuffers are used for memory & speed optimizations. A indexBuffer is a list of indices that index the vertices in the vertexBuffer.
So say I'm going to render a Flat Quad on the screen with 2 triangles. Each triangle takes up 3 vertices, so to render the quad with just a VertexBuffer I will need 6 vertices.
Now if ... |
4,887,619 | 4,914,029 | Can the key of a line in an .inf file be retrieved using the SetupAPI? | I'm using the function SetupGetLineText ( http://msdn.microsoft.com/en-us/library/aa377388(v=VS.85).aspx ) from the Setup API to read a line from a section in an inf file.
Lines are in the format:
key=value
SetupGetLineText appears to return the value part. That's fine, but I also want to know what the key is for the ... | A long shot:
BOOL SetupGetStringField(
__in PINFCONTEXT Context,
__in DWORD FieldIndex,
__inout PTSTR ReturnBuffer,
__in DWORD ReturnBufferSize,
__out PDWORD RequiredSize
);
with
FieldIndex [in]
The 1-based index of
the field within the specified line
from which the string should be
... |
4,887,767 | 4,887,852 | How to make Qt delegate editors 'sticky' | I'm migrating an application from a homegrown UI to Qt. One of the most important controls is the property panel, which takes an object that implements my reflection API's interface and spits out a dialog box containing editors for all the properties.
I've written an implementation of QAbstractItemModel for my property... | There is the QAbstractItemView::openPersistentEditor() method.
|
4,887,792 | 4,888,345 | Filling a string buffer when using Ocilib | I'm using Ocilib to perform a bulk insert on a Oracle database but I'm having some trouble while filling a string buffer.
The documentation says:
For string/RAW arrays, the input array
MUST BE a contiguous block of data and
not an array of pointers. So to bind
an array of 10 elements for a
varchar2(30) column, binded ... | (Try:
std::vector<char> tab_str(myVec.size() * (VCHAR_SIZE + 1));
...
OCI_BindArrayOfStrings(st, ":s", &tab_str[0], VCHAR_SIZE, 0);
...
int offset = 0;
for(vector<MyClass>::const_iterator it = myVec.begin(); it != myVec.end(); ++it, offset += VCHAR_SIZE)
{
it->m_string.copy(&tab_str[offset], VCHAR_SIZE);
... ... |
4,888,012 | 4,888,030 | tools for creating user-friendly command-line prompt? | I notice that some programs (e.g. sqlite, mysql client) provide a command-line prompt that is very similar in capabilities to the bash's, including:
line editing with left and right arrows, delete, insert, ^K, etc.
history browsing with up and down arrows
^R for reverse i-search in command history
which make me think... | Most of these use the GNU readline library
|
4,888,478 | 4,888,584 | Traversals through Tree.. In order problem with memory access violation | So I wrote up this little peace of code as practice for myself...
But i am getting in travers_inorder function at line *traverse_inorder(p->left)* memory access violation and program crashes.
Why???
Any ideas?
UPDATE: I am using visual studio 2008 SP1 an visual C++ compiler
#include <iostream>
#include <time.h>
usin... | My best guess: looks like you never actually set your final child nodes to NULL in your tree generation procedure. As such, your conditional to stop traversing is never hit, as left and right are just uninitialized pointers. In populate_rand_tree, do the following:
if (cnt == 0)
{
old->left = NULL;
old->righ... |
4,888,652 | 4,888,762 | How should a delegate be returned for unmanaged code when called from a callback? | I have a situation where I am stepping in and out of un/managed code, and I think my methodology is causing me to get a "FatalExecutionEngineError". Specifically, I have a C# callback ("X") which returns another callback ("Y") into C#, where both X and Y are called by unmanaged C++ code (which is called by C#). The e... | Delegates generally use fastcall. But c style function pointers use cdecl. Tag your delegate with the UnamangedFuntionPointer-attribute.
|
4,888,879 | 4,888,916 | Elegant ways to count the frequency of words in a file | What are the elegant and effective ways to count the frequency of each "english" word in a file?
| First of all, I define letter_only std::locale so as to ignore punctuations coming from the stream, and to read only valid "english" letters from the input stream. That way, the stream will treat the words "ways", "ways." and "ways!" as just the same word "ways", because the stream will ignore punctuations like "." and... |
4,889,009 | 4,889,069 | Clearing STL in dedicated thread | In one of my projects, I identified a call to std::deque<T>::clear() as a major bottleneck.
I therefore decided to move this operation in a dedicated, low-priority thread:
template <class T>
void SomeClass::parallelClear(T& c)
{
if (!c.empty())
{
T* temp = new T;
c.swap(*temp); // swap conten... | This is only valid if you guarantee that access to the heap is serialized. Windows does serialize access to the primary heap by default, but it's possible to turn this behaviour off and there's no guarantee that it holds across platforms or libraries. As such, I'd be careful depending on it- make sure that it's explici... |
4,889,218 | 4,889,447 | How to stream float .1 as .1 and not 0.1 | std::ostringstream oss;
oss << std::setw(10);
oss << std::setfill(' ');
oss << std::setprecision(3);
float value = .1;
oss << value
I can check if value < 1 and then find the leading zero and remove it. Not very elegant.
|
I can check if value < 1 and then find the leading zero and remove it. Not very elegant.
Agreed, but that's what you have to do without mucking around in locales to define your own version of ostream::operator<<(float). (You do not want to do this mucking around.)
void float_without_leading_zero(float x, std::ostrea... |
4,889,264 | 5,574,627 | REPL / LINQpad / F# interactive alternative for C++0x? | I love using LINQpad and FSI while developing code for C# and F#. For haskell, I've used hugs. And of course, scripting languages almost always come with a REPL. Pretty much every modern browser ships with a fairly fancy javascript repl/ide.
Is there something similar for C++0x?
Neat features would be:
can incl... | the same place, try cling: http://root.cern.ch/drupal/category/package-context/cling
It's a fairly young project and it is the successor of cint.
It will support all the c++0x features which clang supports.
|
4,889,462 | 4,889,678 | Cyclic dependency, headers and templates | I am having troubles with inclusion model of templates implementation and cyclic dependency of *.h and *.hpp files.
Let us imagine the following inheritance sequences of classes:
A->B->C,
A->A1,
B->B1, C->C1
where A, A1 are abstract classes.
A.h (Abstract class)
#ifndef A_H
#define A_H
template <class A>
{
//s... | You'll need to:
Define each class in its header
Have each header include the dependencies it needs
Not **require** that the dependency succeed in defining the class, and forward-declare it as well.
If you do all of the above you'll allow other code to include the headers in any order but they'll still work in their "... |
4,889,707 | 4,890,490 | Compiler optimization on marking an int unsigned? | For an integer that is never expected to take -ve values, one could unsigned int or int.
From a compiler perspective or purely cpu cycle perspective is there any difference on x86_64 ?
| It depends. It might go either way, depending on what you are doing with that int as well as on the properties of the underlying hardware.
An obvious example in unsigned ints favor would be the integer division operation. In C/C++ integer division is supposed to round towards zero, while machine integer division on x8... |
4,889,740 | 4,890,483 | RWCString - pass by value or const reference | I work on a project that uses extensively RWCStrings. They are refcount-ed and thread safe so I've always wondered if it's better to pass them to functions by value and take advantage of the ref-counting, or by const reference and bypass that (assuming the function is read-only).
Which one is better/faster? Any special... | Const-reference. Not using it means calling the copy-constructor, which means a function call and some access to the memory. Passing by const-reference means, basically, passing a pointer; thus there is zero overhead.
|
4,889,868 | 4,889,901 | Remove C++ char* has point address | Since I changed my project settings, the boolean value below returns false because in the debugger, value of the char* parameter contains pointer address. how do i remove this?
I created this simple example to illustrate (i have to keep char* data type) and I can't do pattern matching to remove the pointer address.
vo... | The == operator cannot compare string values in C; it can only compare their pointers. Use the strcmp function to test whether two strings are equal (it returns 0 if they are).
|
4,889,974 | 4,890,002 | how to convert int to vector<int>? | When I assign int to vector I get an error says "conversion from 'int' to non-scalar type 'std::vector<int, std::allocator<int> >' requested", what should I do?
I have vector varr(4, -1); what is the right way to do "varr[2] = 3"?
| They're two different types. If you want to add an int to a vector<int> do something like:
std::vector<int> vec;
vec.push_back(10);
Update: To set an element within the vector:
std::vector<int> vec(16, 0); // Create a 16 element vector containing all 0's
vec[4] = 10; // Sets the 5th element (0 based arrays) to 10
Ther... |
4,890,079 | 4,890,115 | C++ preprocessor directive limits | I have a C++ pre-processor directive that is something like this:
#if (SOME_NUMBER != 999999999999999)
// do stuff
#endif
999999999999999 is obviously greater than 232, so the value won't fit into a 32-bit integer. Will the preprocessor correctly use a 64-bit integer to resolve the comparison, or will it truncate one ... | Try to use the LL suffix:
#if (SOME_NUMBER != 999999999999999LL)
// do stuff
#endif
In my gcc this work fine:
#include <iostream>
#define SOME_NUMBER 999999999999999LL
int main()
{
#if (SOME_NUMBER != 999999999999999LL)
std::cout << "yes\n";
#endif
return 0;
}
With or without the LL suffix.
|
4,890,167 | 4,890,468 | Passing in a functor to a functor | I'm trying to write a functor that I can pass to std::sort that will sort a vector representing the indicies for another vector of objects based on the comparison of the objects in the vector. Rather than assume that the objects in the vector have a member operator<, I want to pass in a predicate such as I would pass ... | std::sort(aFooIndicies.begin(), aFooIndicies.end(), SortIndexVectorObjectsHelper<CFoo, std::binary_function<CFoo, CFoo, bool> >(aFoo, SortFooByX(FALSE)));
The second type argument in SortIndexVectorObjectsHelper is wrong. The type should be SortFooByX, as shown below:
SortIndexVectorObjectsHelper<CFoo, SortFooByX> com... |
4,890,408 | 4,890,471 | Question regarding object lifetime and deallocation responsibility | I'm sitting here with the following class:
class TagCompound : public Tag
{
public:
// [...] Constructor and other methods
void insert(Tag *t);
// [...] more modifying methods
protected:
std::vector<Tag *> _values;
};
TagCompound::insert(Tag *t)
{
_values.push_back(t);
}
This is all ... | You can use tr1::shared_ptr (or std::shared_ptr if you have a 0x compiler) with custom deleters for statically allocated objects (no-op deleters in this case).
|
4,890,487 | 4,890,625 | What is the meaning of this 'missing template arguments' C++ error | Ahh, C++ templates...
The code I see,
makes sense to me,
but GCC...
it disagrees.
The following code compiles and runs as expected, but if you uncomment that #define, you get the error, which I don't understand. The symbol iterator still has only one thing it can refer to: the typedef in the superclass. So ... | You need to change your MyClass::haskey method too.
bool haskey(const string &s)
{
typename MyClass<C>::iterator it = this->find(s);
return (it != this->end());
}
Explanation of such a behavior is in section "Name lookup, templates, and accessing members of base classes" on http://physics.ucsd.edu/students/cou... |
4,890,497 | 4,890,573 | How do I iterate over a Constant Vector? | I have a vector of Student which has a field name.
I want to iterate over the vector.
void print(const vector<Student>& students)
{
vector<Student>::iterator it;
for(it = students.begin(); it < students.end(); it++)
{
cout << it->name << endl;
}
}
This is apparently illegal ... | You have two (three in C++11) options: const_iterators and indexes (+ "range-for" in C++11)
void func(const std::vector<type>& vec) {
std::vector<type>::const_iterator iter;
for (iter = vec.begin(); iter != vec.end(); ++iter)
// do something with *iter
/* or
for (size_t index = 0; index != vec.size(); ++in... |
4,890,510 | 4,890,733 | C++ STL Vector Sorting - corrupting & zeroing out | The programme that I am developing is aimed to process very large amounts of data and generate at least 2^34 boolean data. These data statically generated & cleared throughout the programme run (only a portion is sorted at each instance) and finally a vector of minimum 2^21 rows of statistical data is passed to the fin... | Your comparator doesn't implement strict weak ordering. For example two items A and B with equal col_Sensitivity and col_Precision, both A < B and B < A are true. As you can imagine, trying to sort with a sort function that doesn't actually provide an ordering can produce undefined behavior.
Thanks to (and quoting) @D... |
4,890,654 | 4,890,698 | C++: address of references? | My knowledge of C++ arcana is a bit rough. Let's say I have the following classes:
struct Bar {
int x;
};
class Foo {
Bar& bar;
public:
Bar* getRealAddress() { return &bar; }
Foo(Bar& _bar) : bar(_bar) {}
};
Bar bar1;
Foo foo1(bar1);
Will foo1.getRealAddress() return the same value as &bar1?
|
Will foo1.getRealAddress() return the same value as &bar1?
Yes.
Basically, a reference is the original value in all but name. It's an alias.
|
4,890,694 | 4,890,967 | libcurl on Windows question | Just downloaded libcurl and built it on Windows, using VC2008. It came with a project, I build it, a static library (release).
I use it in my console win32 app, it does not link, unresolved symbols. So I do a dumpbin /exports on the libcurl.lib and nothing. Puzzling...
As part of the libcurl distro, there is a curl pr... | I am sorry, the answer was "in front of my eyes". I needed to use the compiler directive specific to the static lib which is /D "CURL_STATICLIB".
|
4,890,734 | 4,890,835 | Function that will act like an Strlen C++ | I want to make a function that will do the same as Strlen does, andI get the error: "string subscript out of range". I tried fixing it but has no idea.
heres the code:
#include "stdafx.h"
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int strlen1( string str)
{
... | In short, for a non-const std::stringaccessing an element beyond the string length has Undefined Behavior (more precisely, when using the non-const operator[] for that).
C++98 §21.3.4/1, about std::string::operator[]:
If pos < size, returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). O... |
4,890,753 | 4,890,776 | InetNtop: can't find which header it is using | Anyone knows what header I must include for the use of InetNtop function ?
I tried winsock2.h, ws2tcpip.h and i've include the Ws2_32 librabry. I am using windows 7
This is my error that i get an compile time: InetNtop : function could not be resolved
edit:
char temp[10];
int bytes_recv = Recv(temp, sizeof(temp));
ch... | According to its documentation Ws2tcpip.h is its actual header file.
EDIT:
According to the documentation, using this function requires your code to be compiled for Windows Vista or later. Since you are including the necessary header and yet the function is not visible, I surmise the you have not set the proper defines... |
4,891,006 | 4,891,126 | How to create a folder in the home directory? | I want to create a directory path = "$HOME/somedir".
I've tried using boost::filesystem::create_directory(path), but it fails - apparently the function doesn't expand system variables.
How can I do it the simplest way?
(note: in my case the string path is constant and I don't know for sure if it contains a variable)... | Use getenv to get environment variables, including HOME. If you don't know for sure if they might be present, you'll have to parse the string looking for them.
You could also use the system shell and echo to let the shell do this for you.
Getenv is portable (from standard C), but using the shell to do this portably wi... |
4,891,012 | 4,891,065 | Visual Studio: Creating a simple GUI | I have written a C++ application, which I built using g++.
For the purposes of demonstrating this code I want to create a simple GUI, under Windows, I thought it would be a relatively simple task to create this using Visual Studio's GUI builder.
With some stress I have got to the point where I can build and run the C++... | You are going about it backwards. You need to call your program from the GUI. You can't instantiate a "GUI class" from your main.
If you are just doing a proof of concept, why not create a gui app that shells out and calls your program from the command line. You wouldn't even need to use c++, you could do it in c#.
Ot... |
4,891,067 | 4,891,102 | Weird undefined symbols of static constants inside a struct/class | Either I'm very tired or something weird is happening that I'm not aware of, because the code below is resulting in undefined symbols for Foo::A and Foo::B when linking. This is minimized as much as I could from a larger project, but shows the essence of what I'm looking at.
#include <algorithm>
struct Foo
{
stati... | Definition needed
The code you have provided is non-standard. While you can provide initializers for const static int members directly in the class, you still need to provide separate definitions. It is weird, a kind of unexpected, but you are expected to write it like this:
#include <algorithm>
struct Foo
{
stati... |
4,891,251 | 4,891,894 | Global variable named type is hiding the built-in type() function in Lua | A C++ program I'm working on is using lua for configuration. It sets up several lua functions using a hardcoded script:
luaL_loadbuffer(pmLuaState, headerscript, strlen(headerscript), "header script");
It then loads the configuration lua file (that calls the previously mentioned functions):
luaL_loadfile(pmLuaState, f... | Once the global variable has been modified, the value cannot be recovered- that is, you must prevent the script from setting _G.type in the first place, or store the value beforehand. The second is relatively trivial
local type = type -- problem solved
or you can use environments to solve this problem. This is a prett... |
4,891,335 | 4,891,661 | Friending a template parameter | It's impossible to friend a template parameter because the standard disallows it. How might I get effectively the same thing then?
What I want is basically a type that is unusable outside the object which owns it. Why is rather beside the point but if you really must know, I'm trying to formulate a set of smart point... | You could use this, and then let all the owners inherit from Owner.
You could then use Owner class to wrap privately the methods used in accessible_member.
accessible_member is now accessible to Owner. Friend is not inherited, so you can supply (wrap) the necessary methods so all the classes that inherit Owner can use... |
4,891,471 | 4,904,284 | Why do I receive a SIGSEGV signal while using the Aria robotics API? | I am using the Aria C++ programming libs for mobile robots (http://robots.mobilerobots.com/wiki/ARIA). I am new to this API so I wanted to start with a simple action class derived from ArAction. Now I tried to develop a small test program (an ArAction) in order to
control a simulated p3dx robot via MobileSim. Developme... | ok, found it out now -- for the records: the Aria libs in version 2.7.2 are based on gcc-3 and libstdc++ 5, but Ubuntu 10.10 (which I am using) is shipped with gcc-4 and libstdc++ 6 per default. So I had to manually install the older versions of both packages, now my code is running fine...
cheers!
|
4,891,620 | 4,891,741 | I keep getting an error saying my class does not name a type | I have one class, called A, and it has it's own header file. Then I have another class, called B, which also has it's own header file. They each have their own .cpp file where I implement all of their functions.
I'm trying to have class B have a variable of class type A as a private variable, but I keep getting the err... | The problem is that A.h includes main.h, which includes B.h, which tries to use A.
The good way to organize your files would be this:
main.h:
// not needed
main.cpp:
#include "B.h" // for using class B
int main( int argc, char* args[]) {
B test;
}
A.h:
#ifndef A_H
#define A_H
// no includes needed ATM
class A ... |
4,891,919 | 4,891,986 | How to find a specific object in a STL container | I want to find a specific object in a std::list where the object's attribute meets an input argument.
I found a solution using a unary predicate with find(.) or find_if(.) but in I need a binary function.
Why can't I just let the iterator be the reference of the object (like java) and check the field via the reference?... |
I found a solution using a unary predicate with find(.) or find_if(.) but in I need a binary function.
No – you do need a unary predicate – after all, the find_if function only compares with one object (the current object in the list). Your predicate needs to know which attribute value to compare with:
struct compare... |
4,892,108 | 4,892,122 | C++ STL stack question: Why does pop() not throw an exception if the stack is empty? | Why does std::stack::pop() not throw an exception if the stack is empty and there is nothing to pop?
(I'm designing a specialized Stack for my own code and would like to know the tradeoffs with this approach (which requires one to manually check if the stack is empty) vs. throwing an exception.
My guess here would be ... | You are correct. The C++ standard always prefers performance to safety. But there may be STL implementations that include debug range checks.
|
4,892,191 | 4,892,351 | How to avoid hung processing in C++ through multithreading | In my code the main loop looks like the following
while ( (data = foo()) != NULL ) {
// do processing on data here
}
where foo() is written in C (it fetches the next frame in a video stream, using libavcodec, if you're curious).
My problem is that due to reasons too complicated to go in here, sometimes foo() hang... | On Linux you can use pthread_timedjoin_np to make this happen with two threads really easily.
|
4,892,575 | 4,895,203 | Qt translate strings from non-source files | I have a Qt project which uses XML files. Those XML files contain human-readable text and this text should be translated by using the Qt tools (lupdate, lrelease, QtLinguist).
The question is if it is possible to generate entries in .ts file via lupdate without duplicating the strings from the XML files in a source cod... | We had the same problem : XML files containing human readable strings.
Our solution was to make sure that human readable strings in the XML files were easy to extract (we put them in a LABEL attribute) and we developped a small tool which would parse the XML files, extract the strings, generate a context (by extracting... |
4,892,652 | 4,892,763 | Macro concatenation and further expansion | Can I safely expect this
#define TEMPLATE_DECL_BEGIN_0 template <
#define TEMPLATE_DECL_BEGIN_1 TEMPLATE_DECL_BEGIN_0 typename Arg0
#define TEMPLATE_DECL_BEGIN_2 TEMPLATE_DECL_BEGIN_1 , typename Arg1
#define TEMPLATE_DECL_BEGIN_3 TEMPLATE_DECL_BEGIN_2 , typename Arg2
#define TEMPLATE_DECL(N) TEMPLATE_DECL_BEGIN_ ## N >... | Yes. From 6.10.3.3§3 of the C99 standard:
For both object-like and function-like macro invocations, before the replacement list is
reexamined for more macro names to replace, each instance of a ## preprocessing token
in the replacement list (not from an argument) is deleted and the preceding preprocessing
tok... |
4,892,662 | 4,892,745 | Is there a way to use boost::assign operators without polluting namespace? | I try to avoid "using namespace" in my C++ to avoid polluting my namespace. However, I would like to make use of boost assignment operators to do things like this:
std::vector tmp;
tmp += "abc","def","asdf","foo","blah","dfkef";
Without adding "using namespace boost::assign;" this produces an error:
error: no match ... | You're wrong in your assumption it will pollute the namespace: the using namespace feature was exactly created for this kind of uses.
It will only "pollute" the scope where the using namespace is declared, and in this case, the benefits (using the operators) is by far greater than the drawbacks (this "pollution" is as ... |
4,892,680 | 4,892,701 | sorting a vector of structs | I have a vector<data> info where data is defined as:
struct data{
string word;
int number;
};
I need to sort info by the length of the word strings. Is there a quick and simple way to do it?
| Use a comparison function:
bool compareByLength(const data &a, const data &b)
{
return a.word.size() < b.word.size();
}
and then use std::sort in the header #include <algorithm>:
std::sort(info.begin(), info.end(), compareByLength);
|
4,892,865 | 4,892,878 | what does the compiler do on my method concerning type conversion | Hey, I appreciate if you could tell me what the compiler does on my method. If I call it with Area(10.1,10.1); it returns me 102. So the .01 get cut? Do you have a good site where I can get information about this particular topic? thx for your time!
float Area (float length, float width){
int result;
result = length*wi... | Since you're assigning the value of a float expression to an int, the data simply gets truncated upon assignment (but after the expression is evaluated).
|
4,892,923 | 4,893,002 | C (or C++?) Syntax: STRUCTTYPE varname = {0}; | Normally one would declare/allocate a struct on the stack with:
STRUCTTYPE varname;
What does this syntax mean in C (or is this C++ only, or perhaps specific to VC++)?
STRUCTTYPE varname = {0};
where STRUCTTYPE is the name of a stuct type, like RECT or something. This code compiles and it seems to just zero out all t... | This is aggregate initialization and is both valid C and valid C++.
C++ additionally allows you to omit all initializers (e.g. the zero), but for both languages, objects without an initializer are value-initialized or zero-initialized:
// C++ code:
struct A {
int n;
std::string s;
double f;
};
A a = {}; // This... |
4,892,934 | 4,892,978 | What to return as an iterator when there is no container? | I have an inheritance structure of objects with begin() and end() as pure virtual member functions in the base class. From this objects I'm planning to build a composite structure. This inner objects have std::vector member the begin() and end() get their data from. But in a leaf class there is no vector. Now I try to ... | You could implement a very simple iterator class inside your leaf class that simply return dummy iterators. E.g. the begin() returns the same iterator as is returned by end(). You will need to implement some comparison functions as well. I'm not quite sure how std::iterator deals with this, but maybe that has some thin... |
4,892,994 | 4,899,942 | Using boost::threadpool with boost::bind hangs my program in an infinite loop | I'm trying to parallelise a certain aspect of my program using boost::threadpool (not an official part of boost, link). However, I am finding my program stalls and upon inspection, htop shows me that there are two inactive threads (I suspect in my threadpool) and one thread running at 100% (I suspect my main execution ... | The arguments given to boost::bind will be copied.
The arguments that bind takes are
copied and held internally by the
returned function object. For example,
in the following code:
int i = 5;
bind(f, i, _1); a copy of the value of
i is stored into the function object.
boost::ref and boost::cref can be used
... |
4,893,070 | 4,893,128 | Shielding app from library leaks | I have to use a function from a shared library which leaks some small amount of memory (Let's assume I can't modify the library). Unfortunately, I have to call this function huge number of times which obviously makes this leak catastrophic.
Is there any method to fix this problem? If yes, is there a fast method of doi... | I can think of a couple of approaches, but I don't know what will work for you.
Switch to a garbage-collecting memory allocator like Boehm's gc. This can sweep up those leaks, and may even be a performance gain because free() becomes a no-op.
exit(): The Ultimate Deallocator. Fork off a subprocess, run it 10k times,... |
4,893,108 | 4,893,138 | apache httpd extension help for special protocol | I want to create a apache extension for my special protocol which listens on the same port as apache but on a specific directory or file like PHP. I need this to power my game with a custom server but not with PHP. I can't listen on a different port or different server.
I don't want to create a PHP file or something si... | You don't need a special extension, just register a CGI handler that calls your processing code.
Edit
You can setup apache to proxy requests to your daemon.
You will need to return a properly formatted HTTP response or it wont work. You should read up on Apache and web based communications in general to get a better id... |
4,893,226 | 4,893,322 | Is data encrypted in Silverlight decryptable using C++? | I'm looking at sending encrypted data between a Silverlight client and a native code (C++) server using WCF. I was looking at using the AesManaged class to encrypt data the client sends back to the server, but was wondering about the decryption. There is an assumption that if the AesManaged class is implemented again... | All I can tell you is that it was good to ask; I cannot speak as to this specific interop, but I was trying to communicate with a piece of legacy software that used an older native implementation called AesLib, and I was trying to use AesCryptoServiceProvider. They wouldn't talk to each other, apparently because AesLib... |
4,893,262 | 4,893,508 | How can I run a child process that requires elevation and wait? | Win 7/UAC is driving me crazy.
From within my C++ application, I need to run an executable that requires elevation on Windows 7. I want to fire this thing off and wait for it to finish before proceeding. What's the easiest way to do this?
I normally do this kind of thing via CreateProcess(), but it fails for executab... | Use ShellExecuteEx, rather than ShellExecute. This function will provide a handle for the created process, which you can use to call WaitForSingleObject on that handle to block until that process terminates. Finally, just call CloseHandle on the process handle to close it.
Sample code (most of the error checking is omi... |
4,893,290 | 4,893,318 | Intel C++ Compiler understanding what optimization is performed | I have a code segment which is as simple as :
for( int i = 0; i < n; ++i)
{
if( data[i] > c && data[i] < r )
{
--data[i];
}
}
It's a part of a large function and project. This is actually a rewrite of a different loop, which proved to be time consuming (long loops), but I was surprised by two things :
When d... | You're probably register starved, and the compiler is having to load and store. I'm pretty sure that the native x86 assembly instructions can take memory addresses to operate on- i.e., the compiler can keep those registers free. But by making it local, you may changing the behaviour wrt. aliasing and the compiler may n... |
4,893,504 | 4,893,539 | Can one process overwrite the memory of another process? | My project is composed of 3 processes. Process 1 is a "server" of process 2 and 3 and implements shared memory. Process 2 randomly crashes with application errors, trying to access it's own memory, that has been corrupted somehow.
Error is:
Invalid instruction at some address at memory location some not good address... | Accidentally overwrite the memory of another process (without its cooperation)? No*, because you have to "accidentally" do a lot of things correctly. (You have to "accidentally" open a handle to the process, and also "accidentally" call WriteProcessMemory.)
Intentionally? Yes, using the WriteProcessMemory function.
* I... |
4,893,650 | 4,893,661 | Access Violation with static arrays? | I need to parallelise an application using win32 threads. One of the portions of the code involves modifying an static array using threads.
I pass the array as a parameter like this:
struct threadParameter {
float **array;
int row;
}
An example code would be like this:
// Main
float data[100][100]
for (int i ... | Static arrays are NOT pointers to pointers -- the entire array is a single huge chunk of data, and addressable with a single pointer, namely, the pointer to the base of the array. Hence
tp->array = (float **) data;
is incorrect, because you're dereferencing a number inside the array. (The fact that you needed to cast ... |
4,893,696 | 4,893,708 | Csing for in C or C++ | Like a good programmer I guess I'm trying to be lazy and make the program make anything but I'm starting to think this can't be done this way so here it goes...
I have 27 variables a1,a2,a3,a4,a5,a6,a7,a8,a9,b1,b2,b3,etc,c1,c2,c3,etc...
I want the user to give me the numbers for each but I don't want to do it manually ... | This is what arrays are for. Instead of having variables like a1, a2, a3, b1, b2, b3, etc., just have two arrays:
int a[5]; // a[0] through a[4]
int b[4]; // b[0] through b[3]
Then you can access the variables with expressions like a[i], where i is any integer (provided you don't try to access outside the array bounds... |
4,893,730 | 4,893,763 | C++ build after generating pre-processed output (VS 08) | I noticed that when I select
Project Properties -> Configuration Properties -> c/c++ -> Preprocessor ->
Generate Proprocessed file -> With Line Numbers (/P)
(and other options that generate preprocessed file), no object file is created, so the build fails. It's like the right hand doesn't know what the left is... | The definition of the /P switch is: Preprocess without compiling or linking.
So, it doesn't look like there's a way of doing what you'd like to do. (This isn't surprising. The output from /P tends to be rather large, and I doubt that most folks would want to have it generated for every build.)
|
4,893,815 | 4,893,896 | Calling the constructor of a large array of objects on a stack | I'm modifying some C++ source code and I've noticed the author really went out of their way to allocate everything on the stack. Most likely for the deallocation benefits (are there any performance benefits as well??).
I want to keep the same consistency but I need to create a large array of objects and something like... | The stack shouldn't be used for large blocks of memory. You simply have to pay the higher price of heap allocation in exchange for the benefit of accessing more memory. Another option is declaring an array with static storage duration, but that has other drawbacks (not re-entrant, not thread-safe). Everything is a t... |
4,893,857 | 4,893,864 | C++ g++ can't find 'string' type in class header file | I'm new to C++ but I can't figure out why this won't compile for me. I'm running on a Mac, coding with Xcode, but I'm building with my own makefile from bash.
Anyway, I'm getting two compiler errors that "string" type can't be found, even though I've included . Any help would be welcomed. Code:
//#include <string> // I... | string is in the std namespace.
#include <string>
...
std::string myString;
Alternatively you can use
using namespace std;
However, this is a very bad thing to do in headers as it will pollute the global namespace for anyone that includes said header. It's ok for source files though. There is an additional syntax you... |
4,894,094 | 4,894,140 | Passing an array as a parameter with default values into int main() | I am having difficulty passing an array as an argument into int main() with default values.
For example:
int main(int a){}
works wonderfully. As does
int main(int a = 1){}
Passing int main() an array also works wonderfully:
int main(int a[3])
However, combining these two concepts seems break:
int main(int a[1] = {0,... | This link explains it best:
In C++ it is not possible to pass a
complete block of memory by value as a
parameter to a function, but we are
allowed to pass its address.
That's why you can declare a function with
void foo (int bar[]);
but you can't declare
void foo (int bar[] = {0 ,1});
It has nothing to do wi... |
4,894,120 | 4,894,126 | What does "for(;;)" mean? | In C/C++, what does the following mean?
for(;;){
...
}
| It's an infinite loop, equivalent to while(true). When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).
|
4,894,283 | 4,894,304 | Easiest way to get words of one line from istream into a vector? | istream has the >> operator, but it skips new lines like it skips whitespace. How can I get a list of all the words in 1 line only, into a vector (or anything else that's convenient to use)?
| One possibility (though considerably more verbose than I'd like) is:
std::string temp;
std::getline(your_istream, temp);
std::istringstream buffer(temp);
std::vector<std::string> words((std::istream_iterator<std::string>(buffer)),
std::istream_iterator<std::string>());
|
4,894,303 | 4,894,317 | Help with classes and member variables in C++ | Ok I have two classes: Image and Scene. Now in the Image header file, I defined three private variables: xcoord, ycoord, and index (as well as their respective public getter methods).
I have another class named Scene. Scene is not a subclass of Image. Scene has two member variables: int maximum and Image **images. Now ... | You want to call methods so try:
int beginX = this->images[i]->getXcoord();
int beginY = this->images[i]->getYcoord();
otherwise the compiler is looking for a member variable and not a getter method
|
4,894,413 | 4,894,525 | Creating class objects on the stack | Do class objects declared on the stack have the same lifetime as other stack variables?
I have this code:
#include <stdio.h>
#include <vector>
using std::vector;
#include <string>
using std::string;
class Child;
class Parent
{
public:
Parent(string s) : name(s) { };
vector<Child> children;
string name;
};
... | The Child objects that are in the vector survive for the reason that Mark Ransom pointed out, but the pointer to Parent * that each Child contains (which points to p) becomes invalid just as you expected.
If it appears to work, what likely happend is the compiler's optimizer inlined family(), and then combined the stor... |
4,894,414 | 4,894,512 | Overriding the operator= in C++ | My task is to implement a method that overrides the = operator. I have something written, but honestly I have no idea what I'm doing. Can someone explain what the point of doing this overriding is (not in general, I understand that, but just in this case, Im a bit confused)? What is my method supposed to accomplish? Wh... | What your (inner) code does in English:
//allocate new memory and copy
images = new Image*[source.maximum];
This sets images to a newly allocated array of source.maximum uninitialized Image pointers. Whatever images was pointing to is lost.
Scene(source);
This creates a new temporary Scene object and then throws... |
4,894,503 | 4,927,855 | Testing a DLL with Boost::Test? | I am developing a DLL in C++ and want to perform unit testing of that DLL using the Boost Test Libraries. I read the Boost test manual thoroughly but since I am new, I have the following question:
Should I add test classes in the same VC project in which I am developing my DLL?. Ideally I want to do this but I am confu... | You have 3 ways to do this:
You can definitely do what another reply suggest and build your lib as static. I wouldn't recommend this way though.
You can have one or more separate unit test projects in your solution. These projects will link with your library and with either static or shared version of Boost Test libra... |
4,894,535 | 4,894,701 | How can I output a C + Assembly program trace using GDB? | I'm debugging a nasty problem where #includeing a file(not anything I wrote, for the record) causes a crash in my program. This means, I have working and broken, with only one C(++) include statement changed. Some of the libraries I'm using don't have debugging information.
What I would like to do is get GDB to output ... | You can check the difference between the pre-processed output in each version. For example:
gcc -dD -E a.cc -o a.pre
gcc -dD -E b.cc -o b.pre
diff -u a.pre b.pre
You can experiment with different "-d" settings to make that more verbose/concise. Maybe something in the difference of listings will be obvious. It's usuall... |
4,894,574 | 4,894,660 | Figuring out the class of an inheriting object | I have a linked list of Foo objects. Foo is a base class, which has several classes inherit from it. Say, classes A, B, and C.
I am cycling through this linked list and calling a method some_method, which has 3 definitions; one for each child class:
some_method(A a);
some_method(B b);
some_method(C c);
The linked li... | Depending on your requirements, you may want to consider using polymorphism. To do this, add a pure virtual method to your base node class, and move the corresponding methods to the derived classes.
class Foo
{
public:
virtual void some_method() = 0;
};
class A : Foo
{
public
virtual void some_method()
{
//... |
4,894,854 | 4,894,877 | A question regarding C++ template | Suppose the following template definition (the code is meaningless):
template<class X, class Y>
bool FooBar(const Y& val) { return sizeof(X) + 4; }
I have found that following calling code was legal:
float temp = 0.f;
FooBar<int>(temp);
As you can see, the second type parameter Y can be omitted. A compiler infers the... | That is template argument deduction; it is the same as if you used X as the type of a value parameter of FooBar and called it without any template arguments at all. There is a document with more details at IBM's compiler site.
|
4,894,915 | 4,894,944 | On cygwin making(compiling) code the make command tell me I need 'ver' and 'type' command | I want make freetype in my cygwin, after I input make command
I:\freetype-2.4.4>make
make: ver: Command not found
make: type: Command not found
make: * [dos_setup] Error 127
I don't know what is the ver and type command package name.
Someone can tell me I can add them in my cygwin system
| The FreeType docs specifically state that you should stay away from CygWin, preferring MinGW instead.
That seems to be confirmed by the fact that ver and type are Windows commands, and MinGW is UNIX executables under Windows rather than UNIX executables running under the CygWin DLL emulation environment.
So, here's the... |
4,894,933 | 4,894,966 | How to implement classes with references to each other? | I'm new to C++ programming, so maybe you'd find my question too stupid. Sorry about that, but I'd like to know how to implement this Java-style structure:
#include "B";
class A {
B objB;
}
---
#include "A";
class B {
A objA;
}
The compiler going crazy trying to understand this code. Could you please advise me ab... | This code is illegal in C++ and the compiler is right to reject it. The problem is that if you have a concrete object of type A inside of an object of type B and vice-versa, then there is no meaningful definition of the size of either object. In particular, objects in C++ must each be at least one byte in size. Ther... |
4,895,007 | 4,895,038 | How to print mouse coordinates in VC++ Win32 application? | I know there is a function GetCursorPos and the WM_MOUSEMOVE event but can anybody tell me with example code how best to print the mouse coordinates? I'm not sure how to do this in VC++.
| Try this and let me know .
POINT coord;
GetCursorPos(&coord);
cout << "The mouse is at:" << coord.x << coord.y << endl;
|
4,895,125 | 4,895,144 | compare a character with various character classes in c++ | The problem is that I want to compare the characters in a string, one by one: for each one, does it belong to the alphabet; is it lowercase or uppercase. How could I do this?
this is fine what if i want to compare it like with(+-*^) like there is no standard function.
plz help me out
| #include <cctype>
#include <string>
...
for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
if (std::isalpha(*i))
handle_alphabetic_character(*i);
else
handle_non_alphabetic_character(*i);
EDIT for new requirement:
To find characters in an arbitrary character set, you could use... |
4,895,294 | 4,895,297 | C++ "virtual" keyword for functions in derived classes. Is it necessary? | With the struct definition given below...
struct A {
virtual void hello() = 0;
};
Approach #1:
struct B : public A {
virtual void hello() { ... }
};
Approach #2:
struct B : public A {
void hello() { ... }
};
Is there any difference between these two ways to override the hello function?
| They are exactly the same. There is no difference between them other than that the first approach requires more typing and is potentially clearer.
|
4,895,434 | 4,895,445 | "Efficiency" of passing size_t as an argument | Since size_t can be 32-bit or 64-bit depending on the current system, would it be best to always pass size_t to a function as a reference or const reference so it is always 4 bytes? (if it is 8 bytes you would have to make a copy) Lots of open source code I've looked at do not do this, however if their compiler support... | It's customary to pass all primitive types by value because the operations necessary to copy them are typically just a single assembly instruction. Passing size_ts by value is therefore preferable over passing size_ts by reference.
|
4,895,987 | 4,896,023 | Get size of input in console | How would you get the size input string to console or size of valid characters in buffer?
char buffer[100];
cin >> buffer;
I'm looking to put the '\0' where the input ends.
| The question is moot. When the user types more than 100 characters, you have a buffer overrun. You may crash. If not, you got a security issue at best. You shouldn't do this. Read the input a character at a time, or use a safer string library. gets_s comes to mind if it's supported on your platform.
But in answer... |
4,896,017 | 4,896,093 | How to change the library include path of a binary from bash? | I have a software properly installed on Kubuntu.
Now, I am patching and testing some of its libraries.
How can I start the software from bash so that it loads my patched libraries instead of the official libs?
e.g.:
the official libs are locate in /usr/lib/
my patch libraries (used during test development) are in /h... | From 'man bash':
When a simple command other than a builtin or shell function is to
be executed, it is invoked in a
separate execution environment that
consists of the following. Unless
otherwise noted, the values are
inherited from the shell.
[....]
· shell variables and functions marked for export, along
... |
4,896,076 | 4,896,101 | Getting a HANDLE from a std::ofstream | Is it possible to get the underlying file HANDLE from a std::ofstream (Visual C++ 2005)?
This is the opposite of this question:
Can I use CreateFile, but force the handle into a std::ofstream?
The reason I want to so this is to modify attributes of the file (e.g. creation time) without having to open the file with Crea... | The C++ standard does not provide any means for specifying or retrieving the raw file descriptors of an ofstream, so I don't believe this is possible. What is possible, though, would be to build a custom streambuf class that implements stream buffering to and from a HANDLE, then to define a custom ostream type that us... |
4,896,238 | 4,896,270 | Overloading operator -> | Here is my code example:
class X
{
public:
void f() {}
};
class Y : public X
{
public:
X& operator->() { return *this; }
void f() {}
};
int main()
{
Y t;
t.operator->().f(); // OK
t->f(); // error C2819: type 'X' does not have an overloaded member 'operator ->'
... | The problem is that operator -> is supposed to return a pointer, not a reference. The idea is that operator -> should return a pointer to the real object that should have the pointer applied to it. For example, for a class with an overloaded operator ->, the code
myClass->myValue;
translates into
(myClass.operator->... |
4,896,800 | 4,897,419 | Style sheets in Qt for Nokia | I am developing an application for Nokia devices using Qtcreator. But the problem is that the UI is not so attractive. In the desktop apps we can use Style sheet for changing the design & color of the widgets but can we use the same for the Nokia also?
| Hey sample example for how to add style sheets s here.
|
4,896,810 | 4,896,854 | Can a function throw derived class exception when its exception specification has base type? | i have the following code.
class Base{};
class Derived: public Base{};
class Test
{
public:
void fun() throw(Base)
{
throw Derived();
}
};
int main()
{
Test ob; ob.fun();
}
Can function fun() throw exceptions of derived types when its exception specification list has base type ?
| Since Derived derives from Base, it technically is-a Base. So, yes, you can throw derived exception types if your method signature lists their base type.
But note that, as @MSalters says, there are issues with exception specifications.
|
4,896,941 | 4,897,204 | Most efficient way to capture and send images from a webcam in a network | I am writing a simple videophone ( for study ) and I would to know what APIs I have to use to capture and send images from a webcam in a network.
P.s. I wouldn't use complex library like OpenCV.
| You can use Windows Image Acquisition (WIA) or/and DirectShow. Another good alternative is Microsoft Media Foundation(chapter on capturing video).
Mind you that this are cumbersome apis which make this no easy task and you might end up better by using OpenCV.
As for the network part, that's up to your design and prefer... |
4,897,024 | 4,897,061 | including nested classes | I have a container class with several iterators as nested classes. The structure is something ilke this:
class Grid
{
protected:
class Iterator
{
Iterator(Grid* g) : grid(g){}
Grid* grid;
}
class MoreIterator : public Iterator
{
}
}
Now I wanted to move the iterators in a header... | Don't put the nested class declaration in a separate header file. It's bad design and will confuse the hell out of anyone else who has to maintain your code. If the nested class is too big, unnest it and put it in it's own compilation unit (h/cpp combo).
|
4,897,079 | 4,897,184 | Get mouse position in a QImage | I need to get the coordinates of a QImage of where the mouse is currently hovering. Like in image editing programs, where we can see the coordinates of the pixel the mouse in currently hovering.
| Call setMouseTracking(true), and override mouseMoveEvent. Your mouseMoveEvent function will be called whenever the mouse moves inside the QImage. (You have to create a subclass of QImage to do this.)
|
4,897,122 | 4,897,147 | Is it possible to link lib dynamically like a DLL? | This is interview question.
Is it possible to link lib dynamically like a DLL ?
For example, for DLL, we use LoadLibrary and call exported functions.
Is it possible to use lib file in same manner?
| No. .lib library are statically linked, and that is the purpose they're created for, to resolve the name symbols at link-time by Linker, and link-time occurs before runtime. They're often referred to as "static libraries" (that is why I added this tag in your question!). That is the brief story of lib.
However, you can... |
4,897,300 | 4,897,351 | find last location in a string | i have a string
a = "hai my name is prasanth Madhavan"
and i would like to replace the space btw prasanth and Madhavan with a period.
when i use a.find("prasanth") it gives the location of p i.e the begining of the search string. is ther a way to get the location of the ending of the string using find??
| #include <string>
std::string str("hai my name is prasanth Madhavan");
std::string prasanth("prasanth");
std::size_t prasanth_pos = str.find(prasanth);
if (prasanth_pos != std::string::npos && prasanth_pos + prasanth.size() != str.size())
str[prasanth_pos + prasanth.size()] = '.';
|
4,897,383 | 4,897,414 | How do I manage the deletion of an object that has been passed via a signal slot? | I have just added webcam support to my application using videoInput library and OpenCV.
The video stream is in a QThread (producer) and emits a signal sending out a QImage* for my application to update the graphics item which needs it.
The memory management side of it is that I delete the QImage* in the consumer slot o... | Using smart pointers should do most of the work for you: QSharedPointer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.