Keep it simpler, it's C++, not Pascal ;) :
//checks for leap year
bool checkLeapYr(int year)
{
return year%4 == 0 && (year %100 != 0 || year%400 == 0);
}//end function check leap year//checks for leap year
Keep it simpler, it's C++, not Pascal ;) :
//checks for leap year
bool checkLeapYr(int year)
{
return year%4 == 0 && (year %100 != 0 || year%400 == 0);
}//end function check leap year//checks for leap year
A string literal is a constant value in modern C and C++, so the pointer to it has const char*
type (not char*
). The Melarki constructor wants char* argument. Why? It's a very dangerous class. For example, your program is evidently wrong: Melarki destructor called for wholeMelarki will try to deallocate "Stuff" literal in static memory!
Alas, for backward compatibility such (wrong) literal usage treated as deprecated (but not invalid).
You can fix this error if you redesign this class - deallocation bomb from the scratch...
No need to pass references to arrays. In actual fact a pointer to a 1st element of an array passed. Array contents never copied when passed as argument.
What for all these ordinar functions are collected in a class?
You are trying to build absolutely senseless, absurd class NoFather (remember The House That Jack Built... ;) ?):
class NoFather {
...
private: NoFather DataNoFather;
};
Well, we have an object of type NoFather which has a member of type NoFather which has a member of type NoFather...
Formally at the point of DataNoFather declaration all the class NoFather was not completely constructed (that's why you get the message). In actual fact you are trying to construct an impossible thing...
1. Correct function body, of course. Absolutely clear declaration:
void arrSelectSort(int arr[], int size);
// the same as
void arrSelectSort(int *arr, int size);
2. It seems you forgot to initialize total var...
ddanbe, I'm indifferent to C#, Java, C++, Ada, Fortran, PL/I or what else codes on C forum for beginners. And shankhs? Let he/she gets the feel of new language (that's C)...
Best regards
Look at the state-of-art programming of embedded systems for modern microcontrollers. As usually, all codes are written in C. Imagine: no any OS to support an execution of these programs (TinyOS, Contiki et al are not true OS but these control programs are implemented in C too).
Don't forget: most of C compilers have built-in assembler construct (remember asm keyword). When asm instruction enclosed by C function, it's C (not assembler) code again.
More than 30 years ago some OS were written (not only in C) from the scratch w/o any assembler codes. And vice versa: huge programs were written in assembler only (or even in machine codes) long before the C language was born.
Moral: programming languages do not make programs ;)...
I don't understand what for C# code appeares here. There are a lots of insertion (and others) sort C codes in INET. For example, that's one from the excellent tutorial
http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_sorting.aspx#insert
void jsw_insertion ( Str a[], int n )
{
int i;
for ( i = 1; i < n; i++ ) {
int j, save = a[i];
for ( j = i; j >= 1 && a[j - 1] > save; j-- )
a[j] = a[j - 1];
a[j] = save;
}
}
Now look at the a[j - 1] > save
condition. Change all int type for structured variables (not for index variables, of course) to your tc type. So the insert condition must be as follows:
(a[j - 1].cost > save.cost || (a[j - 1].cost == save.cost && a[j-1].amt > save.amt))
That's all. No need to assign structures by elements.
It seems there is a subtle defect in the presented code. You don't break inner loop after key == cases[i].cost
(and have misprint there) but the second member test gets false. It's case <= save
situation but the inner loop continued...
1. Where is an object stored? All non-static members stored there, in the same place:
MyClass ImInStaticStorage;
void where() {
MyClass ImOnTheStack;
MyClsss* pointToTheHeap = new MyClass;
...
delete pointToTheHeap;
}
2. Initially it points to nowhere if you don't initialize it (has unpredictable value).
3. What to do with a pointer member in the class destructor: it depends... If the class object "owns" the referred object (for example, you allocate referred object in a class constructor), you must delete it (no need to assign 0 after that). If you saved this pointer value into the member but don't control life time of the referred object - do nothing.
About int member: int is a simple basic type, no destructors for basic types. Don't worry about int members destiny after destruction...
Privatness is a member name accessibility (not storage class) attribute.
bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
UINT codepage = CP_ACP)
{
bool res = false;
char* p = 0;
int bsz;
bsz = WideCharToMultiByte(codepage,
0,
pw,-1,
0,0,
0,0);
if (bsz > 0) {
p = new char[bsz];
int rc = WideCharToMultiByte(codepage,
0,
pw,-1,
p,bsz,
0,0);
if (rc != 0) {
p[bsz-1] = 0;
s = p;
res = true;
}
}
delete [] p;
return res;
}
int main()
{
wchar_t msg[] = L"Hello, world!";
std::string s("\?");
cvtLPW2stdstring(s,msg);
std::cout << s << std::endl;
return 0;
}
It's possible to add more parameters check ups...
At first define position specifications. For example, what's a position for inexistent item value? What's a position of the 1st node - and so on...
Alas, it's impossible now to separate template class declaration and implementation. Why? Have a look at
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
So place all your cpp file contents into template definition header file (then wait for a new compilers generation ;))...
I think that one of the most promising C++/web technologies is FastCGI. Look at
http://cryp.to/publications/fastcgi/
FastCGI combines the C++ power and comfort programming environment with extremely fast reactiveness and scalability...
May be it was a test on logics and theory of binary arithmetics?..
Sometimes I think that 9 of 10 questions on the C and C++ forums are 100% absurdity...
A la "Urgent help needed! I'm trying to assign void main to char then convert it to a pointer to 2.5D vector but my program do nothing and my compiler said that I have missed semicolon. Why?".
Well, it's a good time to change notes:
/// Must be coin[0] < coin[1] < ... < coin[n-1]
int NumberOfWays(int sum, const int coin[], int n) {
if (0 >-- n)
return 0;
int high = coin[n];
if (n == 0)
return sum % high? 0: 1;
int k = sum / high;
int ways = 0;
for (int i = 0; i <= k; ++i, sum -= high) {
ways += NumberOfWays(sum, coin, n);
}
return ways;
}
int main()
{
int coin[] = { 1, 2, 5, 25 };
int n = sizeof coin / sizeof *coin;
int ways, sum = 100;
ways = NumberOfWays(sum,coin,n);
std::cout << ways << std::endl;
return 0;
}
// Output: 1042. Heaps of ways!..
Absolutely supersonic code ;)...
That's the fateful (and typical) mistake in the average value calculations:
double average;
int sum = 0;
...
average = (sum / 5); // *** integer division!
You try to assign the result of integer division to double value. You want to get exact average value. But 7/5 == 1, 9/5 == 1, 12/5 == 2 and so on. You lost a fractional part of calculated value. It does not matter what's a type of a target.
If you want to get an exact (more precisely, double type) result, make float division, for example:
average = sum / 5.0; // Type of 5.0 constant is double
Look at the trailed backslash:
// Test constructors\
Complex c1, c2(6.35), c3(-5.5, 3.0);
It's a continuation-line character in C and C++. The next line now is a part of a single-line comment, so you don't declare c1, c2 and c2 variables!
The 2nd error is hidden (for the present):
#ifndef Complex_H
#define Complex_h
The C++ names are case sensitive ones. So your header file protection does not work: you define the different macros name.
That's all for now...
It seems now this thread looks like a horrible mash of valued receipts and consumate gibberish advices.
You can't use windows.h header with aged 16-bit Turbo C++ 3.0 compiler.
You can't use goto statement to jump into the main function from outside its body.
You can't do the simplest thing: to present your snippets in a proper way:
[code=cplusplus] your sources
[/code]
Free advice: stop this thread, start from the beginning. Declare well-defined problem in the header of a new thread, present selected suspicious code then ask help on the problem...
Of course, it's my own opinion only ;)...
The special pointer this
has type Class*const
(not Class*) so you can't pass this
as an argument to myFunction.
It seems the myfunction member has a slightly unusual signature with the 1st parameter of type "a reference to a pointer to myClass<temp_Type>". Can you explain what do you want to do with the 1st parameter of this member function?
What's a hot thread!..
I don't know why you want to copy vector contents into dynamically allocated array. I think it's not so good idea: you get a new pointer to the heap then have a new trouble with its deallocation in a proper moment. You always can obtain a pointer to &v[0] (it's a valid pointer until the vector size is changed).
But if you need a special function template to copy vector contents into array, better keep it so simple as you can, for example:
template <typename V>
typename V::value_type* makearray(const V& v) {
V::value_type* p = 0;
size_t n = v.size();
if (n) {
p = new V::value_type[n];
for (size_t i = 0; i < n; ++i)
p[i] = v[i];
}
return p;
}
...
std::vector<int> v;
... v.push_back(...
int* p = makearray(v);
if (!p) {
... the only reason was v.size() == 0;
... break the code: no sense to continue...
}
... // You have v.size() in this context,
// no need in a special parameter...
... do what you want to do...
...
delete [] p;
Thank you all participants for a very interesting discussion in the thread.
Some additions:
Let's remember what is a copy constructor in C++. Copy constructors are (C++ Std, 12.8):
A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments
...
Note: all forms of copy constructor may be declared for a class.
A compiler-generated (default) copy constructor always has const X& parameter. Some careful compilers print warnings if you have more than one copy constructor declared for a class (VC++ 9, for example, does it). I think, it's a very helpful warning in most of cases.
If a class has a copy constructor with X& parameter, this constructor works for non-const initializer (see the 1st post of the thread). It does not matter what "constantness" of initialized object (see an example with Func parameter binding).
So it's possible to modify a non-const only ARGUMENT object (initializer) via X& copy constructor of another object. Sometimes it's useful feature but as usually is an example of bad practice...
At the same time let's repeate that constantness of ordinar (free, not-member) functions parameters is not a part of function signatures. So it's an error to define two functions:
void F(X x) { ... }
void F(const X x) { ... }
All static member …
Let's remember the original post:
...I have four bytes each in an unsigned char:
unsigned char a = BC;
unsigned char b = 1E;
unsigned char c = 04;
unsigned char d = 00;I want to have it so I can put the value 00041EBC into a long variable. This would mean I would need to combine char d,c,b,a in that order to get 00041EBC...
I think it's exactly LSB/MSB specification. The author wants to get long integer value where byte a gets 8 least significant bits, b gets the next 8 bits and so on. It's absolutely little/big-endian neutral specification.
That's why we must (and can ;)) use a portable, architecture-independent approach (with shift operator, for example - this operator effects are so portable defined in the language).
Well, start from the preparing of complete specifications then prepare the use cases list then get down to the application architecture design then implement and debug it (in step by step refinement loop) then test your complete POS application and deploy it...
It's so simple ;)...
Of course, the C++ compiler does not like overloaded shift operator with string left operand. You want insert >> word
, right?
A very unfortunate name for input stringstream: insert...
Copy/paste all commentaries from the source: it's your desired pseudocode ;)...
I think it's a very interesting question. From the C++ Standard (4.5, 1):
An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.
No doubts that VC++ int type can represent all the values of unsigned short. So x * y result was promoted to int (not to unsigned int). That's why this diagnostic message was generated (unsigned long < int and so on)...
1. Regrettably, for negative numbers williamhemsworth's solution does not work (moreover, gives wrong result - for example, it yields 0 for -0.9 but nearest integer value for -0.9 is -1). Right solution:
#include <cmath>
...
double round(double x) {
bool negative = false;
if (x < 0.0) {
x = -x;
negative = true;
}
x = std::floor(x+0.5);
return negative? -x: x;
}
2. In this context a rounding to the nearest integer is not the same thing as a rounding to the nearest int type value. For example, on 32-bit CPU max int is 2147483647 (INT_MAX macros from limit.h). So you can't round 3333333333.3 to int 3333333333 (no such int value) - but you can round it to 3333333333.0. Of course, if you want to round to int, you may use the same method as in round function defined above (no need in floor library call in that case).
Please, read this
http://www.daniweb.com/forums/announcement8-2.html
and this
http://www.daniweb.com/forums/thread78060.html
(especially the last para)...
Don't waste time on these vector based solution debugging troubles.
typedef std::map<std::string,int> Dictionary;
typedef Dictionary::iterator Diter;
typedef Dictionary::const_iterator Citer;
typedef std::pair<std::string,int> V;
// I don't like to inherit from STL classes...
struct Dict
{
Dict& ins(const std::string& word);
Dict& ins(const char* pword)
{
if (pword)
ins(std::string(pword));
return *this;
}
Dictionary dict;
};
// Increment counter if the word found.
Dict& Dict::ins(const std::string& word)
{
Diter d = dict.find(word);
if (d != dict.end())
(*d).second++;
else // new word
dict.insert(V(word,1));
return *this;
}
int main()
{
Dict d;
d.ins("vector").ins("all").ins("problems");
d.ins("avoided").ins("no").ins("vector");
for (Citer p = d.dict.begin(); p != d.dict.end(); ++p)
std::cout << (*p).second << '\t' << (*p).first << '\n';
std::cout.flush();
// If you want vector of word+counter, here it is:
std::vector<V> v(d.dict.begin(),d.dict.end());
std::cout << '=' << v.size() << std::endl;
return 0;
}
/* Output:
1 all
1 avoided
1 no
1 problems
2 vector
=5
*/
Stricktly speaking it's possible and valid behaviour of floating-point calculations.
Floating point types are not mathematical real numbers. The last ones have "infinit" precision but doubles and floats are approximations of real numbers.
So C language literal 0.7 is an approximation (of double type by definition) of the real number 0.7 and 0.7f is ANOTHER approximation of this number. May be 0.7 == 0.7f, may be 0.7 != 0.7f!
Moreover, don't intend that the following code prints OK:
double x = 7.0 / 10.0;
if (x == 0.7)
printf("OK\n");
You can read (by scanf) 0.7 from a text file but you can't intend that the number is equal to 0.7 literal from your code.
Look at your code fragment again:
float a=0.7;
if (a > 0.7)
...
if (a < 0.7f)
...
The 1st if expression evaluation: promote a to double then compare with double type literal.
The 2nd: compare float a var value with float type literal.
Absolutely different operations involved...
Moral:
1. The only "trustworthy" equality tests for floating-point data are == 0.0 and != 0.0.
2. Remember that double and float values are approximations, not exact values.
3. Never use float type in math calculations: it has too low precision.
Probably it was your maiden filght over Computational Mathematics Area ;).
Bon voyage!...
As far as I know the empty CSV line is ",,,,,,,,".
With minimal syntax check up:
/* Includes:
#include <cstring>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
*/
struct Tokenizer
{
public:
Tokenizer(char delim):chdelim(delim)
{}
void setDelim(char delim);
void clear() { token.clear(); }
int parse(const char* ptext);
int parse(const std::string& s) { return parse(s.c_str()); }
int size() { return token.size(); }
std::vector<std::string> token;
char chdelim;
};
int Tokenizer::parse(const char* ptext)
{
clear();
if (!ptext)
return 0;
std::string tok;
const char* p = ptext;
const char* q, *qq;
const char* qend = ptext + std::strlen(ptext);
bool goon = true;
for (p = ptext; goon ;p = q+1)
{
q = std::strchr(p,chdelim);
if (!q)
{
q = qend;
goon = false;
}
while (p < q && *p == ' ')
++p;
for (qq = q - 1; qq > p && *qq == ' '; --qq)
;
tok.assign(p,qq-p+1);
token.push_back(tok);
}
return size();
}
struct RowCol
{
RowCol():x(0),y(0) {}
RowCol& set(int i, int j)
{
x = i; y = j;
return *this;
}
bool parse(const char* pxy);
bool parse(const std::string& sxy)
{
return parse(sxy.c_str());
}
int x, y;
};
bool operator <(const RowCol& a,const RowCol& b)
{
return a.x < b.x?true:a.x > b.x?false:a.y < b.y;
}
bool RowCol::parse(const char* pxy)
{
if (!pxy || *pxy != '(')
return false;
Tokenizer t(',');
t.parse(pxy+1);
if (t.size() != 2)
return false;
x = atoi(pxy+1);
y = atoi(t.token[1].c_str());
return true;
}
typedef std::map<RowCol,std::string> Map;
typedef Map::const_iterator Iter;
typedef std::pair<RowCol,std::string> V; …
It seems the best answer is: Google is your friend ;)...
Try Ultimate++ RAD suite (a very goos IDE TheIDE bundled with MinGW compiler). It's integrated with SDL game graphic library (download it separately), examples included.
http://www.ultimatepp.org/
Use double (not float) type for math calculations!
double x, y, z, sum, pi;
...
sum = 1.0;
for (i = 0, y = 3.0; i < n; ++i, y += 2.0)
{
z = 1.0 / y;
if ((i & 1) == 0)
sum -= z;
else
sum += z;
}
pi = 4.0 * sum;
It depends on OS. No the C language specifications. For Windows see:
http://forums.msdn.microsoft.com/en-US/vclanguage/thread/79b89629-765f-4e9a-9bfb-f99226ef8821/
Unix: http://www.in-ulm.de/~mascheck/various/argmax/
Please, let's stop an impetuous publicity of std::vector class as universal panacea.
It is std::valarray is the most effective STL class for dynamic size arrays of numbers.
See, for example: http://stdcxx.apache.org/doc/stdlibref/valarray.html
C++ Standard:
The class template valarray<T > is a one-dimensional smart array, with elements numbered sequentially from zero. It is a representation of the mathematical concept of an ordered set of values.
As usually, no need to dynamically change size of an array after its creation (the main goal of std::vector class). So valarray elements access is faster than vector elements access (with factor 3-4! ). There are tons of use cases where valarray code looks like a wonder of clarity, laconic brevity and effectiveness. In simple cases valarray is an usual array with a wonderful size() member function...
Some additions:
In most of C++ implementations reinterpret_cast do nothing (like formally incorrect union trick, see Radical Edward's note). If you want to make a trick, do it honestly (it is open to question, of course ;)). It follows from this that reinterpret_cast is "better" than union trick (in the spirit of C++ language).
I know (old) computers where pointers are hardware-typed, so you can't refer to an integer via pointer to float (and vice versa). Probably, on such computers C++ compiler (in theory) can generate a proper conversion code for reinterpret_cast (but not for unions, of course). A very good compiler is capable to generate a proper run-time check up of a good object alignment (in debug mode, for example) for reinterpret_cast - and so on.
Apropos, reinterpret_cast for pointers has C++-defined result only if you previously assigned a pointer value to void* then reinterpret_cast this void* value to the same type!
Moral: use reinterpret_cast where possible, but a trick is a trick...
It was a very interesting remark especially taking into account:
1. No classes in pure C
2. It's C++ forum.
;)
Of course, you have (formal) access rights to a really allocated by reserve() call vector's memory buffer. So quadsPerVertIndex[n]
returned a reference to your process memory chunk (no segmentation faults at this moment). But the next step of quadsPerVertIndex[n].push_back(i/4)
expression' elaboration was:
call push_back() member function for the vector (see vector header sceleton in my post above) which was placed in this memory slot.
Alas, there is no any valid vector header info in this slot now (reserve() call does not built any vector elements in a new buffer). But push_back() code does not know about that. It takes a pointer (no valid pointer values here) and try to access memory via this "pointer" value... Crash...
Have you noticed that resize() creates empty element objects? In your case:
1. resize() calls vector<int> constructor for every new slot in the buffer.
2. push_back takes an empty vector, allocates a buffer for a pushed element - and so on...
Moral: resize() is not "better" than reserve(). These vector member functions have different functionalities - vector maintenace for resize(), vector usage optimization for reserve().
Sorry, but char* ay[][255]
declares 2D array of pointers to char.
Probably, coveredinflies wants to pass an array as a function argument so right example is most likely
void foo(char ay[][255] );
But it's not the same as
void foo(char **ay);
A pointer to an array is a funny thing in C and C++. Array name is implicitly converted in a pointer in all contexts except argument of sizeof operator. So no need in pointers to arrays.
But we can't pass 2D array declared as a[...][...] in the second foo because of its argument type is a pointer to a pointer to char, but not an implicit pointer to 2D array with 255 columns...
As usually, a proper typedef helps to clear codes:
class Movie
{
typedef void (Movie::*MovieFunc)();
public:
Movie()
{
f.push_back(&Movie::heHe);
f.push_back(&Movie::haHa);
}
void show(int part) { (this->*f[part])(); }
private:
void heHe() { cout << "He he" << endl; }
void haHa() { cout << "Ha ha" << endl; }
vector<MovieFunc> f;
};
void Serial()
{
Movie m;
m.show(0);
m.show(1);
}
Must be char* foo ( const char *msg ) {
, of course ;)...
Try to compress:
bool Reverser(std::istream& sentence = std::cin, bool im1st = true)
{
std::string word;
if (sentence >> word)
{
if (Reverser(sentence,false))
std::cout << " ";
std::cout << word;
if (im1st)
std::cout << std::endl;
return true;
}
return false;
}
#include <ctype.h>
// or #include <cctype> in C++
if (isascii(c))
{...
It's the same as (c&~0x7F)==0...
Apropos, I far as I know, rand() % N
(where rand() is a pseudo-random numbers generator) is NOT uniformely distributed in 0..N-1 range...
Right (but cumbersom) construct is (alas):
(int)(N*(rand()/(double)MAX_RAND))
I like Todd Veldhuizen's remark very much (http://www.oonumerics.org/oon/oon-list/archive/0331.html):
C++ is a chainsaw, a nailgun, a 15-ton bulldozer.
A toothpick is not so "hard" as a 15-ton bulldozer, right? But is a toolpick better than a bulldozer? It depends...
I think, it's an absolutely aimless article (and discussion too), because of VTBL is not a part of C++ language. If you want to know how virtual functions calls were implemented in the specific C++ implementation. search Google (or what else;)), for example:
http://forums.msdn.microsoft.com/ru-RU/vclanguage/thread/0e2d1b36-1805-46de-afe8-ce7b6348fe28
http://bytes.com/forum/thread535605.html
I have no time to copy/paste all URLs;)...
See also
http://www.gidforums.com/t-17557.html
Storm in a teacap...
From C++ Standard:
15.5.2 The std::unexpected() function [except.unexpected]
1 If a function with an exception-specification throws an exception that is not listed in the exception-specification, the function std::unexpected() is called (18.6.2) immediately after completing the stack unwinding for the former function
2 The std::unexpected() function shall not return, but it can throw (or re-throw) an exception. If it throws a new exception which is allowed by the exception specification which previously was violated, then the search for another handler will continue at the call of the function whose exception specification was violated. If it throws or rethrows an exception that the exception-specification does not allow then the following happens: If the exception-specification does not include the class std::bad_exception (18.6.2.1) then the function std::terminate() is called, otherwise the thrown exception is replaced by an implementation-defined object of the type std::bad_exception and the search for another handler will continue at the call of the function whose exception-specification was violated.
3 Thus, an exception-specification guarantees that only the listed exceptions will be thrown.
...
and another quote:
18.6.2.2 Type unexpected_handler [lib.unexpected.handler]
typedef void (* unexpected_handler )();
1 The type of a handler function to be called by unexpected() when a function attempts to throw an exception not listed in its exception-specification.
2 Required behavior: An unexpected_handler shall not return. See also 15.5.2.
3 Default behavior: The implementation’s default unexpected_handler calls terminate().
May be, it helps.