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,366,904
4,372,966
Custom stream to method in C++?
I'm making a logger and I wish to have some kind of stream-like happenings going on, ideally doing CLogger << "Testing, " << 1 << ",2,3\n"; instead of CLogger->log("Testing, %i,2,3", 1); My question is how would I do this? I don't want to directly create a stream to stdout as I want to use my own method which includes ...
If all that you need is directing certain log messages to files, have you considered std::ofstream? Otherwise, I like to derive my logging class from std::ostream, so I get all of the stream goodness. The trick is to put all of your application-specific code in the associated streambuf class. Consider: #include <iostre...
4,366,935
4,367,295
Run boost library with borland compiler 5.82
I am trying to run the "getting started" example: #include <boost/lambda/lambda.hpp> #include <iostream> #include <iterator> #include <algorithm> int main() { using namespace boost::lambda; typedef std::istream_iterator<int> in; std::for_each( in(std::cin), in(), std::cout << (_1 * 3) << " " ); } ...
I think boost::lambda doesn't work with 5.8.2 - It may not even work with the very latest C++Builder compiler. Have a look at the results on the bcbboost pages, and keep an eye on David Dean's blog.
4,367,557
4,367,634
double byte swapping
There are some discussions about the same question but I would like to ask some more , 1) How portable is the below code for a double byte swapping int ReadDouble(FILE *fptr,double *n) { unsigned char *cptr,tmp; if (fread(n,8,1,fptr) != 1) return(FALSE); cptr = (unsigned char *)n; tmp = cptr[0]; ...
It's not as easy as that. Just because an architecture is big-endian for integers doesn't mean it's big-endian for floating point numbers. I've heard of platforms that store integers big-endian and floats little-endian. So first you should discover what the actual memory representation of double on your source platform...
4,367,599
4,367,699
Does a C++ standard library have to be written in C or assembly?
Is it possible to write the complete C++ standard library (including STL of course, but self-contained, only internal dependencies) using only C++? I would imagine containers and <cstdlib> functionality would be doable in terms of chars, bitshifts, and for loops and other byte fancy things, but stuff like exceptions an...
Since pretty much anything written in C can be rewritten fairly easily in C++, you're asking whether assembly code is needed, and the answer is generally no. Unless we're talking about embedded programming, operating systems have all the necessary file and I/O functionality available through system calls, usually (nowa...
4,367,742
4,367,778
split malloc mem space
I am using MS VS 2010, C++, unmanaged. I would like to split allocated area if possible. For example let's say I allocated a 1KB space in memory: void* space = malloc(1024); later, I decided to have this block as seperate 512B and 512B spaces: space1 = 512B and space2 = 512B and finally when I want to get rid of thes...
No, you can't free them separately, as malloc() will keep only one copy of the necessary bookkeeping data, so it can only free one chunk. You would have to write your own malloc/free wrappers.
4,367,892
4,367,959
Search for specific value in std::map
Possible Duplicates: Checking value exist in a std::map - C++ How to traverse a stl map/vector/list/etc? Hello, Is it possible to search for specific value in std::map, not knowing the key? I know I could iterate over whole map, and compare values, but it is possible to do using a function from std algorithms?
Will this help? STL find_if You need to have some sort of predicate, either a function pointer or an object with operator() implemented. Said predicate should take just one parameter.
4,367,947
4,368,021
Reduce server resources and compilation of php to C++
I've searched tutorials of how to reduce server resources (CPU, memory...) in a website, using php (if it's possible) , but in vain (maybe I couldn't choose good keywords). If the only way to manage server ressources is the c++ language (php compiled to ). How can we write a c++ code that can do this task (without usin...
You do not have to do this at all. There are lots of opcode caching like, APC - this will compile PHP script into opcode cache and the cache is reusable until the PHP script updated again or the date validity exceeded. What is opcode cache? Which PHP opcode cacher should I use to improve performance? PS: eAccelerator ...
4,368,055
4,814,319
Coding style advice/rationale(s) for placing spaces in control statements with C++
Given the following two coding styles, please specify a rationale (some pros/cons) for why one would possibly be preferable over the other when writing C++ code. ( Please do not answer with "it is not important"; "just stick to one"; etc. The question is specifically about the possible pro/cons (if any) of the two spac...
I recently fixed some code where a single-line-if was modified and someone forgot to add some braces. While reading the code, it seemed to me, that the style ...condition){ is harder to read than the style ...condition) { because the closing ) and opening { are easier to see when separated by a space. (When using Couri...
4,368,062
4,368,092
Syntax for Function Prototyping in Header Files
Consider I have the following function prototype: void MyFunction(int MyParameter); With the following definition: void MyFunction(int MyParameter) { // Do stuff here. } Where should they each be put if I have a header file (no main function) with a namespace? Does the prototype go in the namespace and the defini...
If you choose to have a namespace, both should be inside : .h : namespace MyNameSpace { void MyFunction(int MyParameter); } .cpp : void MyNameSpace::MyFunction(int MyParameter) { // Do stuff here. }
4,368,109
4,369,257
Do I need to delete my buffer after sending it into boost::asio::buffer?
Sp I have a function like: void WriteToUrl(const unsigned char *buf, int size) { boost::asio::write(s, boost::asio::buffer(buf, size)); } Do I need to delete buffer if I do not use it any where else? How do I need to clean after y function?
If I have understood you are always the ownership of the buffer 'buf'. With synchronous operations, as ::write, you can delete the buffer as soon as ::write finish. With asynchronous operations, as ::async_write, you need to give an asynchronous completion token (a callback) which will be called when the operation has ...
4,368,124
4,368,375
wrap std::iterator in C++
I have a need to wrap a vector iterator, but don't like the idea to rewrite it from scratch. And I can't subclass it as far as vector iterator doesn't seem to be cross-platform. At least gnu and ibm ones look different. What I want to do is the following: class MyContainer { vector<double> data; vector<int> ind...
This looks a lot like a permutation_iterator, one of the "built in" adapters from the Boost.Iterator Library See this example (modified from the Boost docs) on codepad.
4,368,361
4,368,807
Construct object with itself as reference?
I just realised that this program compiles and runs (gcc version 4.4.5 / Ubuntu): #include <iostream> using namespace std; class Test { public: // copyconstructor Test(const Test& other); }; Test::Test(const Test& other) { if (this == &other) cout << "copying myself" << endl; else cout << "copying som...
The reason this "is allowed" is because the rules say an identifiers scope starts immediately after the identifier. In the case int i = i; the RHS i is "after" the LHS i so i is in scope. This is not always bad: void *p = (void*)&p; // p contains its own address because a variable can be addressed without its value b...
4,368,440
4,368,486
"undefined reference" to a template class function
I am writing a template class for an array of objects, call it arrayobjclass, which holds pointers to other objects, specifically to other arrays in my implementation. The arrays are implemented as objects as well, call them arrayclass. Looking for compilation ready with minimal changes. when I try to test my classes w...
You can't put template declarations in .cpp files like that. Template declarations and implementation need to be visible in the same translation unit. Put template implementations in headers that you #include directly.
4,368,525
4,369,503
WSAGetLastError() returns 122
Well.. I am not really sure what that means, but my systems runs and runs and runs without crying for insufficient memeory... I guess it has to do with the system error 122, because there is no 122 in the winsock error codes (MSDN)... Anyone got a clue?... It occures on a call to getaddrinfo(NULL, /*PortNumber*/, &hint...
The problem is your implementation of operator const char*(). Once that function returns, your stringstream object is no longer valid because it is no longer in scope.
4,368,596
4,370,022
DFID (Dept-First Iterative Deeping) vs. IDA* (Iterative-Deeping A*)
I wonder what are the advantages and disadvantages of these two algorithms. I want to write AddEmUp C++ solved, but I'm not sure which (IDA or DFID) algorithm should I use. The best article I found is this one, but it seems too old - '93. Any newer? I think IDA* would be better, but.. ? Any other ideas? Any ideas an...
The Russel & Norvig book is an excellent reference on these algorithms, and I'll give larsmans a virtual high-five for suggesting it; however I disagree that IDA* is in any appreciable way harder to program than A*. I've done it for a project where I had to write an AI to solve a sliding-block puzzle - the familiar pro...
4,368,665
4,368,752
Best way to manage memory ownership in C++? Shared-pointers or other mechanisms?
In a new piece of code I have several different classes that refer to each other. Something like this (this is not my actual situation but an example of something similar): class BookManager { ... }; class Book { public: void setBookManager(BookManager *bookManager) {m_bookManager = bookManager;}...
In C++ if you have shared, un-coordinated access to common objects then the most common approach is some kind of reference counting, which you get from shared_ptr. The only downside is that it isn't pervasive in C++ (especially libraries), so you sometimes need access to the raw pointer. In those cases, you need to be...
4,369,078
4,369,291
Relation between stack limit and threads
What is the relationship between ulimit -s <value> and the stack size (at thread level) in the Linux implementation (or for that matter any OS)? Is <number of threads> * <each thread stack size> must be less than < stack size assigned by ulimit command> valid justification? In the below program - each thread allocate...
On UNIX/Linux, getrlimit(RLIMIT_STACK) is only guaranteed to give the size of the main thread's stack. The OpenGroup's reference is explicit on that, "initial thread's stack": http://www.opengroup.org/onlinepubs/009695399/functions/getrlimit.html For Linux, there's a reference which indicates that RLIMIT_STACK is what ...
4,369,191
4,369,405
Sizeof Reports Improper Size of Type-defined Structure - C++
My application has a defined structure: typedef struct zsSysVersionMsg_tag { WORD cmd; BYTE len; } zsSysVersionMsg_t; I would expect sizeof(zsSysVersionMsg_t) to evaluate to 3. However, when I run my application it evaluates to 4. Can someone explain why this is? (I really need it to evaluate to 3.) Thanks...
Most platforms will "align" and "pad" structures so that they begin and end exactly on a word boundary. This is done to improve memory performance. Assuming you are on Windows, you can set your own alignment. In your case, you want to align on single bytes, so do this: #pragma pack( push, 1 ) typedef struct zsSysVers...
4,369,219
4,369,287
Sequence points in C++ and exceptions
Can compiler reorder variable setting and throw() op in C++? Or, does standard C++ 14882-1998 allows or prohibit compiler of this transform? For code: bool funct() { bool succeeded = false; bool res_throw = false; try { throw("it"); succeeded = true; } catch(...)...
Yes, there is a sequence point associated with the throw statement, because there is a sequence point at the end of every statement. So succeeded must remain false in your example. I don't have the C++98 Standard, but in the C++03 Standard: 1.9p16: There is a sequence point at the completion of each full-expression. ...
4,369,241
4,369,286
How do I pass a C++ reference, to a pointer argument of a C function?
I just want to check here on how to pass a reference to a function that wants a pointer. I have a code example below. In my case, I am passing a C++ reference to a C function that will change my value. Should I use the '&' address of operator in this call: retCode=MyCFunc( &myVar)? It seems that I am taking a reference...
Your usage is correct, to do &myVar to get the address of it and pass to a function that wants a pointer. Taking the address-of a 'reference' is the same as taking the address of the referent.
4,369,356
13,048,344
problem with boost.test with old version
I'm trying to use boost.test on a remote system with boost 1.33.1. On my pc this little example from http://www.boost.org/doc/libs/1_42_0/libs/test/doc/html/tutorials/hello-the-testing-world.html works: #define BOOST_TEST_MODULE MyTest #include <boost/test/included/unit_test.hpp> // I've changed here int add( int i, i...
On Boost 1.33 use: #include <boost/test/auto_unit_test.hpp> in place of: #include <boost/test/unit_test.hpp> and also before the #include add: #define BOOST_AUTO_TEST_MAIN or you'll get a linker error
4,369,505
4,369,552
base class using a type defined by the parent class
I have a Visual Studio 2008 C++ application where a base class A_Base needs to instantiate a data member whose type is defined by a parent class. For example: template< typename T > class A_Base { public: typedef typename T::Foo Bar; // line 10 private: Bar bar_; }; class A : public A_Base< A > { public: ...
You can try the following: template< typename T > class A_Base { public: typedef typename T::Foo Bar; // line 10 private: Bar bar_; }; class A_Policy { public: typedef int Foo; }; class A : public A_Base<A_Policy> {}; int _tmain( int argc, _TCHAR* argv[] ) { A a; return 0; }
4,369,661
4,369,703
Qt - How to save a configuration file on multiple platforms
I'm writing a Qt application that needs to save some settings to the user's configuration directory. I've come up with the following code to get this folder: #ifdef Q_WS_WIN path = QDir::homePath() + "/Application Data/Timely"; #else path = QDir::homePath() + "/.config/Timely"; #endif This fails on Windows 7 c...
Depends on the settings you want to record, but I would suggest to use QSettings.
4,369,772
4,369,829
reallocating boost::shared_array
I have a shared_array: boost::shared_array myarr(new char[m_length]); I would like to reallocate the array. I thought of creating a new shared_array with the wanted size and using the swap boost method but this will copy the referance count as well. Do you have another idea? //new_length>m_length void func(boost::share...
Why not just instead use a boost::shared_ptr<std::vector<char> >? Let the standard library handle resizing. (In fact, depending on why you were using shared_array in the first place, you might well get away with just using a std::vector, and passing it around by reference carefully.)
4,369,773
4,369,818
CPPUnit array assert
I'm kinda new to C++ and even more CPPUnit. Can somebody tell me what should I use to assert for array values (compare them to expected). Should I use memcmp or is there something better in CPPUnit, C++ in general or any other library?
In modern C++, we compare ranges of data for equality with std::equal.
4,369,807
4,369,853
c++ passing a string literal instead of a const std::string&?
I have the following code which compiles with no warnings (-Wall -pedantic) with g++ #include <iostream> #include <string> using namespace std; class Foo { public: Foo(const std::string& s) : str(s) { } void print() { cout << str << endl; } private: const std::string& str; }; class...
The reason why this fails is because it essentially compiles to the following under the hood. Foo o(std::string("wurd")); In this case the Foo value is taking a reference to a temporary object which is deleted after the constructor completes. Hence it's holding onto a dead value. The second version works because it'...
4,369,948
4,370,028
C++ / Arduino: How do I convert a string/char-array to byte?
I want to convert char lineOneC[8] = {0,1,1,0,0,0,0,1}; into byte lineOneB = B01100001; How do I do this in C++ / Arduino?
I'm not sure about specific restrictions imposed by the Adruino platform, but this should work on any standard compiler. char GetBitArrayAsByte(const char inputArray[8]) { char result = 0; for (int idx = 0; idx < 8; ++idx) { result |= (inputArray[7-idx] << idx); } return result; } A test of...
4,370,165
4,370,174
Very Simple C++ TCP Echo Server
I am new to C++ network programming but have experience with Java sockets etc. I have been trying to write a simple TCP echo server in C++ but cannot really make any progress. I've tried looking at some code like at http://cs.baylor.edu/~donahoo/practical/CSockets/practical/ but cannot get anything to work. Can anyone ...
The terms "simple" and "C++ TCP Echo Server" don't belong together in the same sentence. There is no such thing. The sample that you are looking at is probably as close to "simple" as you're going to get (if you want to get into the nitty-gritty). Using a library that handles all the heavy lifting for you would make th...
4,370,399
4,370,544
Overriding global operator new to track huge memory allocations?
I am trying to produce a special build of a large monolithic application. The problem I am trying to solve is tracking hard-to-reproduce huge memory allocations (30-80 gigabytes, judging by what OS reports). I believe the problem is an std::vector resized to a negative 32-bit integer value. The only platform exhibiting...
Why not to do something like this? void *operator new(size_t size) { // if (size > MAX_SIZE) ... return malloc(size); } void *operator new [](size_t size) { // if (size > MAX_SIZE) ... return malloc(size); } Setting a breakpoint in the if would find the problem right away.
4,370,463
4,370,485
c++ reference/pointer
Possible Duplicate: Difference between pointer variable and reference variable in C++ I saw this simple code the other day, and I consider myself a beginner with pointers, although I have about a year and half experience with c++. Anyways... Whats the difference between int a = 0; int &b = a; and int a = 0 int ...
A reference must always be initialized A reference can't be null Once initialized, a reference can't be changed to be an alias of a different object.
4,370,474
4,370,620
is there a function in C or C++ to do "saturation" on an integer
I am doing some 3D graphics and I have an open ocean. For this ocean, I have a matrix representing the sea state (i.e. wave heights) for a particular rectangular subsection of the sea. The rest of the ocean is flat. My problem is that my controlled sea, where there are waves, is positioned in the middle of open flat se...
template<typename T> T saturate(T val, T min, T max) { return std::min(std::max(val, min), max); }
4,370,542
4,370,581
main doesn't continue after pthread
Im using Ubuntu 10.10, Code::Blocks with GCC 4.2. I have written a code like that: #include <iostream> #include <stdlib.h> #include <pthread.h> using namespace std; void *thread1proc(void* param){ while(true) cout << "1"; return 0; } int main(){ pthread_t thread1; pthread_create(&thread1,NULL,t...
It stops because you call pthread_join and the thread you are joining "to" has an infinite loop. From that link: The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated.
4,370,553
4,370,615
getline and file handling
I want to read the first lines of 2 separate files and then compare them...the following is the code i use but it gives me "istream to string error". do i need to use a while condition to start reading the files first? ifstream data_real(filename.c_str()); /*input streams to check if the flight info ...
getline(istream, string) returns a reference to the istream, not a string. So, comparing the first line of each file could be something like: string read1, read2; if !(getline(is,read1) && getline(data_test,read2)){ // Reading failed // TODO: Handle and/or report error } else{ if(read1.substr(0,3) == read2....
4,370,563
4,370,608
Can a DLL call/load another DLL?
I want to call some third party DLL routines from my own DLL. I'm just not sure how to do that in C++.
You can use load-time dynamic linking or run-time dynamic linking in your DLL in the same way as in the executable. The only restriction is not to call LoadLibrary from your DllMain function to avoid deadlocks.
4,370,601
4,370,634
What do people need to run my application?
I made a little app and built a release version. Now I want to upload it to my site. I have never done this before with Qt, so I'm unsure as to what I should include along with the binary. How do I figure out which DLLs should be included with my app? And where do I get them? I'm running Windows, but I'd also like to k...
For windows: You can use dependency walker to see what Qt libraries (or others) you should ship. This is the depends.exe executable that is included with Visual Studio, but you can download it separately from: http://www.dependencywalker.com/ Load your app into that and it will list out all the modules it expects at ru...
4,370,649
4,370,666
Call c++ function into a PHP code
I have some c++ OOP classes (separated files) , and I want to create objects in PHP code that can call the functions in those classes.. (PHP classes derived from c++ classes). Because the php is not more than a scripting language, I've got some functions that can only writen by a low level language that has a closed r...
PHP classes derived from c++ classes I don't think there is any way for such close interaction. You would have to either Write a PHP extension in C. Related article: Extension Writing Part I: Introduction to PHP and Zend Write an external program and run it using exec()
4,370,702
4,370,841
What problems would you foresee with my 'using block' construct being added to C++?
Header files with declarations like this: void FooBar(System::Network::Win32::Sockets::Handle handle, System::Network::Win32::Sockets::Error& error /*, more fully-qualified param declarations... */); are common in certain frameworks. And using declarations, which could mitigate this problem, are generally not consider...
The ISO/IEC JTC1/SC22/WG21 (aka C++) standards committee is close to finishing the C++0x standard; you have essentially no chance of getting this proposal into the C++0x standard. For any proposal, you have to present the motivation for the feature, explaining why this should be added to the standard instead of the 50 ...
4,370,776
4,370,850
What is a good way to find real time in milliseconds with C++?
I am currently using clock() function supplied by the time.h library. It gives me time precision up to milliseconds. However, it's timing is based on CPU clock cycles. I need a function that instead of using CPU cycles as clock(), will use system realtime with precision up to milliseconds. I am using linux with gcc co...
#include <sys/time.h> ... timeval tv; gettimeofday (&tv, NULL); return double (tv.tv_sec) + 0.000001 * tv.tv_usec;
4,370,813
4,371,596
Using GCC on Mac OS to Compile C Program for MS-DOS (DOSBox)
I am running GCC 4.2.1 under Snow Leopard on Mac OS X. I want to use it to compile some old C/C++ DOS games I wrote 15 years ago so that I can run them under DosBox. To do this they obviously need to be compiled in DOS executable format, can anyone tell me how to do this using GCC please? Thanks!
DOSBox runs 16 bit x86 real-mode code under emulation. The regular GCC compiler on OSX 10.6 targets the OSX operating system and 32 bit x86 protected mode, so you cannot use that to build code to run in DOSBox. What you may be able to do is run a DOS compiler in DOSBox itself. DJGPP is an MS-DOS port of GCC, however it...
4,370,943
4,370,973
Linux executable parameters tab complete
I use Ubuntu. For many executables (i.e. valgrind) you can start typing a parameter like --leak-check=full and tab-complete it by the time you type --le I recently added --version parameter to my own program (in c++). Question: How can I add this functionality of tab-completion of arguments?
You can define that in /etc/bash_completion (edit: and /etc/bash_completion.d/). Have a look at this article: http://www.debian-administration.org/articles/316
4,371,041
4,371,402
Qt - Expand QTreeView on single click?
While double-clicking the text of a QTreeView expands the children, a single-click does not. The icon defined in the CSS (and placed to left of text) expands the children on a single-click, though. How do I make it so a single-click (or touch event) of the text will expand the children? bookTreeView->setModel(sta...
Something along the lines of QObject::connect( tree, SIGNAL(clicked(const QModelIndex &)), tree, SLOT(expand(const QModelIndex &)) ); The clickedsignal might not do what you want. You can also have a look at the currentChanged signal, which might be what you want. I've never used Qt in a mobile context :)
4,371,077
4,371,144
Ambiguous partial template specialization
I've got a trait class which I need to specialize (and partial-specialize) many times. Some partial specializations overlap: template< typename T > struct C { }; template< typename T1, typename T2 > struct TRAIT { }; template< typename T > struct TRAIT< T, T > { }; template< typename T1, typename T2 > struct TRAIT< C<...
Your best bet for this, if you can't avoid overlapping specialization, is to clarify all your overlaps. You'll need to write another specialization for template< typename T> struct TRAIT< C<T>, C<T> > { }; ...but, as everybody else said in the comments, it's best to avoid overlapping if at all possible. As others call...
4,371,479
4,371,547
Can boost::regex_search be done on a wstring?
This is what I tried: std::wstring extractText(std::wstring line) { std::wstring text; boost::regex exp("^.*?PRIVMSG #.*? :(.+)"); boost::smatch match; if (boost::regex_search(line, match, exp)) { text = std::wstring(match[1].first, match[1].second); } return text; ...
use wregex and wsmatch
4,371,520
4,371,642
Do I need to implement a FileNotFoundError exception?
I've a class called TFile, and I can't (don't want to) modify it. It doesn't throw exception if the input/output file is not found but I can check the iternal status using the method IsZombie. Now, I've implemented a very simple exception: class FileNotFoundError : public std::runtime_error { public : FileNotFoundErro...
There is no std exception that gives you a highly selective way to catch a 'file not found' error condition. So, yes, if you want to signal that condition with an exception and you want to allow the client code to do something meaningful then you need to create your own class for that. There is however also a reason w...
4,371,556
4,371,649
Why might the "fatal error C1075" error occur intermittently when using msbuild?
Possibly related to my other question (note: different error code): Why might the “fatal error C1001” error occur intermittently when using msbuild? Our buildbot slave compiles our source code nightly and works most of the time, but intermittently, we see this error: c:\Program Files\Microsoft Visual Studio 9.0\VC\in...
Judging by this and your other question, I'm starting to put my money on "hardware failure". Could be that one bit in one of your RAM chips is faulty, so if you just happen to hit this very byte, a '}' will turn into something else. I'd run a RAM test tool. Does this machine exhibit other weird behavior? Rare random cr...
4,371,580
4,371,640
Crash when accessing matrix in C++
I'm trying to create a 2D array to represent a weighted graph. To make the matrix I am making an array of arrays, as shown in the constructor below. This matrix will store the weight of the edges connecting two nodes. For example graph[1][2] would store the weight of the edge between points 1 and 2. Weighted_graph::We...
I presume you are referencing the graph member of the object you are constructing. However, graph is declared as a local variable there.
4,371,600
7,720,750
Why might the "fatal error C1001" error occur intermittently when using msbuild?
Possibly related to my last question (note: different error code): Why might the "fatal error C1075" error occur intermittently when using msbuild? On our nightly 64-bit build, we see this error appear intermittently: Generating Code... c:\program files\microsoft visual studio 9.0\vc\include\xtree(944) : fatal error ...
Replacing the RAM fixed this (as with my other question with the different error code).
4,371,699
4,371,978
Mixing template function overloading and inheritance
The following code prints: generic overload But what I wanted is that the overload or the specialization were called in both cases, not the generic one. I'm not trying to mix overloading with template specialization, they're here together because none worked as I expected. Is there any template magic to accomplish thi...
Two ways using type_traits to test if the argument is derived from Interface. #include <boost/type_traits.hpp> class Interface {}; class Impl: public Interface {}; class Bar { template <class T> void foo_impl(T& value, boost::false_type) { std::cout << "generic\n"; } void foo_impl(Interface& v...
4,371,767
4,371,785
What is going on when you execute `cout << "output";` in C++?
I'm trying to understand what's really happening when I compile and execute C++ code, but the line cout << "output"; has me a bit confused. I know that the <<, operator is the bitwise leftshift operator, and that executing y = x << 6 will assign the value to y that resulted from shifting x to the left by six bits. I al...
In a word, the << operator is overloaded (a very common c++ feature). Just like other methods, operators may be overloaded, and as hinted by Martin York in his response, operators are little more than methods which the compiler invokes when it parses an operand and operator expression. What happens is that when applied...
4,371,849
4,371,891
boost asio socket exits after sending some msgs
when i connect via telnet to it it's giving me "Connection lost to host" after i receive some msgs then exits, what's wrong? you can review the code here: http://textuallircserver.googlecode.com/svn/trunk/src/client.cpp any help is apperciated
The message "Connection lost to host" sounds like if a firewall were closing the connection down. Can you try telnet via command line and check the output?
4,372,130
4,384,760
ImageMagick open and write image with qt ans magick++
Im using Magick++ Library with Qt Im using the following code to read and write an image: Image image; image.read(qPrintable(f.absoluteFilePath())); image.addNoise(GaussianNoise); image.magick("png"); image.write("image_name"); Where f.absoluteFilePath is the absolute path for my image Example: /Users/user/D...
For everyone who might have tha same problem: Imagemagick will save the images inside the .app bundle You will not be able to find the image files unless you specify a path inside the read() function I noticed the following by checking the size of my .app file It was increased everytime I was trying to save images.
4,372,154
4,372,231
C++ boost - Is there a container working like a queue with direct key access?
I was wonndering about a queue-like container but which has key-access, like a map. My goal is simple : I want a FIFO queue, but, if I insert an element and an element with a given key is already in the queue, I want it the new element to replaced the one already in the queue. For example, a map ordered by insertion ti...
Boost multi-index provides this kind of container. To implement it myself, I'd probably go for a map whose values consist of a linked list node plus a payload. The list node could be hand-rolled, or could be Boost intrusive. Note that the main point of the queue adaptor is to hide most of the interface of Sequence, but...
4,372,224
4,375,053
Fast Method for computing 3x3 symmetric matrix spectral decomposition
I am working on a project where I'm basically preforming PCA millions of times on sets of 20-100 points. Currently, we are using some legacy code that is using GNU's GSL linear algebra pack to do SVD on covariance matrix. This works, but is very slow. I was wondering if there are any simple methods to do eigen decompos...
Using the characteristic polynomial works, but it tends to be somewhat numerically unstable (or at the very least inaccurate). A standard algorithm to compute eigensystems for symmetric matrices is the QR method. For 3x3 matrices, a very slick implementation is possible by building the orthogonal transform out of rotat...
4,372,236
4,372,422
How do I convert from std::wstring _TCHAR []?
I'm using a library and sends me std::wstring from one of its functions, and another library that requires _TCHAR [] to be sent to it. How can I convert it?
Assuming you're using Unicode build, std::wstring.c_str() is what you need. Note that c_str() guarantees that the string it returns is null-terminated. e.g. void func(const wchar_t str[]) { } std::wstring src; func(src.c_str()); If you're using non-Unicode build, you'll need to convert the Unicode string to non Unico...
4,372,312
4,372,348
C++/SDL threading - events break down
I have a Snake game in-development (up at https://github.com/RobotGymnast/Gingerbread/tree/eventThreaded). Initially, everything (graphics, events, game logic update, physics) were called from a "main" thread. Then I started multithreading (using boost threads). It's been pretty straightforward, but I recently split th...
I'm not sure about SDL, but on several windowing subsystems (I believe on both X and Win32), you cannot modify ANYTHING related to a graphics object or widget, except from the thread which initially created that graphics object/widget. It doesn't look like (to my limited 10 second google search) SDL abstracts that bit ...
4,372,328
4,372,388
Piece of code that compiles with gcc but not g++
Possible Duplicates: Is this a legitimate C++ code? “C subset of C++” -> Where not ? examples ? Could anybody come up with a piece of code that compiles with gcc or any other C compiler, and doesn't compile g++ or any other C++ compiler? UPDATE: I don't mean just keywords UPDATE2: Thank you All for answers. Apparent...
#include <stdlib.h> int main() { char* s = malloc(128); return 0; } This will compile with gcc, but not with g++. C++ requires an explicit cast from void* here, whereas C does not.
4,372,554
4,372,585
Magic Square Program (C++)
For those unfamiliar with the classic magic square algorithm: A magic square is a two dimensional array (n x n) which contains a numerical value between the values 1 and n^2 in each location. Each value may appear only once. Furthermore, the sum of each row, column and diagonal must be the same. The input should be od...
You forgot to initialize your MagicSquare to contain all zeros: for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { MagicSquare[i][j] = 0; } } Thus this check will almost always fail: if ( MagicSquare[newRow][newCol] == 0 ) { i = newRow; j = newCol; } As C/++ doesn't initialize them to 0...
4,372,625
4,372,656
How to create function with options of arguments?
Create a function that can have different argument list. something like this void s(int d, double t); void s(string d, UNIT e); thanks in advance. Edit 2: Okay, when i try it with my class it doesn't work... here is my base class class GUIInterface { public: ..... virtual void LoadFile(string fileName) = 0...
Function overloading is perfectly legal in C++, as long as the parameters can produce a unique resolution. In the above case, the first parameter will always be sufficient to resolve uniquely to one of the functions. In a class context, if the member functions are defined in the same class, it works just as it does for...
4,372,725
4,372,771
Test arrays with same value in same position
I have the following problem: here it is...output summary is below. Output Summary: Test two arrays to determine if they contain the same value in the same position. Write a main program that tests function isEqual. Using prototype: bool isEqual(int A[ ], int B[ ] ) #include <iostream> #include <iomanip> #include <stri...
Okay When you use the [] "operator", it checks the value of the array at that position so lets say for array A, A[1] == 3, right? Same goes for B, B[2] == 7 Remember that arrays are 0 based, meaning that element 0 is in fact, the first element in the array (B[0] == 1). so when you're calling "isEqual(A[index], B[index...
4,373,047
4,373,091
Read text file into char Array. C++ ifstream
Im trying to read the whole file.txt into a char array. But having some issues, suggestions please =] ifstream infile; infile.open("file.txt"); char getdata[10000] while (!infile.eof()){ infile.getline(getdata,sizeof(infile)); // if i cout here it looks fine //cout << getdata << endl; } //but this outputs the ...
Every time you read a new line you overwrite the old one. Keep an index variable i and use infile.read(getdata+i,1) then increment i.
4,373,101
4,373,132
what is the operator be overloading here : String8::operator const char*() const
I know it is used to get the containing c string ,similar to std::string.c_str(). But how should I use the operator? //android/frameworks/base/include/utils/String8.h 458 inline String8::operator const char*() const 459 { 460 return mString; 461 }
This is a user-defined conversion, which allows you to convert from a user-defined type to another type. You could do stuff like this, by using it to get a const char* from a String8 object. String8 str = "Hello"; const char *cptr = str; // gets const char* from str std::strlen(str); // std::strlen expects a const cha...
4,373,118
4,373,200
What is the most efficient way to enumerate vertices of k dimensional hypercube in C++?
Basic Question: I have a k dimensional box. I have a vector of upper bounds and lower bounds. What is the most efficient way to enumerate the coordinates of the vertices? Background: As an example, say I have a 3 dimensional box. What is the most efficient algorithm / code to obtain: vertex[0] = ( 0, 0, 0 ) -> ( L...
It will probably go faster if you can reduce conditional branching: bound[idx][k] = upperLowerBounds[(idx >> k) & 1][k]; You might improve things even more if you can interleave the upper and lower bounds in a single array: bound[idx][k] = upperLowerBounds[(k << 1) | (idx >> k)&1]; I don't know if shifting idx increm...
4,373,123
4,448,483
How to get the role of a QPushButton created by a QDialogButtonBox?
I'm trying get all the button child widgets of a currently active window. The buttons were created through QDialogButtonBox. I'm trying to get the roles of each button so I can identify which button is the OK, CANCEL, or SAVE button. However I'm getting an error with the following code: QWidget *pWin = QApplication::a...
You are creating a new empty QDialogButtonBox which has no idea about buttons in allPButtons list. Calling buttonRole() on them returns -1 (InvalidRole) because buttons are not in that button-box. You must do as jkerian wrote and myButtonBoxPtr must point to the QDialogButtonBox which is already in your window. You can...
4,373,307
4,375,732
Is it possible to do an inplace merge without temporary storage?
I was just thinking, if I were to implement std::inplace_merge it would probably look something like this: template <class Bi, class Cmp> void inplace_merge(Bi first, Bi middle, Bi last, Cmp cmp) { if(first != last) { typedef typename iterator_traits<Bi>::value_type T; typedef typename iterator_trai...
There are several known algorithms for merging in-place, though some of them are fairly complex. The general way in which they work is doing an out-of-place merge, using some of the array elements themselves as the external storage space. I know that Alex Stepanov and Paul McJones' "Elements of Programming" details o...
4,373,325
4,373,409
Error "Expected specifier-qualifier-list before" at struct constructor
I am trying to write some code to optimize some Open GL functions for a program I'm writing, unfortunately, I am not exactly a C or C++ veteran, but that's partially why I'm doing this project! So I'm creating a struct to handle 3x3 matrices and I am defining the struct as follows: #ifndef MATRIX3BY3_H #define MATRIX3B...
C does not support constructors or member functions of structs. There is no way you will get this to compile as C or Objective-C. You need to compile this as C++ or Objective-C++, at which point it will almost compile: you have an error in your 3rd constructor, in that you're attempting to initialize the members iy a...
4,373,391
4,373,471
Disable window maximize/minimize
How do I disable the maximizing and/or minimizing capability of a window with the Windows API? The maximize/minimize boxes need to be greyed out and disabled, and double clicking the title bar, dragging to the top of the screen, etc needs to not work also.
You can call SetWindowLong/SetWindowLongPtr to modify a window's styles. For furthur detail, please refer to: http://msdn.microsoft.com/en-us/library/ms633591%28v=VS.85%29.aspx or http://msdn.microsoft.com/en-us/library/ms644898%28VS.85%29.aspx Then, what do u mean about 'draging to the top of the screen'?
4,373,480
4,378,849
In C++, which is faster? (2 * i + 1) or (i << 1 | 1)?
I realize that the answer is probably hardware specific, but I'm curious if there was a more general intuition that I'm missing? I asked this question & given the answer, now I'm wondering if I should alter my approach in general to use "(i << 1|1)" instead of "(2*i + 1)"??
Just an experiment regarding answers given about "... it'll use LEA": The following code: int main(int argc, char **argv) { #ifdef USE_SHIFTOR return (argc << 1 | 1); #else return (2 * argc + 1); #endif } will, with gcc -fomit-frame-pointer -O8 -m{32|64} (for 32bit or 64bit) compile into the following assembly code: ...
4,373,674
4,373,901
Problem properly pushing 2D vector of structs (C++)
I am having trouble filling a vector of type vector<vector<clickable> >. The compiler seems to be ok with pushing back vector<clickable> onto it as long as the push_back happens in the same function as the declaration of the variable, but it doesn't allow it when the variable is declared in a .h file and the push_back ...
The error message says, in effect, that it thinks the vector you're trying to push_back onto is actually a vector<vector<string> >, rather than a vector<vector<clickable> > as you were expecting. You probably just need to do a clean rebuild.
4,374,103
4,374,144
c++ device driver development in linux
I wanted to get more details for writing Graphics device drivers and audio device drivers using c++ for Linux box. I am newbie at developing device drivers , Please provide me development/documentation details for the same. Thanks -Pravin
Linux kernel device drivers are written in C rather than C++. Most device drivers are accessed via a special device file (/dev/yourdevice0) on which control as well as read and write operations can be performed. User mode client programs and user mode drivers open the device file and use it as a pathway to talk to the ...
4,374,352
4,374,363
C++ typedef declaration
Can you please explain what does the following line means? typedef int (*Callback)(void * const param,int s)
It means that Callback is a new name for the type : pointer to a function returning an int and taking two parameters of type 'const pointer to void' and 'int'. Given a function f : int f(void * const param, int s) { /* ... */ } The Callback can be used to store a pointer to f : Callback c = &f; The function f can...
4,374,644
4,375,194
Help with Curl ERRORBUFFER
I have a program which uses curl. and a part of it looks like this.. char* Error = NULL; Error = (char*)malloc(1024); memset(Error, 0, 1024); .............. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, Error); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3); if(CURLE_OK != curl_easy_perform( curl)){ ...
You cannot use a std::string to receive the error as that does not have a writable buffer. You can use a std::vector though if you want to use STL and not have to handle memory of arrays. const size_t errBufSize = 1024; std::vector<char> errBuf( errBufSize ); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &errBuf[0]); Y...
4,374,677
4,374,995
What is the equivalent of a C++ pure-virtual function in Objective-C?
Simple answer would be Protocol. The another point is that it is said that all methods in ObjectC are virtual, so no need to say virtual in ObjC. I find it hard to understand this concept. Any comments to figure out more clear around this question ? Thanks for commenting.
Simple answer would be Protocol. Simple but wrong. A protocol is an interface specification. It's a collection of messages that an object must (ignoring the @optional keyword for now) respond to. The term "virtual function" has no direct counterpart in Objective-C. In Objective-C you don't call functions on obje...
4,374,708
4,374,743
Which Linux distribution should I go for learning C/C++/Assembly in Linux
I am a primary windows developer with experience in C#, .NET, Visual C/C++. I want to lean C/C++ development in linux in order to create portable GUI applications which run on both Windows and Linux. I have used Fedora in past (2005). Want your suggestions to know which is the best distribution currently to learn progr...
You can't really go wrong with any of the major ones. Personally I use Debian, but Fedora and OpenSUSE are good choices as well. I would also like to point out that you can use C# to create portable GUI applications. Have a look at Mono and Gtk#. I have developed quite a few Gtk# apps and they usually run flawlessly...
4,374,953
4,374,992
#include <comutil.h> cause errors
VS 2010 C++ CLR Library project, errors on adding comutil.h library > Error 20 error LNK2001: unresolved > external symbol "extern "C" long > __stdcall VariantCopy(struct tagVARIANT *,struct tagVARIANT const > *)" (?VariantCopy@@$$J18YGJPAUtagVARIANT@@PBU1@@Z) D:\Projects\AL\Service\ncFlow\ncOPClient.NET\Stdafx.obj...
According to MSDN, _bstr_t requires comsuppw.lib. Add this library to the linker dependencies list.
4,374,987
4,375,044
Undefined values in dynamic arrays
I am going through a book to refresh my memory on data structures and c++ and I am reading through implementing a bitvector. In my Bitvector class, I have the following: class BitVector { public: Bitvector(int p_size) { m_array = 0; m_size = 0; Resize(p_size); } ~Bitvector() { ...
You can change the acquisition of the data to: newvector = new unsigned long int[p_size](); to get a block of data initialized to 0s. Or you can initialize it manually either iterating over the array or with memset (which is fine for POD types, but not for non-POD types, so be careful where you use it). On the questio...
4,375,129
4,380,967
How do I get an SSL* from Boost.ASIO?
I'm implementing a client SSL connection via Boost.ASIO. According to the reference book I'm using, I need to call SSL_get_verify_result to ensure that everything's okay with the server certificate. Unfortunately, it takes a pointer to an SSL structure, and I have no idea how to get that out of ASIO. I've tried using t...
Problem solved. The structure that it says impl() returns is boost::asio::ssl::detail::openssl_stream_service::impl_struct*. I didn't expect it to be documented, but I finally searched for it in desperation and discovered otherwise. Even better, it contains a pointer to the SSL structure I need, as well as the OpenSSL ...
4,375,180
4,375,229
How to insert into std::map?
Is there a std iterator I could use to insert elements into std::map using a std algorithm (for example std::copy) ? I need a container to link one object to a string, and I thought about using std::map. Is there a better container? Forgot to say - items needs to be sorted.
I think what the OP is looking for is std::inserter(mymap, mymap.end()) so you can do: std::copy( inp.begin(), inp.end(), std::inserter(mymap, mymap.end()) ); The input types must be a pair type that your map takes, otherwise your algorithm would need to be std::transform with a function/functor to convert the input t...
4,375,224
4,375,305
add constructor to templated class
I have a templated class holding a value. Is it possible to add a constructor to the class to allow implicit conversion like in the example below? Or is there a better way to do this? #include <string> template<typename T> class Value { public: Value(const T& value) : m_value(value) { }; private: T m_value...
Calling f(const Value<std::string>&) with a string literal would require two user-defined conversions (const char[]==>std::string==>Value<std::string>) in order to match the function parameters, while the standard only allows one. I see two possibilities to solve that: either overload the constructor or overload f(). ...
4,375,238
4,400,244
Validating XML that doesn't define a schema using Xerces
I'm using the Xerces-C++ (version 2.6.1) SAX2 parser to validate XML such as the document below. (This is MSML - Media Server Markup Language as defined in RFC 5707.) <?xml version="1.0" encoding="UTF-8"?> <msml version="1.1"> <createconference name="example"> <audiomix> <n-loudest n="3"/> <...
And with much flailing around and trial and error, I eventually found the problems. Validation errors are reported to the error callback on the ErrorHandler passed to the parser. There was no problem with the schemaLocation attribute. With that fixed, and adding in caching of the XML grammar to improve performance,...
4,375,509
4,376,702
Tips about designing containers
Every time when I'm designing new data structures in C++, I have some troubles with pointers, references, constness, etc. Can somebody please recommend me good books with good tips about designing containers? P.S book of John Meyers, is that good choice?
There is a detailed description of how the STL is implemented in "The C++ Standard Library: A Tutorial and Reference" by Nicolai M. Josuttis. Meyer's Effective STL is less comprehensive but does have a section on containers.
4,375,542
4,375,610
unpredictable behaviour of threads
I'm trying to implement this simple example of how to synchronize threads using pthread library: #include <iostream> #include <pthread.h> using namespace std ; static pthread_mutex_t locker; pthread_cond_t cond; volatile bool ok=false; void *func2(void *data) { int i; for(i=0;i<100;i++) { pthread_mutex_lock (&l...
You need to acquire the mutex before you call pthread_cond_wait, and after pthread_cond_wait returns, the mutex is reacquired. Your fun1() should look something like: void *fun1(void *data) { int i; for(i=0;i<100;i++) { pthread_mutex_lock (&locker); if(ok==false) pthread_cond_wai...
4,375,600
4,375,667
Can you mix shared pointers with non-pointer data members?
Take the following example: class BookManager { ... }; class Book { public: void setBookManager(BookManager *bookManager) {m_bookManager = bookManager;} private: BookManager *m_bookManager; }; Since the caller is typically not interested in keeping a BookManager for a Book if the Book...
create a copy BookManagerPtr(new BookMarkManager(m_bookManager)), make m_bookManager a BookManagerPtr too or make book a template thus allowing it to use BookManager* and shared_ptr. shared_ptr is about shared ownership, in your example MyModule owns the example and book don't, so it's not compatible with shared_ptr
4,375,619
4,375,733
Simple compression in c++
we have a C++ MFC application and C# Web Service. They are communicating over HTTP, but as they are exchanging text data, compression will help a lot. But for some reasons, we can't use an external library. We basically need to compress a byte array on one side and decompress it on the other side. What should we use ...
As has already been said, the zlib is probably what you are looking for. There are several algorithms within: The deflate and inflate pair zlib itself lzo The simpler is probably lzo (I advise to pass the uncompressed size on the side), but zlib isn't very complicated either and the compression rate can be parameteri...
4,375,674
4,375,793
How to pass a char* from C to CPP?
A little background: I've got a library of C code that is part of larger system (all C). For this particular part of the C library a GUI has to be created which allows users to play around with the options. For the GUI I've chosen QT, since cross-platform support is desired. I'm using Eclipse and MinGW as IDE and compi...
Your problem is not passing the char * from C to C++ but calling a C++ function from C. I presume that CLogic.c is compiled as a C library? If not, can you rename it to CLogic.cpp or use a compiler switch to force it to be compiled as C++ even though it has a C file extension? If you want a C++ GUI on a C library/syste...
4,375,704
4,375,858
Cannot open source file: 'WIN32': No such file or directory
Getting this error building a C++ project in VS2008. Very confused what it means, why does it think WIN32 is a file?
Go to Project-->Properties-->C/C++-->Command line. You most probably have a /I"" before your /D "WIN32". For some reason an empty include directive causes the /D to evaporate hence your error. Go to Project-->Properties-->C/C++-->General-->Additional include directories and make sure there are no redundant chars there...
4,375,727
4,378,216
Sequential calls to long method produces spilling
Hi the title says everything really. I have a method which reads in a file holding data on the composition of materials (like polythene, or the natural composition of lead) each of these materials is held in a different object and each has a different composition. The make method is called sequentially, as the once the...
In what way is my question incomprehensible? (Seriously, other than my lack of knowledge of technical programming terms, I wrote the code so it could be understood. What does the question lack?) The method above is called six times from the main method. Each time it is called it takes input from a file (such as the s...
4,375,790
4,376,172
Editing an /etc/fstab entry in C++
I'm trying to edit the /etc/fstab file on a CentOS installation using C++. The idea being that based on another config file I will add entries that don't exist in the fstab, or edit entries in the fstab file where the mount point is the same. This lets us set the system up properly on initial bootup. I've found setmn...
When modifying system configuration files such as /etc/fstab keep in mind that these are critical state and, should your "edit" be interrupted by a power loss, might result in a failure to reboot. The way to deal with this is: create an empty output: FILE* out = setmntent("/etc/fstab.new", "rw"); open the original for...
4,375,876
4,385,586
Separating Axis Theorem is driving me nuts!
i am working on an implementation of the Separting Axis Theorem for use in 2D games. It kind of works but just kind of. I use it like this: bool penetration = sat(c1, c2) && sat(c2, c1); Where c1 and c2 are of type Convex, defined as: class Convex { public: float tx, ty; public: std::vector<Point> p; void ...
OK, I was wrong the first time. Looking at your picture of a failure case it is obvious a separating axis exists and is one of the normals (the normal to the long edge of the triangle). The projection is correct, however, your bounds are not. I think the error is here: float c1_min = FLT_MAX, c1_max = FLT_MIN; float c2...
4,375,932
4,375,998
Unable to declare 2 friend overloaded<< in a template .h
I'm trying to create two overloaded operators in a template BSTree.h and am encountering errors that really don't tell me what the problem is. Running a search on the error codes seperate or in conjunction hasn't yielded anything for me. The first overloaded<< for the BSTree doesn't cause any errors on compile, but th...
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Usually this means that the compiler doesn't know an identifier as a type, so it goes assuming it's a parameter name, with the type implicitly being int. (In C of old there was a rule that the int in a parameter type could be om...
4,376,115
4,376,862
c++ API for sql on windows
i have got one small database on microsoft sql and i wannato acces it using c++ api not the vc++ so can any one suggest me how should i do this...
You should have a look at ADO. It's a set of COM classes (so not Visual C++ specific) that can be used from any Windows C++ compiler. If on the other hand you're after a cross platform approach to accessing databases in C++, you might want to have a look at SQLAPI++
4,376,189
4,380,565
Find the first occurence of char c in char *s or return -1
For a homework assignment, I need to implement a function which takes a char *s and a char c and return the index of c if found, and -1 otherwise. Here's my first try: int IndexOf(const char *s, char c) { for (int i = 0; *s != '\0'; ++i, ++s) { if (*s == c) { return i; } } retur...
Yours is perfectly fine, as far as it goes. You should also write a simple test program that tests for the first char, last char, and a missing char. Piling on to the 'other ways to do it' group, here is one with no break, a single return, and showing off pointer arithmetic. But, beware: if I were grading your homework...
4,376,359
4,376,384
Find the index of a special character in string in C++
I wanna know if there is any standard function in visual stodio 2010, C++, which takes a character, and returns the index of it in special string, if it is exist in the string. Tnx
You can use std::strchr. If you have a C like string: const char *s = "hello, weird + char."; strchr(s, '+'); // will return 13, which is '+' position within string If you have a std::string instance: std::string s = "hello, weird + char."; strchr(s.c_str(), '+'); // 13! With a std::string you can also a method on it...
4,376,458
4,394,779
prepend and remove from a ( void * ) in C
i think this is a pretty straight forward problem , but i still can not figure it out . I have function which sends stream over the network . naturally , this takes const void * as argument: void network_send(const void* data, long data_length) i am trying to prepend a specific header in the form of char* to this bef...
using unsigned char * solved the issue . thankyou all for your comments.
4,376,708
4,376,879
allocate shared_ptr in a function
I need to create a function that returns an allocated shared_ptr variable. is this the correct way? typedef boost::shared_ptr<std::vector<char> > sharePtr; void createPtr(sharePtr &p) { p = sharePtr(new std::vector<char>); } void test() { sharePtr p; createPtr(p); }
Yes, it is correct. But why not write just: sharedPtr createPtr() { return sharePtr(new std::vector<char>); } void test() { sharePtr p = createPtr(); } ? This can be faster than your version, and faster even more with a compiler supporting move semantics. It's also recommended to use make_shared instead of d...
4,377,308
4,377,401
C++ size_t or ptrdiff_t
If you have the following code where p is a pointer: p = p + strlen(p) + size_t(1); Since strlen() and size_t are both size_t, should I cast the code to ptrdiff_t ? p = p + (ptrdiff_t)(strlen(p) + size_t(1)); If so why? Thanks, Greg
std::ptrdiff_t is signed. std::size_t is unsigned. Casting strlen(p) to ptrdiff_t would make sense if p could have a negative length, which is not possible. However, that cast could overflow the resulting signed value if p is large enough (for instance, larger than 2,147,483,647 bytes on most 32-bit platforms). So it c...
4,377,320
4,377,528
Converting special characters (like \n) to their escaped versions
How to convert for instance "A\r\nB\tC\nD" to "A\\r\\nB\\tC\\nD" in C(++)? Ideally using standard library only and a bonus upvote for both pure C and pure C++ solutions.
Of course, replace char with wchar_t and std::string with std::wstring if you're using wide character strings. std::string input(/* ... */); std::string output; for(std::string::const_iterator it = input.begin(); it != input.end(); ++it) { char currentValue = *it; switch (currentValue) { case L'\t': ...
4,377,483
4,377,581
c++ static POD initialization
I have a single instance of a simple POD a.hpp class A { struct Zzz { A* m_aPtr; int m_val; } static Zzz s_zzz; }; a.cpp A::Zzz A::s_zzz; I expect that both s_zzz.m_aPtr and s_zzz.m_val will be initialized to zeros before any other static initialization in any other compilation unit and ...
At least in C++0x, you can rely on all zero-initialization being performed before any other initialization code runs. From the C++0x FCD, section [basic.start.init] Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization ...
4,377,582
4,378,169
C++ Virtual classes basic questions
Is there any difference between virtual public & public virtual? If yes, then why? Why are all classes not virtual? Example: class x { protected: int a; }; class y : public virtual x { protected: int b; };
To understand difference between virtual and non-virtual inheritance check (and try to understand) the code: #include <iostream> using namespace std; struct Base { int a; }; struct D11 : virtual Base {}; struct D12 : virtual Base {}; struct D21 : Base {}; struct D22 : Base {}; struc...
4,377,860
4,377,947
when does the memory, pointed by (char *) as function parameter gets deleted?
code 1 : void foo(char * text) {} foo("Test"); as far as i understand, this will happen : memory is allocated for "Test" pointer is created and its value is copyed to (char * text pointer), so (char * text) points to the place in memory, where "Test" is (better to say, on the first char of "Test") after the function...
You can think of string literals as being part of the code. They aren't dynamically allocated, they have so-called "static storage duration", which means they exist for the duration of the program, and they don't need to be freed (indeed, must not be freed). It is always wrong to delete[] something that wasn't created ...
4,377,923
4,385,207
DirectShow Source Filter
I have created directShow Source filter, it tested on Win32, and works fine. But when I port them on windows Mobile 6.5.3 After calling CoCreateInstance(MyfilterGUID), I have such: hr 0x8007007e {The specified module could not be found. } HRESULT Why this happens? I suppose this because something wrong with my Direc...
I resolve this issue, that's happens because, my DLL has dependencies from MS dll msvcr80d.dll. To fix this needed in Visual Studio Project Properties -> General -> Use of MFC set Use MFC in a Static Library. And all works...