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 |
|---|---|---|---|---|
6,632,065 | 6,635,893 | What is the use of boost::visit_each? | I read the documentation on visit_each, but can't really see what exactly it does, as well as the general use for it, if every user has to overload it anyways. Someone care to enlighten me?
Edit: Maybe I'm just so confused because the following is the whole content of <boost/visit_each.hpp> and I just don't see any "m... | I suspect the important part of that documentation is this line: "Library authors will be expected to add additional overloads that specialize the T argument for their classes, so that subobjects can be visited." In other words, there is no general use for it, it is just a common name for any visitor-based introspecti... |
6,632,453 | 6,632,471 | Weird thread execution order? | I wrote a small program to see the amount of overhead there is to create a thread.
Here is the program (I wrote it quickly so it isn't the best):
#include <iostream>
#include <pthread.h>
void * lala(void * cake) {
int * hi = (int *)cake;
std::cout << *hi << '\n';
}
int main(void) {
pthread_t thread;
for (int i = ... | First thing, you are passing the address-of a local variable to the thread, which is constantly changing. So, when the thread gets time to read it, the content of i would already be changed.
Why can't you just pass i instead of &i, where variable is just of 4-bytes (i.e. fits in pointer)?
Secondly, you shouldn't be con... |
6,632,533 | 6,635,484 | How can I pull variadic template arguments off from the tail instead of the head? | For silly reasons I'll not go into here, I need the commented out line to work and the line above it it to not work:
template<uint _N, typename... _Args>
struct PartialTuple;
template<uint _N, typename _Arg, typename... _Args>
struct PartialTuple<_N, _Arg, _Args...>: PartialTuple<_N-1, _Args...> {};
template<typename... | Here's a solution: Instead of truncating N from the back, I just truncate sizeof...(Args) - N from the front:
#include <tuple>
/* Concatenator helper */
template <typename T, typename Tuple> struct cat;
template <typename T, typename ...Args>
struct cat<T, std::tuple<Args...>>
{
typedef typename std::tuple<T, Args.... |
6,632,541 | 6,632,557 | What's wrong with this class? | I'm trying to create a simple static C++ library that I can link it into a MonoTouch app and invoke the functions via MonoTouch. I'm trying to compile the static library in XCode and have this (edited since ildjarn fixes):
class MyClass
{
public:
static int Get5() { return 5; }
static int Get10() { return 10; }... | Member accessibility decorators are followed by a colon in C++, like labels or switch cases --
class MyClass
{
public:
static int Get5() { return 5; }
static int Get10() { return 10; }
};
Also, accessibility decorators have no effect on namespace-scoped types in C++, so public class MyClass is nonsensical.
|
6,632,553 | 6,633,497 | mix cobol with c++/C | I tried to mix COBOL code with C++, but i not have success :(
I see this topic in IBM forum: http://publib.boulder.ibm.com/infocenter/comphelp/v111v131/index.jsp?topic=/com.ibm.aix.cbl.doc/PGandLR/tasks/tpsub17.htm ( Calling between COBOL and C/C++ programs )
But, when I go to build this code, I receive several a lot... | The IBM docs are specific to their compiler and OS. Try this instead
OpenCobol wiki
|
6,632,571 | 6,632,795 | Connect to SqlServer with socket programming | I'm wondering if there is a direct way of connecting to SQL Server. In other words, How ADO.NET is connecting to SQL Server?
| For academic exercise kind of work the TDS protocol is described at Tabular Data Stream Protocol Specification and there is a free implementation at FreeTDS. Do you have any real motive to re-invent the wheel?
|
6,632,580 | 6,633,308 | Having a pair<string, string> how to find if its part of some pair in map<string, string>? | We have a pair of strings for example such pair Accept-Language : RU , and we search thru map, for example of http request headers. All we ned to know if there is such pair in map or not - a bool value. How to do to a soft search meaning we do not need to find exact same pair but pair like Accept-Language : ru-RU,ru;q=... | First of all, if you are using a map, you cannot have multiple entries with the same key. E.g. you can't have both Accept-Language : RU and Accept-Language : ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4 because they have the same key `Accept-Language'. Perhaps in your case you should use a vector of pairs, or a multimap.
Next, ... |
6,632,584 | 6,632,593 | How to use delete[] when pointer outside memory allocation? | Note that the question has been changed and no longer matches the answers
I'm trying to create memory to hold a buffer of floats (here, 4 floats).
I've allocated the memory, and all the 4 values in the memory are zero.
The loop of course iterates 4 times, but the 4th time moves ptr to outside the memory that I've alloc... | Copy the pointer before you increment it.
int inFramesToProcess = 4;
float *ptr = new float[inFramesToProcess]();
float *ptr_copy = ptr;
for(UInt32 i = 0; i < inFramesToProcess; ++i) {
ptr_copy++;
}
delete[] ptr;
Or just don't use pointers for dynamic arrays, use a vector instead. Then you don't hav... |
6,632,606 | 6,632,683 | where does node.js fit within the web development context? | I know that node.js is said to be "event-driven I/O" server-side javascript hosted on V8 Javascript engine. I visited the node.js website, and then read the wikipedia entry, but cant quite get the whole idea of where to use it and how it will be useful. "Event-driven I-O"? "V8 Javascript engine"? In some context though... | The node.js server is, in simple terms, a replacement for something like the Apache web server - but it is largely written in JavaScript which runs on the server (executed by the V8 engine) rather than on the client side. It can be extended with 'native code' modules (written in e.g. C++) wrapped in a JavaScript interf... |
6,632,793 | 6,632,845 | Create two windows in one application? | It might be a simple question, but I don't know where to start the search for the answer. How do I create two individual windows interface in one application using native winapi? Do I put two CreateWindow() functions using same HINSTANCE? What if I want a login screen windows and the content page such that login screen... | You're over-thinking it. To create two windows, call CreateWindow twice. It's just that simple.
Calling DestroyWindow does not cause your program to exit its message pump. Calling PostQuitMessage is what does that. So don't do that.
When the button is clicked, destroy the one window and create the other. There are no t... |
6,632,915 | 6,632,937 | Is the memory in std::array contiguous? | Is the memory in std::array contiguous? Is the following valid/good practice?
std::array<type1,Num> arr = //initialize value
type1 * ptr = &arr[0];
Could I then pass ptr to functions expecting a c-style array?
| Yes, it is contiguous, as it is basically (and actually) a type arr[10];, but with STL like interface. It also doesn't decay to a pointer on the slightest provocation.
You can safely pass &arr[0] to a function expecting a C-style array, that's the design goal of it. To use it with the STL algorithms however, just use t... |
6,632,971 | 6,632,991 | What is the difference between std::array and std::vector? When do you use one over other? | What is the difference between std::array and std::vector? When do you use one over other?
I have always used and considered std:vector as an C++ way of using C arrays, so what is the difference?
| std::array is just a class version of the classic C array. That means its size is fixed at compile time and it will be allocated as a single chunk (e.g. taking space on the stack). The advantage it has is slightly better performance because there is no indirection between the object and the arrayed data.
std::vector ... |
6,633,056 | 6,633,117 | Grab Program's Console Output | I am creating a network administration program for a company I'm currently doing some contract work with (irrelevant I suppose)
As part of the program, I would like to have a console/telnet(type) clone. I have a working directory system, where I can essentially read all files in directories, and change directories. I a... | As Jerry mentioned, what you're looking for is a pipe (CreatePipe). Two of them actually - one for input and one for output. You then create the new process with them set as stdin/stdout/stderr in STARTUPINFO passed to CreateProcess. You can then use WriteFile, ReadFile, PeekNamedPipe and friends to communicate.
A comp... |
6,633,188 | 6,749,180 | InternetReadFile reads only 10kb | i'm trying to download file from http server using WinINet library calls. It works perfectly fine on my local web server. but when i'm trying download something from the internet, InternetReadFile reads only ~10kb of any file (text or binary). TRANSFER_SIZE = 4096 in the example below, thus there are two reads by 4kb a... | I read the response as text and it was the "404 error" respond from the web server - file was missing. So it's useful to read the responses ;)
And libcurl looks like nice replacement of the WinINet library - easier to start with, a lot of options.
|
6,633,471 | 6,634,539 | DLL export and inheritance in C++ | I'm trying to export a class and its base class from a DLL like this:
#ifdef MY_EXPORTS
#define DECLSPEC_TEST __declspec(dllexport)
#else
#define DECLSPEC_TEST __declspec(dllimport)
#endif
class DECLSPEC_TEST BaseClass
{
// stuff.
};
class DECLSPEC_TEST DerivedClass : public BaseClass
{
// This class o... | Ok, I don't know how to explain this but I put the implementation of the derived class' constructor in a CPP file instead of within the class definition and the error went away...
thanks everybody :)
|
6,633,515 | 6,634,105 | MFC app Assert fail at CRecentFileList::Add on Command line FileOpen | I'm using VS2010 and Windows 7, and my app is SDI shared DLL, upgraded from VC6. After installing my application, if the user double-clicks the registered file type, the application crashes at the MFC function:
void CRecentFileList::Add(LPCTSTR lpszPathName, LPCTSTR lpszAppID)
{
// ...
#if (WINVER >= 0x0601)
// ...
#i... | The comment you inserted in your code contains the answer:
// Crash here: "hr = 0x800401f0 CoInitialize has not been called."
The HRESULT value is telling you that you need to call the CoInitialize function in order to initialize the COM library for your application's thread.
Of course, the message is a little bit ou... |
6,633,538 | 6,634,574 | Static Assert inside struct allowed? | I have several template settings struct, is it ok, to use static asserts in these structs?
template<typename T, int N, (and so on...)>
struct Settings{
static const int n = N;
STATIC_ASSERT(n == 5);
typedef typename T GAGA;
}
Thanks for your responses!
| You would have to look at the STATIC_ASSERT macro definition to see what is exactly going on. A common implementation of STATIC_ASSERT that can be used there could be:
#define STATIC_ASSERT( x ) \
typedef char static_assert_failed[ (x) ? 1 : -1 ]
Usually there is a bit more trickery to get the line number to be par... |
6,633,574 | 6,633,600 | error in c++ code "expected constructor, destructor, or type conversion before ‘(’ token" and "no matching function for call to ..." | really trying to solve the errors, double checked everything. please help.
New to c++, please be kind.
header file (.h)
#ifndef GUARD_Optimized_quick_sort_h
#define GUARD_Optimized_quick_sort_h
#include <vector>
#include <list>
#include <iterator>
using namespace std;
template <class T> class optimized_quick_sort
{... | You're missing the return type in all of your function implementations, as well as a little typename for the iterators, example:
template <class T>
int optimized_quick_sort<T>::quick_sort( typename vector<T>::iterator begin, typename vector<T>::iterator end)
^^^ ^^^^^^^^ ... |
6,633,663 | 6,634,568 | namespaces ; expected unqualified id before ')' token ; invalid use of struct | I am new to c++ and am trying to understand namespaces and how they work
I thought i'd code up a simple "hello world" program using namespaces but as it turned
out, it seems to have backfired on me and i am getting a bunch of weird errors.
Here is my code:
#include <iostream>
namespace names
{
using... | This has nothing to do with namespace.
In C/C++ the rule for declaring a function is:
returnType functionName(functionArgument1,functionArgument2,...);
Your way of declaring the function does not follow the C/C++ rule. What you have is:
void class hello();
It should be:
void hello();
Probably you are confusing it wi... |
6,633,717 | 6,633,728 | C++ ifstream::read() and C arrays | It seems to be a general consensus that C arrays are bad and that using the smarter alternatives, like vectors or C++ strings is the way to go. No problem here.
Having said that, why does the read() member of ifstream input data to a char*...
The question is: can I input to a vector of bytes somehow using the STL alone... | You can read directly into an allocated vector (I have no ability to compile this from here so there might be typos or transposed parameters etc...) but the idea is correct.
vector<char> data;
data.resize(100);
// Read 100 characters into the storage of data
thing.read(&data[0], 100);
|
6,633,971 | 6,634,282 | Unable to pass null function-pointer as template argument | I would like to pass a function as a template argument to another function so that it can be stored and called back later. In some cases, I want to pass NULL for the call back, but I'm having trouble. Here's an example of what I'd like to be able to do:
#include <iostream>
struct Foo {
int i;
};
template <typename ... | This can be solved by using template overloads. Instead of having just one ´T_new` signature you´ll have one signature for the NULL case and one for the other:
// Unused signature, no implementation so using this will result in link error
template<typename T, typename F>
T* T_new();
// NULL overload (NULL is an int)
te... |
6,634,358 | 6,634,382 | What does it mean to set the declaration of a function equal to 0? How can you assign an integer to a function? | I was browsing through the sources of a (prefer not to name) GUI Toolkit which wrapped up the Windows API when I found the following function definition in the window class:
virtual LRESULT CALLBACK wndProc (HWND, UINT, WPARAM, LPARAM) = 0;
What is happening here? How can you assign a function to an integer? Or does ... | That line of code defines a pure virtual function in C++. It has nothing to do with the otherwise tricky Win32 API or GUI code in general.
A pure virtual function is a virtual function that is used when the designer of the class wants to force derived classes to override the function and provide their own implementatio... |
6,634,387 | 6,637,842 | C++ Statically linked shared library | I have a shared library used by a another application beyond my control which requires *.so objects. My library makes use of sqlite3 which needs to be statically linked with it (I absolutely need a self-contained binary).
When I try to compile and link my library:
-fpic -flto -pthread -m64
-flto -static -shared
I end ... | You shouldn't use the -static flag when creating a shared library, it's for creating statically linked executables.
If you only have a static version of the library, you can just link it in using -lsqlite3. But if there's both a dynamic version(.so) and a static version, the linker will prefer the dynamic one.
To instr... |
6,634,543 | 6,634,570 | Why does it cout in something that we doesn't cin in arrays? | When the following program is fead the following input (reading from cin):
1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1
The output is surprising:
1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1
#include<iostream>
using namespace std;
int main()
{
int arey[3][3];
int i,j;
for(j=0;j<=3;j++)
{
for(i=0;i<=3;i++)
{
... | Arrays use 0 based indices, so the valid range of indices for your
int arey[3][3];
are 0 <= i < 3 and 0 <= j < 3
So you need to change the condition in your for loops to be strictly < instead of <=
|
6,634,572 | 6,634,594 | C++ classes refer to each other ( => error + field '...' has incomplete type) | Classes in my application work like this: Creature has few fields with Actions. When these Actions must be run Creature calls someActionField->do(this). Action has method viod do(Creature* cr) and all information about what to do with this Creature.
So, Creature must have Action field and know that Action has do method... | You Creature class has members of type Action. The compiler needs to know the full definition of the Action class to compile that - an incomplete type as produced with a forward declaration is not enough.
The Action class only requires a pointer to a Creature object in that header. In that case, the compiler only needs... |
6,634,687 | 6,634,844 | initialize a member variable inside of constructor? (this should be very basic...) | Edit: I need to refactor this question, it has too many extraneous components to be clear what my question (which is about C++) is. But anyone who can understand what I am asking please do answer.
I have a class which represents a thread. The threading library I am using, TinyThread++, starts a thread by creating a thr... | You can do the following: initialize m_routine using a function, that will return a new E_threadRoutine like so -
m_routine(createThreadRoutine(func, arg))
and have createThreadRoutine return a new E_threadRoutine whichever way you want. Then, you can initialize m_thread with (thread_function_common, m_routine). The ... |
6,634,691 | 6,634,786 | Safe way of casting void* to something higher? | I've got a generic class that manages resources of all kinds of types, but since I don't want to create an instance of ResourceManager for every T there is (thus having one resource manager for each type T), I have to make the type of T unknown to the ResourceManager class.
I do this by saving a map of void* pointers ... | You can easily do this, if you extend your saved value type - make it a struct that also saves a type_info object:
#include <type_info>
struct ResourceInfo
{
std::type_info const& info;
void* ptr;
};
// ...
// just to give you the general idea
template<class Res>
void CacheResource(std::string const& location, R... |
6,634,730 | 6,634,783 | Is a virtual destructor needed for your Interface, if you always store it in a shared_ptr? | Since boost::/std::shared_ptr have the advantage of type-erasing their deleter, you can do nice things like
#include <memory>
typedef std::shared_ptr<void> gc_ptr;
int main(){
gc_ptr p1 = new int(42);
gc_ptr p2 = new float(3.14159);
gc_ptr p3 = new char('o');
}
And this will correctly delete all pointer thanks... | I would still follow the common rule for classes that are meant to be derived:
Provide either a public virtual destructor or a protected non-virtual destructor
The reason is that you cannot control all of the uses, and that simple rule means that the compiler will flag if you try to delete through the wrong level in ... |
6,634,840 | 6,634,885 | Can I read any readable valid memory location via a (unsigned) char* in C++? | My search foo seems lacking today.
I would like to know if it is legal according to std C++ to inspect "any" memory location via an (unsigned(?)) char*. By any location I mean any valid address of an object or array (or inside an array) inside the program.
By way of example:
void passAnyObjectOrArrayOrSomethingElseVali... | C++ assumes strict aliasing, which means that two pointers of fundamentally different type do not alias the same value.
However, as correctly pointed out by bdonlan, the standard makes an exception for char and unsigned char pointers.
Thus, in general this is undefined behaviour for any pointer type to read any deliber... |
6,634,888 | 6,634,905 | Why can't I initialize a variable-sized array? | GCC gives no error when you initialize a variable-sized array as long as the variable is const, but when it isn't, it won't compile.
What's the reason behind this? What's so wrong with doing:
int size = 7;
int test[size] = {3, 4, 5};
That won't compile at all, but if I don't initialize test[] then it does compile! Tha... |
The size of the array must be a constant integral expression.
An integral literal is a constant integral expression. (int arr[5];)
A constant integral variable initialized with a constant expression is a constant expression. (const int j = 4; const int i = j; int a[i];)
A constant variable initialized with a non-cons... |
6,635,025 | 6,638,285 | unordered_multimap<string, string> to map<string, string> soft search, How to do such thing and how to preprocessed maps for faster search? | We have a map<boost::shared_ptr<service>, rules> service_map where rules is
struct rules
{
boost::unordered_multimap<string, string> set_of_rules_1;
boost::unordered_multimap<string, string> set_of_rules_2;
}
In my case of rules are pairs from of http request headers and arguments, for example in one such unordered_mu... | This is a tall order, and you'll have to develop some of the logic yourself. However, here's a skeleton solution:
1) Write a function that ranks rules according to their relevance for a given set of data:
int relevance(const rules & r, const data & d); // write this
2) For each piece of data, create a sorted ranking o... |
6,635,882 | 6,635,912 | When should I pass "T* const&" type of pointer ? | I would pass T*& pointer, when I am intending to change the pointed value inside the function:
void foo(char *&p)
{
p = (b == true)? new char[10] : 0;
}
But I am not able to get what is the use case for T* const& kind of pointer (since that pointer is not changeable)? I mean why should not I pass simply T* const ?
v... | You would use a T* const & as a parameter if the value of the pointer object might be changed by something external to your function and you wanted to be able to observe changes to the value of the pointer object or if you wanted to store a reference or pointer to the pointer object for later reading.
A T* parameter (e... |
6,635,923 | 6,635,978 | queue management system | I want create simple Queue Management system for my project. System will work like this example. Lets say there are 3 offices
Person pushes to button "Office 1"
Software generates auto-incremented number, adds him to queue (db) and prints check with generated number.
And shows last 3 values of queue on big screen.
Wh... | I am not 100% sure I have understood your requirement, but I will assume the question comes down to the fact that you need some kind of message queue solution.
Windows comes with a standard message queue solution which you can install from the windows installation disks and use from .NET using the System.Messaging name... |
6,635,981 | 6,636,776 | Initialize C struct data member in a C++ wrapper class | The essential problem has basically already been answered elsewhere on this site, but what I really want is opinions on the best way to implement my class in terms of practicality and aesthetics, and if there are any subtleties involved. So bearing that in mind, here's my question:
I have a simple encryption program th... | Yes, you can use the ctor-initializer, you just need to add a helper function:
Stream::Stream() : stream_(def_stream) {}
static lzma_stream def_stream()
{
lzma_stream tmpStream = LZMA_STREAM_INIT;
return tmpStream;
}
Among other things, this allows you to initialize a const aggregate member. And almost all compi... |
6,635,985 | 6,636,034 | Platform independent parallelization without changing the framework? | I hope the title did not mislead you.
My problem is the following: Currently I try to speed up a raytracer and this is done with the help of the graphics card. It works fine despite the fact that it got slower by this. :)
This is caused by the fact, that I trace one ray on the whole geometry at once on the graphics car... | use either Thread Building Blocks or boost::thread.
http://www.boost.org/doc/libs/1_46_0/doc/html/thread.html
http://threadingbuildingblocks.org/
As far as threadpool/on-demand-threads - threadpool is generally better idea as it avoids creation overhead.
Number of waiting threads is gonna depend on the underlying syste... |
6,636,202 | 6,640,221 | Qt Model/View Delegation: How to simply translate text data? | I'm using a QSqlTableModel as a data source and a QTableView to display the data.
Also I'm using a QDataWidgetMapper to edit the data in a seperate form.
All I want to do is translate a Date/Time string from one format in the database (2011-07-09T18:21:49) to a different format to show in the table (18:21) and another ... | Ok I think this might be the right way to do it (an intermediate data model),
but now I used a QItemDelegate.
I did the following and it worked:
class DateTimeDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit DateTimeDelegate(QObject *parent = 0);
void setEditorData(QWidget *editor,
const ... |
6,636,548 | 6,636,654 | what does the following c++ code do | I know its very naive question, but i am not able to understand what the following code does.
#include <malloc.h>
#define MAXROW 3
#define MAXCOL 4
int main(){
int (*p)[MAXCOL];
p = (int (*)[MAXCOL])malloc(MAXROW*sizeof(*p));
}
Please provide a complete explanation including the type and size of p.
It is just for lear... | As far as I can tell, it's gibberish. You probably meant (int(*)[MAXCOL]).
In C it means that the programmer who wrote it doesn't know how void pointer typecasts work.
In C++ it means that you are allocating an array of arrays. p is an array pointer, so *p is an array of size MAXCOL, and you allocate MAXROW such arrays... |
6,636,579 | 6,636,750 | Which technique for breaking out of a 'visitor' loop is easier for compilers to analyze? | I'm currently generating code intended for a C++ compiler. I'm generating a class that will take a visitor object, call the accept method on it with several objects. However, I want the visitor to have the ability to 'break', that is, the visitor should have a way of indicating that it wants to stop the rest of the acc... | On the first option your unoptimized simplified code will look something like this:
call visitor.accept o1
branch on result is false to end
call visitor.accept o2
branch on result is false to end
call visitor.accept o3
branch on result is false to end
call visitor.accept o4
So how can the compiler optimize that? Well,... |
6,636,658 | 6,636,763 | Can typedef of member function be simplified with helper template classes? | I recently found that function pointer syntax can be simplified when using the following helper class:
template<typename Sig>
struct Fun {
typedef Sig* Ptr;
};
It allows me a pointer to void() as follows:
typedef Fun<void()>::Ptr fun_ptr;
fun_ptr f = foo;
I would like to create a similar utility for to create a t... | template<typename T, typename Sig>
struct convenience {
typedef Sig T::*type;
};
struct test {
void member() {}
void cmember() const {}
};
static_assert( std::is_same<
convenience<test, void()>::type
, decltype(&test::member)
>::value, "Oops" );
static_assert( std::is_same<
co... |
6,636,698 | 6,636,726 | Assigning references from an array to another array - "warning: target of assignment not really an lvalue" | Consider the following code. I've included excessive couts for clarity (at least on my end):
#include <iostream>
using namespace std;
int main(){
double *array1;
array1 = new double[10];
array1[5] = 10;
//the following 2 lines return the same thing
cout << "array1 = " << array1 << endl;
cout << "&array1[0] = " <... | The expression subarray1 is an lvalue to your pointer object of the same name. This pointer points to the first element of the dynamically-allocated buffer.
The expression &subarray1[0] is an rvalue pointer that points to the first element of the dynamically-allocated buffer (and thus it evaluates to the same value as ... |
6,636,731 | 6,653,477 | Sleeping a boost thread for some nanoseconds | I want a boost thread to sleep for some nanoseconds. The following code is a sample that compiles without errors. However, it does not work as expected and I cannot figure out why.
#include <iostream>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time.hpp>
//Bu... | The BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG changes the size of ptime.
boost::this_thread::sleep is a compiled function, which was compiled (on your distro) without that define, so it expects microsecond-precision ptime arguments. You're passing nanosecond-precision ptime arguments, and the function fails.
If you extrac... |
6,636,755 | 6,637,011 | Release build problems; Passing a std::string object to a static library function | This is the first time I've tried to use the release build with Visual C++ 2005 and it seems there's definitely some differences.
My current error is:
Unhandled exception at 0x6ef7d628 (msvcr80d.dll) in <program_name>:
0xC0000005: Access violation reading location 0x6c2e6769.
I look into the call stack and it turns ... | The #1 way to fix Cannot open precompiled header file" is to do a clean/rebuild all.
After that, I would start with the differences between the release and debug builds. Either open the project file or compare the project settings from within visual studio.
Get the library to build in release before worrying about the ... |
6,636,847 | 6,637,317 | Odd results using glTexImage2D | I've been trying to figure out how glTexImage2D works and an seeing some odd results from some pretty clear-cut code. My code simply draws a rough circle into a 256*256 length unsigned array and then sends that data out to become a texture. The texture displayed however is turning out as variations of red and orange no... | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)data);
First the positive things. You use a sized internal format (GL_RGBA8, rather than GL_RGBA). This is very good; keep doing that. You have a clear understanding of the difference between the internal format (GL_RGBA8) and th... |
6,636,915 | 6,636,928 | String class e char in C++ | When I have
char anything[20];
cout << sizeof anything;
it prints 20.
However
string anymore;
cout << sizeof anymore; // it prints 4
getline(cin, anymore); // let's suppose I type more than one hundred characters
cout << sizeof anymore; // it still prints 4 !
I would like to understand how c++ manages this. Thanks
| sizeof is a compile-time construct. It has nothing to do with runtime, but rather gives a fixed result based on the type passed to it (or the type of the value passed to it). So char[20] is 20 bytes, but a string might be 4 or 8 bytes or whatever depending on the implementation. The sizeof isn't telling you how much... |
6,636,932 | 6,644,263 | Detecting functions using stack trace | I am looking at an application with a debugger (I don't have the source code!).
I put a breakpoint in a certain function (exported function) and I look at the stack trace.
Obviously I cannot see the symbols, but I can see the DLL name and an ordinal.
My question is how can I tell if the functions I see in the stack tra... |
Its a windows machine. I don't quite understand what you mean by "name" and "toolchain". – TCS
TCS: I was hinting at the fact that there is more than one debugger, and more than one linker that may generate different type of metadata in DLL's.
To the point, I've had good 'debugging' (inspecting/auditing) third-party ... |
6,636,937 | 6,644,175 | Reading SQL table in C++ | I am trying to read a SQL Server table in C++ using a function like this..
CCommand<CDynamicAccessor>* Read(char* tblName)
{
wostringstream query;
query << "SELECT * FROM " << tblName;
return dataSource -> Query (query);
}
which calls this other function
CCommand<CDynamicAccessor>* Query(w... | Most probably the result is a wchar_t * string and you cast it to char *
|
6,636,963 | 6,637,214 | How would I delete an array of QCheckBoxes using a vector of pointers to each element? | In my current project, I have an array of QCheckBoxes that I create at run-time given the dimensions from the user. Every time the user clicks the 'Generate' button, the dimensions that they inputted are gathered, and an array of QCheckBoxes is created. It is done in the following code:
void MainWindow::on_generateBoxe... | First delete all the elements (QCheckBoxes) in the vector and then clear the vector:
qDeleteAll(checkBoxVector);
checkBoxVector.clear();
Because you are adding checkbox pointers to the vector, just clearing the vector doesn't delete the checkboxes.
|
6,636,981 | 6,637,136 | Reading a file relative to an included file | I need to load some text (shader code) from a file that is placed next to my library file. This way, I can #include TextureBloomer.h in several projects, and TextureBloomer will take care of loading its shader without needing to set paths through configuration or environment variables. The directory hierarchy looks lik... | You are using that file as sort of a "resource" of your program. A simple option is in these cases to generate automatically a .cpp module that contains the source you need as string literals... i.e. if your source code is for example
void foo(int x, int y)
{
return x + y;
}
you generate a .cpp that contains
const ... |
6,637,012 | 6,637,094 | How Can i integrate c++ and Python with SWIG |
Possible Duplicate:
Integrate Python And C++
I am the python GUY and do web stuff in django. I want to know that how easy or hard it is to integrate python and C++ using SWIG.
Is it efficient/easy to do or should leave C++ and code the things in python.
There are some things C++ files which have been coded already ... | I often use swig for work in order to translate code to multiple languages and it is a really useful tool.
In order to understand what is the best way for you, you should observe your software interfaces. If you c++ classes have methods that only receive and returns simple types like strings or stl structures, you can ... |
6,637,325 | 6,637,497 | interface, interface client, vs inheritance, Software design principles, compoment packaging issue | I came across one issue as to how to package interface, interface client and inheritance. That is, in the book below, author mentioned that Switachable is more appropriate to deploy with Switch together as a component, rather than Light.
What I want to understand is the reasoning behind it (Both Switch and Switchable ... | Since Light inherits from Switchable, it could also be deployed with Switchable - it seems, however, due to the naming, that the primary class interacting with the Switchable interface will be Switch - which means that the two are tightly-coupled: you should never put tightly-coupled class/interface definitions in sepa... |
6,637,639 | 6,751,994 | How to tell flex and bison to stop processing input? | What is the best way to flex and bison to stop processing when an error is encountered. If I call yyerror, it does not stop scanning and parsing my file. While the input is syntactically correct, there is an user error, such as they tried to load the same file twice. Once I am out of flex/bison, then my program will... | YYABORT is the standard way of getting out; it causes yyparse to return immediately with a failure (1). You can then throw an exception or do whatever you want. You'll need to reset flex's input if you want to parse something else, but if you do, you can just call yyparse again and parsing will start over from the be... |
6,637,704 | 6,637,749 | How to compile c++ libs using Microsoft C++ compiler without the IDE | I want to use Notepad and invoke the compiler and linker from the command prompt.
No IDE no make , nmake or anything like similar because I want to know the exact syntax required to do the following:
1. create a static library
2. create a dll
Yes, I have browsed the MSDN site but the examples I saw assume one is using ... | For DLLs, pass the /c flag to cl.exe (which compiles but doesn't link), and pass the /DLL flag to link.exe. Instead of making an executable, it makes a DLL.
For static libraries, use the lib.exe program.
|
6,637,744 | 6,637,848 | Doing type erasure safely without boost and c++0x | Say i have a templated class
template<class T>
class A;
template<>
class A<int>
{
public:
void print(){ std::cout << "I am an int !" << std::endl; }
};
template<>
class A<double>
{
public:
void print(){ std::cout << "I am a double !" << std::endl; }
};
Now, if I want to store every possible... | The only answer to this question is "Roll your own class that already exists in Boost", whether you like ptr_vector, shared_ptr, any, etc. They already have all the bases covered in this regard. Pick your favourite and roll your own implementation, then use that.
Edit: A commenter mentioned TR1. Good shout. TR1 has sha... |
6,637,883 | 6,637,925 | Fast C++ single producer single consumer implementation | I'm looking for a single-producer, single-consumer FIFO implementation that would perform faster than the normal lock-write-unlock-signal / waitForSignal-lock-read-unlock stuff. I'm looking for something supported by most POSIX operating systems (x86 specific is fine) written in either C or C++.
I'm not looking to pas... | You will want to look at Intel's Thread Building Blocks. They build on the primitives provided by x86's user-mode atomic operations, and pthreads or Win32 threads, and provide fast, efficient, templated data structures. A concurrent queue is among many.
|
6,637,958 | 6,637,979 | Convert int16 to byte array | I'm really new to C, and so a bit confused.
I am trying to convert an int16 to a byte[] array.
I have a int16 like -200, and I want to convert it into a byte[2] array, like the following example does.
Velocity = -200 = hex FF38 = [hex FF] [hex 38] = [255] [56]
I am taking the values and passing them to the serial port... | Your approach looks fine, but maybe you're getting tripped up by an endianness issue?
Serial protocols may also be regarded as either little or big-endian at the bit- and/or byte-levels (which may differ). Many serial interfaces, such as the ubiquitous USB, are little-endian at the bit-level. Physical standards like R... |
6,638,039 | 6,638,167 | Using Separate Libs for Debug and Release in VC++ | I'm downloading GLFW for use with Visual Studio 2010. I see that the download has a separate folder for Debug and Release builds (each folder has two Libs and one DLL), but the filenames in both folders are the same. How should I configure Visual Studio to pick the right file, since I would expect that renaming a Lib o... | Visual Studio build properties (including the directories where it searches for files) are all build configuration specific. On the project configuration dialog, just press the drop-down to switch from Debug to Release. The settings you change will affect that particular build configuration and no others.
If you don't ... |
6,638,104 | 6,638,131 | std::vector Destruction and Unexpected Memory Leak | Consider the following example:
#include <vector>
class Foo {
std::vector<int*> v;
public:
Foo() {
this->v.push_back(new int(23));
this->v.push_back(new int(24));
this->v.push_back(new int(25));
}
~Foo() {
}
};
int main() {
Foo f;
return 0;
}
When f goes out of sco... | std::vector<T> does indeed call the destructor of T when it is destroyed. Here T is int *. The destructor of int * does nothing. The storage for the int * itself is freed, but the ints they point to are not.
Consider:
int main() {
int *x = new int(23);
return 0;
}
This exhibits the same problem; when x goes out ... |
6,638,213 | 6,638,225 | Will (and should) there be sockets in C++11? | Is the new C++11 going to contain any socket library? So that one could do something std::socket-ish?
Seeing as how std::thread will be added, it feels as if sockets should be added as well. C-style sockets are a pain... They feel extremely counter-intuitive.
Anyways: Will there be C++ sockets in C++11 (googled it but ... | No, it is not. As for the near future, the C++ standards committee has created a study group that is developing a networking layer proposal. It looks like they're going for a bottom-up approach, starting with a basic socket layer, then building HTTP/etc support on top of that. They're looking to present the basic socke... |
6,638,297 | 6,638,777 | How to edit SFML source code to add a new Drawable Object? | Hey i'm working on a class called a "Body" which holds shapes and sprites together as one object. I would like to get into the source code and add a new overload RenderWindow's Draw() function, so this new object can be taken in and drawn easily. How do i do this?
I'm currently using
Windows 7
SFML 1.6
Newly msVS++ 20... | Note:
Before you derive from and implemented your own Drawable, you may want to consider if you need to do it at all. The author of SFML has stated that sf::Drawable was not initially meant to be subclassed outside of SFML.
That aside,
For SFML 1.6:
It appears that all you need to do is derive your class from sf::Drawa... |
6,638,357 | 8,259,849 | Cross-Platform Threading/Forking-with-static-variables in C/C++ | I'm trying to write a server program which can keep a track of the number of instances of some object.
At the moment I'm using a static int which is incremented during the object's constructor:
class myObj{
public:
static int numOfInstances;
myObj();
};
int myObj::numOfInstances = 0;
myObj::myObj(){
this... | Multiprocessing is not part of the C++ standard. However, if you are on a POSIX system (where you have fork()), you can obtain shared memory from the operating system; look at the shmget() familiy of functions. You will need some synchronisation mechanism for access to the shared memory (like a mutex or a semaphore); t... |
6,638,515 | 6,638,530 | std::vector Destruction and Unexpected Memory Leak pt 2 | A few hours ago I asked this question. I learned that std::vector deletes each of its elements when its destructor is called. Consider this program (a derivative of a previous example):
#include <vector>
#include <iostream>
class Bar {
int x;
public:
~Bar() {
std::cout << "~bar()" << std::endl;
}... | The answer to this question is exactly the same as the answer to the last question. Deallocating a pointer does not call delete on it, so the thing it points to is not automatically destructed.
Put another way, Bar has a destructor, but Bar* does not. So a std::vector<Bar> would invoke the destructor of each element.... |
6,638,580 | 6,638,657 | Alternative to gethostbyname | I can't use gethostbyname to grab a host's IP address, it is a deprecated function that only works 10% of the fricken' time on Windows!
I can't find any adequate resources on other ways to find a host's IP address using other functions (MSDN recommended getaddrinfo but that doesn't seem like what I want.)
| Actually, getaddrinfo is what you want. It's just a long-winded way to do it, not to mention the fact that sometimes multiple IP addresses are found (e.g. one IPv4 address and one IPv6 address). I'd recommend looking at Beej's Guide to Network Programming, specifically getaddrinfo.
|
6,638,666 | 6,638,675 | C++ Error: expected primary expression before '*' token in constructor with parameters | I'm trying to make a class that has a constructor with five parameters. The only thing the constructor does is pass all the parameters to the superclass constructor. This class doesn't have any extra variables: its only purpose is to change the implementation of the getClassType virtual function. For some reason, this ... | You don't pass the types into the base class constructor:
class A
{
public:
A(int) {};
}
class B : public A
{
public:
B(int x) : A(x) // notice A(x), not A(int x)
{}
};
So, you constructor should look like this:
Suelo(b2World *world,int x,int y,int w,int h) : Plataforma(world,x,y,w,h){}
|
6,638,729 | 6,638,811 | when do we need to pass the size of array as a parameter | I am a little bit confused about pass an array in C/C++. I saw some cases in which the signature is like this
void f(int arr[])
some is like this
void f(int arr[], int size)
Could anybody elaborate what's the difference and when and how to use it?
| First, an array passed to a function actually passes a pointer to the first element of the array, e.g., if you have
int a[] = { 1, 2, 3 };
f(a);
Then, f() gets &a[0] passed to it. So, when writing your function prototypes, the following are equivalent:
void f(int arr[]);
void f(int *arr);
This means that the size of... |
6,638,754 | 6,639,380 | Why are the different output of C++ and C# compiler? | I have been asked this questions before but this time i want to know the difference between the compiler of C++ and C#.
C# coding of array
static void Main(string[] args)
{
int n;
int[] ar = new int[50];
Console.Write("Enter the size of array= ");
n = int.Parse(Console.ReadLine());
... | This is a complete guess but the Borland C++ is trying to interpret a number with a leading 0 as octal (which is a standard convention like the '0x' prefix for hexadecimal). Since 08 isn't a valid octal number (only 0-7 are valid digit it octal) it is splitting it up into two inputs.
Try entering '010' and if the prog... |
6,638,798 | 6,638,829 | When should I use a singleton class in C++? | From a beginning C++ user's point of view the only reason I would see a singleton class useful is similar to when I want to use a static variable. Do you guys know when its most appropriate to use a singleton class?
| The only time you should use a singleton is in the rare case where it is VITAL that there only ever be one of these objects. This simply doesn't come up nearly as often as you might think.
Quite often it's more than sufficient to just make a single instance of the class in question, but not put in all the machinery req... |
6,638,810 | 6,638,830 | What is the purpose of Virtual member in C++? | I don't see the purpose of a virtual member in a class other than safety. Are there any other reasons to use virtual when designing implementations? Edit: I erased the variable part.
| There is no such thing as a virtual variable, only a virtual function or virtual inheritance. As such, lack of a purpose for such a thing seems like rather a good thing.
Edit: Virtual functions are how C++ implements run-time polymorphism. Trying to explain the uses/purposes of polymorphism is probably a bit beyond wha... |
6,638,961 | 6,638,995 | Series of strcmp() calls at the start of simple C++ program | I have a simple C++ program:
#include <iostream>
int main()
{
std::cout << "Hello\n";
return 0;
}
I was playing with "scratchbox" - cross compilation platform that I use in order to compile applications for ARM platform. I run it on my Nokia N900 phone.
While investigating some performance problems I ... | Not sure, but could it be that test actually is the system test command, and not the program you wrote? This could happen for example if $PATH does not contain ., the current directory. And given that it is a small platform, all test, mv, etc., might actually be just one executable, which emulates the correct program... |
6,638,999 | 6,639,696 | std::cout << Predicting the automatic field width in displayed for an arbitrary double | I'm displaying a large number of doubles on the console, and I would like to know in advance how many decimal places std::cout will decide to display for a given double. This is basically so I can make it look pretty in the console.
e.g. (pseudo-code)
feild_width = find_maximum_display_precision_that_cout_will_use( who... | In your question you are mixing precision and width, which are two different things.
Other answers concentrate on precision, but the given precision is the maximum, not a minimum of displayed digits. It does not pad trailing zeros, if not ios::fixed or ios::scientific is set.
Here is a solution to determine the number... |
6,639,012 | 8,158,397 | Minimum size/width of a QPushButton that is created from code | I created 2 rows of push buttons, each row is inside a QHBoxLayout.
I create the buttons in the code:
static const char* buttonText = "23456789TJQKA";
for (int ii = 0; buttonText[ii]; ii++)
{
QPushButton* pushButton = new QPushButton(this);
pushButton->setText(QString(buttonText[ii]));
ui->horizontalLayou... | This happens because the minimumSizeHint of the QPushButton does not allow the QLayout to resize it :
The default implementation of minimumSizeHint() returns an invalid
size if there is no layout for this widget, and returns the layout's
minimum size otherwise. Most built-in widgets reimplement
minimumSizeHint()... |
6,639,037 | 6,639,050 | Lifetime of temporary within operator+ sequence |
Possible Duplicate:
Guaranteed lifetime of temporary in C++?
Lifetime of temporaries
I have a quick question regarding the lifespan of a temporary object, when returned from an overloaded operator+ method. For example, if the expression...
a = b + c + d + e
...is evaluated by overloaded operator+ methods which retu... | Yes, in the usual case: "Temporary objects are destroyed as the last step in evaluating
the full-expression (1.9) that (lexically) contains the point where they were created." (§12.2/3).
There a couple of exceptions to this, but they don't apply here.
|
6,639,057 | 6,639,081 | What is implicit dereference in C++ | What exactly does implicit dereference in C++ mean? Does it mean when I pass a reference to variable into a function parameter I don't need the & in front of it to use its value?
| I assume that your teacher was trying to explain the difference between pointers and references.
It is relatively common (though not technically accurate) to refer to references as fancy pointers that do implicit de-referencing.
int x = 5;
int* xP = &x;
int& xR = x;
xR = 6; // If you think of a reference ... |
6,639,172 | 6,639,223 | C++ how to write an operator that isn't a member function? | Anyone got an idea on how to write an operator for a class that isn't a member function of the class?
| Just make it a free function, or a friend function. A good example of this is operator<<:
class X {
public:
int x;
}
ostream& operator<< (ostream& os, const X& x) {
os << x.x;
return os;
}
The benefit of making it a friend function is that you have direct access to private members, whereas a free fun... |
6,639,245 | 6,639,272 | What means that kind of declaration in c++? | What does this kind of declaration mean in c++?
CSomething & SOMETHING = m_vSOMETHING[m_iSOMETHING];
| It is a reference variable which is initialized to point to the specified cell in m_vSOMETHING
So a declaration of
int &reftotable = table[42];
Will produce reftotable as a variable which reference cell 42 in the table, similar to what
int *pointertocell = &table[42];
would do. In the first case with the referenc... |
6,639,264 | 6,639,316 | Const mismatches: 2 overloads have no legal conversion for 'this' pointer | I'm getting this weird error:
error C2663:
'sf::Drawable::SetPosition' : 2
overloads have no legal conversion for
'this' pointer
I think it has something to do with const mismatches but I don't know where, or why.
In the following code I have a vector of shapes and sprites, and when trying to access one of the... | Render is declared with a const after the parameters. This means it does not change its object. Which means, that all of the object's member variables are considered constants within Render, as changing their state means changing the containing object. Assuming Shapes is a member variable, and that SetPosition does cha... |
6,639,579 | 6,639,622 | Template compile-time errors when compiling list iterators with ARM GCC | This code gives me many headaches when compiling under GCC ARM. I am using it fine with MSVC++ compiler 2010. I get compile errors like:
Error 1 error : expected ';' before 'i' C:\Users\Ryan\Desktop\droplets\source\MultiList.h 62
Why won't my templated code compile using GCC?
#ifndef MULTILIST_H
#define MULTILIST_... | It won't compile because it is chock full o'errors:
g++ -Wall /tmp/junk.c
/tmp/junk.c: In destructor ‘MultiList<E>::~MultiList()’:
/tmp/junk.c:62:9: error: need ‘typename’ before ‘std::list<std::list<E>*>::iterator’ because ‘std::list<std::list<E>*>’ is a dependent scope
/tmp/junk.c:62:34: error: expected ‘;’ before ‘i... |
6,639,655 | 6,639,817 | Can someone explain this makefile to me? | I've been using c++ casually for a couple of months with a makefile I don't even remember where I got or if I did it myself (the actual structure it has. I know I've added some libraries and flags though):
SRC = filename.cpp
TARG = filename
CC = g++
CPPFLAGS = -g -Wall -Werror -Wextra -pipe -pedantic -Weffc++ -std=c+... | If you want to compile a class instead of a program, you need to do a little surgery on the file. I'm assuming that you want an object file, not a library; the rules for libraries are more complex. But this should do the trick.
SRC = class.cpp
OBJ = $(SRC:.cpp=.o)
CC = g++
CPPFLAGS = -g -Wall -Werror -Wextra -pip... |
6,639,700 | 6,639,790 | How to use C++0x lambdas local variables for std::fill()? | So I was trying to test a lambda accessing local variables in the scope in which it is used, based roughly on a simple example by Bjarne on the C++0x FAQS page at:
http://www2.research.att.com/~bs/C++0xFAQ.html#lambda
When I try this simple test code:
#include <iostream>
#include <vector>
#include <algorithm>
using na... | Bjarne's example doesn't compile. It can't compile, not unless they defined std::fill differently in C++0x. Maybe it was from a conceptized version of std::fill that could take a function, but the actual version of it (according to section 25.1 of N3242) takes an object, not a function. It copies that object into every... |
6,640,005 | 6,640,035 | When should I use templates and when overloaded functions? | I am confused. I never seem to decide what to use, a template or an overloaded function. Overloads need more coding. So in what cases is it preferred to use templates and in what overloaded functions?
For example, i recently had to take this decision while making a small GBA game. There were two types u16 and int and ... | Basic Rule should be:
Use Templates when you want to perform same functionality/Operations on different data types.
Use overloaded functions when you want to perform different functionality/Operations on different/same data types
Also, A good measure of when you really need a overloaded function over template is when y... |
6,640,240 | 6,641,119 | visual c++ 2010 C++ build problems | When compiling any C++ project with visual studio 2010 express I'm liable to get following behaviour - build started message appears in output window, CPU climbs to near 100%, multiple MSBuild.exe processes are spawned, long pause (several minutes) with nothing happening, build aborts with the following message
xxx.vcx... | You've already eliminated KB2298853. Do make sure to install SP1. It is not the only reason, some other users have this problem too, even after the workaround. The basic failure appears to be a problem creating a pipe that lets msbuild talk to the IDE. Which is why it doesn't fail when you run msbuild from the comm... |
6,640,254 | 6,640,379 | How to store various types of function pointers together? | Normal pointers can be stored using a generic void*. e.g.
void* arr[10];
arr[0] = pChar;
arr[1] = pINt;
arr[2] = pA;
Sometime back, I came across a discussion that, void* may not be capable enough to store a function pointer without data-loss in all platforms (say 64-bit and more). I am not sure about this fact though... | You can convert a function pointer to another function pointer of any function type and back without loss.
So as long as when you make the call through the function pointer you typecast it back to the correct type first, you can store all of your function pointers in something like:
typedef void (*fcn_ptr)(void); // '... |
6,640,344 | 6,640,878 | how many heaps have a software at least under windows | I have discover that the C-runtime has in own heap ( and also all the Heap API under windows HeapWalk..). I'm a little bit in trouble in regard of my previous knowledge in the way it seems a Process have in fact several Heaps and not only one. Is it right ? And if it is the case, why there is the need of several Heaps... | A Windows process generally has at least 3 heaps:
the default process heap. GlobalAlloc() allocates from it, mostly used by Windows
the COM heap. CoTaskMemAlloc() and SysAllocString() allocate from it, used by any COM server
the CRT heap. The new operator and malloc() function allocate from it.
It is not uncommon ... |
6,640,363 | 6,640,401 | Receiving HTTP headers | In educational purposes I'm writing a HTTP server in C++.
When receiving a request, how do I know when the client has finished sending headers? Is there an obligation that all headers must be sent in one shot? What if a client sends G, then after 5 seconds E, then T..? Should I wait a timeout and just close the connect... | There are two parts to this answer.
Firstly, the issue of delay and time-out: you should deal with timeouts indeed, as it's generally not possibly to detect whether a TCP connection is broken. There is more on this topic in this question: TCP socket in Unix - notify server I am done sending
Secondly, the format of an H... |
6,640,733 | 6,640,741 | reversing of a string | #include<iostream>
#include<string.h>
using namespace std;
char * reverse (char *);
int main()
{
char * a;
cout<<"enter string"<<endl;
gets(a);
cout<<a;
cout<<"the reverse of string is"<<reverse(a);
return 0;
}
char * reverse (char * b)
{
int i,j=strlen(b);
for(i=0;b[i]!='\0';i++)
{
... | You are not allocating memory for the string. gets doesn't allocate memory for you, so you're just reading into some random location - results are undefined.
Apart from that, there are more problems:
This is tagged C++ but it's more like C with cout (using string would be a better idea)
You are using gets instead of f... |
6,640,974 | 6,641,012 | Does unsigned math require more CPU instructions? | Take an C++ integral variable i, and suppose that you're multiplying its value by 2.
If i has signedness, I believe that the operation is somewhat equivalent, at least mathematically, to:
i = i << 1;
But if i's type is unsigned, then since unsigned values do not overflow but are performed modulo their range, presumabl... | No, it doesn't take more instructions, at least on x86.
For some operations (e.g. addition and subtraction), the same instruction is used for both signed and unsigned types. This is possible since they work the same when using 2's complement representation of signed values.
There is also no difference for left-shift: T... |
6,641,161 | 6,641,175 | c++ why doesn't a copy of an object allow access to a private variable of the original? | For example,
Number operator+(Number a, Number b) {
return Number(a.x + b.x);
}
Would this cause some kind of "unable to access private member error". I understand that if I don't pass by reference, the Number a, and Number b are copied on the stack and used in the body of the function. However, I don't see wh... | operator+ is an unbound function, i.e. it is not a member of Number so, this is the rule, it has no implicit access to private members.
The rule is not affected by you passing Number objects by value or by reference. Access protection is applied to every access to a Number object, even if it is your private, stack-bas... |
6,641,254 | 6,641,263 | reversing a string in place | #include <string>
#include <algorithm>
#include <iostream>
using namespace std;
bool compare( const string::size_type i, const string::size_type j )
{
cout << "comparing " << i << " and " << j << "." << endl;
return i < j;
}
void reverse_inplace( std::string &s )
{
std::string::size_type i = 0;
std::st... | The loop body isn't being executed because you have a semicolon after the while() line, which is causing the loop body to be ignored. Therefore, the increment and decrement statements aren't being hit; neither are the couts.
|
6,641,475 | 6,641,582 | Longest substring that occurs at least twice: C++ question | The title is horrible, I know, but until I know the answer to my question, I can't think of a better one. If you can, please edit.
I was solving (for fun) a very easy problem on one of OnlineJudge sites. The problem is this:
Input: a single string containing
lowercase latin letters. The length of
string is at leas... | Without running your code, I think your second solution fails on input strings of length 1.
Your dif vector is empty whenever the input string has length 1, which causes *max_element(dif.begin(), dif.end()) to fail.
|
6,641,573 | 6,641,614 | How to use the stride parameter in VBO? | I have problems understanding how to use one buffer with 3 different data in it, I have the following structure for my vert,text,color data:
struct xyzf {
float x, y, z;
};
struct xyf {
float x, y;
};
struct vertype {
xyzf points[4];
};
struct textype {
xyf points[4];
};
struct coltype {
GLuint poi... | It seems you are interleaving your data per quad, but you should rather interleave it per vertex (at least that's what usually done).
Your code should be right if you change the vertex layout to this:
xyz
uv
rgba
xyz
uv
rgba
xyz
uv
rgba
xyz
uv
rgba
Rather than
xyzxyzxyzxyz
uvuvuvuv
rgbargbargbargba
|
6,641,630 | 6,641,734 | sum of all the numbers below 1000 that are multiples of 3 or 5 | Project Euler problem 1 is: Find the sum of all the multiples of 3 or 5 below 1000
Here is my program, using two simple functions to work out the sum of all the multiples of 3 and all the multiples of 5 and then add them up:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#... | As most others pointed out, you're summing the multiples of 15 twice.
Just a hint for another solution:
The sum of multiples of 3 below 1000 is
SUMBELOW(3,1000) = 3 + 6 + 9 + ... + 999 = 3*(1+2+3+...+333) = 3*333*(1+333)/2 = 3*((1000-1)/3)*(1+(1000-1)/3)/2
(All divisions are integer divisions...)
There are similar for... |
6,641,831 | 6,641,931 | property sheet data validation | When the user clicks the OK or APPLY button on a property sheet and the program determines data on some page is invalid, how can I cause the page containing the error to be displayed along with a message box describing the error?
Currently the procedure doing the validation does the following while processing the PSN_A... | I think the problem is in the design of your validation and it's presentation.
Am I right in thinking that you iterate through your property sheets, validate them and display a message box if something is awry? Because of course, what you have witnessed will happen, if I am on property page 3 and I wrote crap in to a ... |
6,641,873 | 6,641,880 | does it makes sense a virtual template method? | Suppose a construct like this:
class Interface
{
public:
template <typename T>
virtual void reportOperationError(T code , std::string message) = 0;
};
i don't understand the use case for this thing, in which case it is useful, and how?
In case you wonder, I haven't seen this code anywhere, just want to understan... | Templated member functions cannot be virtual... Each instantiation of the function will add another entry to the virtual table, and the compiler will have to go over all of the code in order to create the vtable. Therefore, regardless of it being useful or not, it's just not legal C++.
|
6,641,912 | 6,663,809 | unresolved external symbol in eclipse cdt | I try to build cpp file using eclipse cdt. Linker throws "unresolved external symbol", however path to lib file that contains implementation for function is listed in LIB environment variable on Project properties->C/C++ Build->Environment
What am I doing wrong?
UPD I try to build file. There is lib RpcRT4.Lib on the p... | I'm not entirely clear on whether you've already done this based on the question, but just adding the directory to your linker's search path isn't enough for any compiler/linker I've ever used. There could be hundreds of different libraries in there, even different versions of the same library, and the linker has no i... |
6,642,015 | 6,642,171 | ordered doubly linked list search | suppose we have doubly linked list ordered by integer value:
struct ListItem
{
int value;
ListItem *prev, *next;
};
struct List
{
ListItem *first, *last;
int count;
};
can we use faster search algorithm such as binary search to locate ListItem inside List and how?
| For most practical purposes, no. If you want faster search, a linked list is a poor choice of data structure. Consider a vector, deque, set, or multiset instead.
Edit: Perhaps it would be good to provide some guidance about which of those makes sense when. A vector makes the most sense if you have two basically separat... |
6,642,127 | 6,642,321 | Accessing MySQL database from C++ | I want to connect to a MySQL database from a Qt C++ application. Database is located on a host and is available on internet. I have the MySQL username, password and IP of host and a port number (that I don't know what is)
Application::getInstance()->db = QSqlDatabase::addDatabase("QMYSQL");
QSqlDatabase *db = &... | Well, because you gave very little information, I cannot give you anything but a hunch, so here I go: Often webhosters configure there MySQL Databases to only accept connections from localhost (for a php or similar site, that is locate there, that's enough and that way it is more secure and abuse is less likely). That ... |
6,642,411 | 6,648,094 | How do I create child elements using msxml parser? | I have a users.xml
<?xml version="1.0"?>
<Data>
<Users>
<User name="xyz" email="xyz@xyz.com">
<Tasks/>
</User>
</Users>
</Data>
I have got a reference to Users element using the following code
IXMLDOMDocumentPtr pXMLDom;
// code to load the xml dox
IXMLDOMElementPtr pXMLDo... | Ok, I've found a solution, thanks to TERACytE
IXMLDOMDocumentPtr pXMLDom;
// code to load the xml dox
//Creating <User>
MSXML2::IXMLDOMElementPtr pUser = pXMLDom->createNode(NODE_ELEMENT, "User", "");
//Creating <User name="">
MSXML2::IXMLDOMAttributePtr pName = pXMLDom->createAttribute("name");
pName->value = name;... |
6,642,464 | 6,642,495 | Member functions comparison as predicates | I have a structure like this.
struct A
{
int someFun() const;
int _value;
};
I store objects of this structure in a vector.
How to find the object whose member someFun() returns 42?
How to find the object whose _value is 42?
I guess I have to use the combination of bind and equal_to, but I'm not able to find t... | vector<A> va;
vector<A>::const_iterator v0 = find_if(
va.begin()
, va.end()
, boost::bind(&A::someFun, _1) == 42 );
vector<A>::const_iterator v1 = find_if(
va.begin()
, va.end()
, boost::bind(&A::_value, _1) == 42 );
In case you do need to compose bind expressions (e.g. using a functor that c... |
6,642,603 | 6,647,303 | Changing status bar position | I'm trying to make a map editor, and I'm loosely basing it off of the Game Maker map editor. One of the things I like about it is the object panel on the left-hand side and a status bar between the end of it and the right-hand side of the window. Here's a picture:
I can't figure out how that was done. I assume the cre... | You can do this by telling the status bar not to reposition itself, then positioning it yourself.
The former means altering the status bar's styles. See here - particularly CCS_NOMOVEX.
The latter means moving the status bar window in response to WM_SIZE messages sent to the window the status bar is in (usually your ma... |
6,642,613 | 6,642,680 | String input in C and C++ | I want to write a program in C or C++ that asks to user to enter the string at run time of different lengths at different times as given by user (either space separated or non space separated) and store it into an array. Please give me the sample code in C and C++ for it.
e.g.
1st run:
Enter string
Input: Foo
Now ch... | Use getline.
Take a look a this example:
http://www.cplusplus.com/reference/iostream/istream/getline/
|
6,642,721 | 6,644,062 | multiple nested dependent names - where to stick the typename keyword? | This question was inspired by this other question. While trying to answer that question, I understood that I have a lot of questions myself. So... Consider the following:
struct S1
{
enum { value = 42 };
};
template <class T> struct S2
{
typedef S1 Type;
};
template <class T> struct S3
{
typedef S2<T> Typ... | The name before the scope operator :: must always be a namespace or class (or enumeration) name, and namespace names can't be dependent. So you don't have to tell the compiler that this is a class name.
I'm not just making this up, the standard says (section [temp.res]):
A qualified name used as the name in a mem-in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.