1,247 Posted Topics
Re: `(4/(2*n-1)` results in integer division. Instead, you need something like `4.0 / ( 2*n - 1 )` To get alternative plus and minus signs, we do not need the expensive and approximate `std::pow()`. Something like this: // pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + … | |
Re: This is a canonical way to flatten out arrays of more than one (runtime) dimension. (The code below is for three dimensions): #include <vector> #include <memory> template < typename T > struct array_3d_flat { array_3d_flat( std::size_t i, std::size_t j, std::size_t k, const T& v = T() ) : data( i*j*k, … | |
Re: int main(){ vector<user> userDetails; // string line; string userName; string password; { // local scope: we do not want to keep // the stream for longer than necessary ifstream readFile("userInfo.txt"); // while(getline(readFile,line)) { // a line consists of just two ws-seperated tokens // we can directly read them into userName … | |
Re: > `srand(time(NULL));` Not a good idea to reseed the linear congruential rng each time the function is called. Perhaps something like: `static int seed_once = ( std::srand( std::time(0) ), 0 ) ;` instead. Or better still, just document that std::rand() is used; and expect `main()` to call `std::srand()`. C++11: #include … | |
Re: You could do this in linear time; see Boyer and Moore's Voting Algorithm [url]http://www.cs.utexas.edu/users/moore/best-ideas/mjrty/index.html[/url] [CODE=C++98]#include <iostream> int candidate_element( const int *array, int N ) { int count = 1 ; int curr_candidate = 0 ; for( int i = 1 ; i < N ; ++i ) { if( array[i] … | |
Re: > Can anyone show me a few examples or pseudocode of implementation of closest pair algorithm O(n^2), O(n log^2 n), O(n log n)? The assignment states that a simple linear search (quadratic time) is all that is required: > if the closest distance is less than 500 feet, the system … | |
Re: > In the following small c++ program ... Use `std::string` instead? #include <iostream> #include <string> int main( int argc, char* argv[] ) { for( int i = 1 ; i <argc ; ++i ) { const std::string arg = argv[i] ; const auto rem = arg.size() % 3 ; const … | |
Re: Enable all warnings and the compiler will point you in the right direction. #include <iostream> int main() { int a=3; std::cout<< a++ << " " << ++a ; // *** warning: operation on 'a' may be undefined } It is undefined behaviour in both C++98 (which has the old sequence … | |
Re: > Does this mean that if I have a .h file with a templated class in it I don't need to have inclusion guards on it? No. > Long story short, templates are not subject to the linkage part of the One-Definition Rules. The same is true for functions that … | |
Re: Depending on the character set that is being used internally, either `char` / `std::string` or `wchar_t` / `std::wstring` as appropriate. To communicate with the outside world (for instance performing file i/o or communicating over the network), ideally use `utf8` encoded chars and `std::string` or `char16_t` and `std::std::u16string` (which are `utf16` … | |
Re: > ... lose a lot of precision as x moves away from zero since 1E6f/(2*pi) has very few sigfigs after the zero subtracting 1E6f leaves me with 1 or 2 sigfigs when doing the rest of the calculation. If you haven't done so already, you might want to have a … | |
Re: `boost::interprocess::message_queue` is portable. For redirecting standard streams on Windows, see: [http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx](http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx) | |
![]() | Re: > You need top move ALL of the data one character toward the head of the string, not just one. This requires another loop inside the first one. I think your teacher is trying to instruct you on nested loops... `std::remove()` is **O(N)** void remove_space( char* cstr ) { int … |
Re: #include <string> #include <cctype> #include <algorithm> #include <iostream> bool is_palindrome( const std::string& str ) { std::string s ; for( char c : str ) if( std::isalpha(c) ) s += std::toupper(c) ; return !s.empty() && std::equal( s.begin(), s.begin() + s.size()/2, s.rbegin() ) ; } int main() { const char* const phrases[] … | |
Re: > swap random elements as many times as you want. The canonical way to generate an unbiased random permutation in linear time is the Fisher-Yates shuffle http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle Using the standard library: #include <algorithm> #include <random> #include <ctime> #include <cstdlib> #include <iostream> #include <iomanip> int main() { constexpr std::size_t N = … | |
Re: Canonical: #include <memory> namespace restricted { struct A { virtual ~A() {} virtual int value_a() const { return a ; } protected: int a = 0 ; virtual void value_a( int i ) { a = i ; } }; struct B : A { virtual int value_b() const { … | |
Re: > given that it created the && move constructor, why couldn't it create some kind of reference re-assign operator? C++11 did that with `std::reference_wrapper<>`. A small class provided by the library, which fills the syntactic gap. Without having to redefine C++98 references; without causing existing code to break. http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper #include … | |
Re: Local runtime-sized arrays with automatic storage duration (with the undesirable features of C99 VLAs excluded, and support for aggregate initialization and range-based for loops included) will be part of C++14. http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3639.html Note: Implementation support for VLAs has been made optional in C (C11). C++14 wiil also have `std::dynarray<>` http://en.cppreference.com/w/cpp/container/dynarray | |
![]() | Re: #include <iostream> #include <memory> #include <vector> int main() { typedef double corner_points_t[4][3] ; // using corner_points_t = double[4][3] ; std::size_t n = 15 ; // curves.size() // option one: low-level memory management - raw pointer sematics, messy { corner_points_t* corner_points = new corner_points_t[n] ; // { {0} } ; // … ![]() |
Re: #include <iostream> #include <map> #include <string> int main() { std::map< int, std::string > map { { 1, "one" }, { 3,"three" }, { 5,"five" }, { 7, "seven" }, { 9, "nine" }, { 11, "eleven" } } ; std::map<int,std::string>::key_type two = 2 ; std::map<int,std::string>::key_type ten = 10 ; // … | |
Re: http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html | |
Re: > In C/C++, the char type is just that, an integer type (with values between -128 and 127) with some special semantics. The default `char` type may be an unsigned integral type. > It is implementation-defined whether a char object can hold negative values. - IS . . . > … | |
Re: A class that has a constructor that accepts a range: #include <iostream> #include <initializer_list> #include <iterator> #include <array> #include <vector> #include <sstream> struct A { template < typename ITERATOR > A( ITERATOR begin, ITERATOR end ) { std::cout << "A::constructor - " ; for( ; begin != end ; ++begin … | |
Re: For `std::regex_search()` with iterators, the iterators must be for iterating over a sequence of **characters**. Iterator through the vector `tokens`, pick up each `std::wstring` and then apply `std::regex_search()` on the sequence of characters in the string. #include <fstream> #include <vector> #include <string> #include <boost/regex.hpp> // testing with GCC 4.8, broken … | |
Re: > But, since I am a newbie, I decided to start learning about reading binary files first Yes. Learn by taking one small step at a time. And while you are learning, learn good idioms. This is rarely right: `char * buffer = new char [length];` Instead, use `std::vector<>` or … | |
Re: I've found that Boost Python works best with C++ http://www.boost.org/doc/libs/1_52_0/libs/python/doc/ Perhaps, you would want to use it in conjunction with py++ http://pypi.python.org/pypi/pyplusplus/ The other major option is SWIG. http://www.swig.org/ | |
Re: you may find this link interesting. [url]http://msdn2.microsoft.com/en-us/library/ms724423(VS.85).aspx[/url] | |
Re: The IS is the place where something about C++ is "officially" said. > 2.14.7 The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. Oitside of that, this is about as close as one can get: http://www.stroustrup.com/C++11FAQ.html#nullptr | |
Re: wouldn't [ICODE]/usr/share/dict/words[/ICODE] suffice? in FreeBSD, this has words from Webster's 2nd International dictionary (quite a few words). [CODE]>cat /usr/share/dict/words | wc -lw 235882 235882 [/CODE] if you are not on unix, download from [url]http://www.freebsd.org/cgi/cvsweb.cgi/src/share/dict/web2[/url] | |
Re: > can't we use a string function pls? Not functions in `<string>`, but a couple of functions in `<ctime>` #include <iostream> #include <ctime> int main() { int month, day, year ; std::cin >> month >> day >> year ; // validate std::tm tm ; tm.tm_mon = month - 1 ; … | |
Re: Though **n** is very large, **n-m** is quite small `(n-m) < 100000`. You do not need a full sieve; a partial sieve with a size of **n-m+1** would suffice. #include <iostream> #include <vector> #include <cmath> // copy all prime numbers between m and n to stm void copy_primes_between( int m, … | |
Re: Well, brace-enclosed initialization solves the 'most vexing parse' problem quite nicely. struct A { A() ; /* ... */ } ; struct B { B(A) ; /* ... */ } ; B b1 ( A() ) ; // declares a function b1 B b2 { A{} } ; // defines … | |
Re: #include <chrono> #include <type_traits> struct timer { typedef typename std::conditional< std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock >::type clock_type ; // ... private: clock_type::time_point start_time /* = clock_type::now() */ ; }; | |
Re: For an **O(log n)** algortithm, see: http://stackoverflow.com/questions/9812742/finding-the-total-number-of-set-bits-from-1-to-n | |
Re: A far better list than anything you would find on this site: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list | |
Re: > proper way to pass a temporary stream... > I'm disliking the std::stream's lack of copy constructors. > I know exactly what the problem is, but I don't know what I can do about it The proper way is to move the temporary stream. Stream classes in C++ are moveable, … | |
Re: > x,y are coordinates of a point and double is their polar angle. and i am doing this sorting so that after sorting the points are in the order which will make a polygon. For a sort using the default `operator<` for `std::pair<>` to result in an ordering of the … | |
Re: You would find it a lot easier if you factor the code into small functions, each function doing just one thing, and doing it well. Problem one: get validated numeric input from user int int_in_range_from_stdin( int min, int max ) { int number ; std::cout << "enter an integer in … | |
Re: > either way, the first code produce type error which should not be there if the second code is working. :/ Each element of a two-dimensional array is a one-dimensional array. Not a pointer to a one-dimensional array. int a[20] ; for( int& i : a ) i = 0 … | |
Re: > There is no reason for that dynamic_pointer_cast to fail to compile, or the push_back to the vector for that matter. Whatever is causing this error is not your responsibility, it is that of Microsoft developers. Either file a bug report or see if they fixed it in VS2012 (november … | |
Re: while(!inputFile.eof()) { getline(inputFile, myString); // what happens if this fails? list.push_back(myString); // push_back the previous line one more time? } Instead, write: while( getline( inputFile, myString ) ) list.push_back(myString) ; | |
Re: > i put the seed in side the function. the int main is only calling the function. void my_function() { static const int seed_once = ( std::srand( std::time(0) ), 0 ) ; // ... } > I want to pick a random number from 60,000 to 200,000. #include <iostream> #include … | |
Re: > But, i didn't understand what other memory is needed for. > Could anyone please explain what this excess memory is needed for? There are very few people who could explain this better than Doug Lea. > ... > This approach leads to fixed bookkeeping overhead per chunk. Because both … | |
Re: > Can C++11's Mutexes be used for Inter-Process Communication? In other words, can it be used for shared memory and signalling an event? C++11 does not have any inter-process functionality. C++11 threading primitives (mutexes, atomics, etc) are just that - threading primitives. They know nothing about processes, and they are … | |
Re: Visual Studio 2012 (November update). Way ahead of GCC (the other major contender) in C++11 conformance - Microsoft has implemented almost everything in the standard. clang 3.2 with its libc++ is on par with VS 2012; and it is somewhat more mature and stable in comparison. But it has to … | |
Re: struct A // non-copyable, moveable { A() { /* ... */ } ~A() { /* ... */ } A( const A& ) = delete ; A& operator= ( const A& ) = delete ; A( A&& ) { /* ... */ } A& operator= ( A&& ) { /* ... … | |
Re: in addition to what you are currently doing, you also need to print the characters for the lines. for example: [code=cplusplus] #include <iostream> #include <iomanip> using namespace std; int main() { cout << setw(4) << right << "|"; for( int i=1; i<=10 ; ++i ) cout << left << setw(5) … | |
Re: > i would reconmend not using Xcode if your working on c++ becuse it uses the std c++ libray There is nothing fundamentally wrong with Xcode as an IDE for C++. You can't program in C++ - Xcode or no Xcode - without using the standard C++ library. If Xmod … | |
Re: Simplest: use `std::ifstrea`m for input, `std::ofstream` for output. // read from file { std::ifstream file( FILENAME ) ; // open file for input // read stuff // ... } // file is closed when the stream goes out of scope // over-write the contents of the file { std::ofstream file( … | |
Re: A one-off calculation of the hamming distance between two strings would take O(N) time. This code would not be noticeably faster - but it is perhaps cleaner. #include <string> std::size_t hamming_distance( const std::string& a, const std::string& b ) { if( a.size() != b.size() ) return -1 ; std::size_t hd = … |
The End.