Search Results

Search found 1031 results on 42 pages for 'iostream'.

Page 7/42 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • is Boost Library's weighted median broken?

    - by user624188
    I confess that I am no expert in C++. I am looking for a fast way to compute weighted median, which Boost seemed to have. But it seems I am not able to make it work. #include <iostream> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/median.hpp> #include <boost/accumulators/statistics/weighted_median.hpp> using namespace boost::accumulators; int main() { // Define an accumulator set accumulator_set<double, stats<tag::median > > acc1; accumulator_set<double, stats<tag::median >, float> acc2; // push in some data ... acc1(0.1); acc1(0.2); acc1(0.3); acc1(0.4); acc1(0.5); acc1(0.6); acc2(0.1, weight=0.); acc2(0.2, weight=0.); acc2(0.3, weight=0.); acc2(0.4, weight=1.); acc2(0.5, weight=1.); acc2(0.6, weight=1.); // Display the results ... std::cout << " Median: " << median(acc1) << std::endl; std::cout << "Weighted Median: " << median(acc2) << std::endl; return 0; } produces the following output, which is clearly wrong. Median: 0.3 Weighted Median: 0.3 Am I doing something wrong? Any help will be greatly appreciated. * however, the weighted sum works correctly * @glowcoder: The weighted sum works perfectly fine like this. #include <iostream> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <boost/accumulators/statistics/weighted_sum.hpp> using namespace boost::accumulators; int main() { // Define an accumulator set accumulator_set<double, stats<tag::sum > > acc1; accumulator_set<double, stats<tag::sum >, float> acc2; // accumulator_set<double, stats<tag::median >, float> acc2; // push in some data ... acc1(0.1); acc1(0.2); acc1(0.3); acc1(0.4); acc1(0.5); acc1(0.6); acc2(0.1, weight=0.); acc2(0.2, weight=0.); acc2(0.3, weight=0.); acc2(0.4, weight=1.); acc2(0.5, weight=1.); acc2(0.6, weight=1.); // Display the results ... std::cout << " Median: " << sum(acc1) << std::endl; std::cout << "Weighted Median: " << sum(acc2) << std::endl; return 0; } and the result is Sum: 2.1 Weighted Sum: 1.5

    Read the article

  • What am I doing wrong?, linking in C++

    - by Facon
    I'm trying to code a simple base64 encoder/decoder (to test my programming skill). I can compile it, but it doesn't link, I've this message error: C:\Documents and Settings\Facon\Escritoriog++ base64.o main.o -o prueba.exe main.o:main.cpp:(.text+0x24a): undefined reference to `Base64Encode(std::vector const&)' collect2: ld returned 1 exit status Compiler & Linker: Mingw32 3.4.5 SO: Windows XP This is my source code: base64.h: #ifndef BASE64_H #define BASE64_H #include <iostream> #include <vector> typedef unsigned char byte; std::string Base64Encode(const std::vector<byte> &array); std::vector<byte> Base64Decode(const std::string &array); #endif base64.cpp: #include "base64.h" std::string Base64Encode(std::vector<byte> &array) { const char *base64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const unsigned int size = array.size(); std::string output; for (unsigned int i = 0; (i < size); i++) { if ((size - i) > 3) { output.push_back(static_cast<char>(base64_table[array[i] >> 2])); output.push_back(static_cast<char>(base64_table[((array[i++] & 0x03) << 4) | ((array[i] & 0xF0) >> 4)])); output.push_back(static_cast<char>(base64_table[((array[i++] & 0x0F) << 2) | ((array[i] & 0xC0) >> 4)])); output.push_back(static_cast<char>(base64_table[array[i] & 0x3F])); } else if ((size - i) == 3) { output.push_back(static_cast<char>(base64_table[array[i] >> 2])); output.push_back(static_cast<char>(base64_table[((array[i++] & 0x03) << 4) | ((array[i] & 0xF0) >> 4)])); output.push_back(static_cast<char>(base64_table[(array[i] & 0x0F) << 2])); output.push_back(static_cast<char>('=')); } else if ((size - i) == 2) { output.push_back(static_cast<char>(base64_table[array[i] >> 2])); output.push_back(static_cast<char>(base64_table[(array[i] & 0x03) << 4])); output.push_back('='); output.push_back('='); } } return output; } std::vector<byte> Base64Decode(const std::string &array) // TODO { const char *base64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; } main.cpp: #include <iostream> #include <vector> #include "base64.h" using namespace std; int main(int argc, char *argv[]) { const char* prueba = "sure."; vector<byte> texto; string codificado; for (unsigned int i = 0; (prueba[i] != 0); i++) { texto.push_back(prueba[i]); } codificado = Base64Encode(texto); cout << codificado; return 0; } PD: Sorry for my bad knowledge of English :P

    Read the article

  • [C++] Adding a string or char array to a byte vector

    - by xeross
    I'm currently working on a class to create and read out packets send through the network, so far I have it working with 16bit and 8bit integers (Well unsigned but still). Now the problem is I've tried numerous ways of copying it over but somehow the _buffer got mangled, it segfaulted, or the result was wrong. I'd appreciate if someone could show me a working example. My current code can be seen below. Thanks, Xeross Main #include <iostream> #include <stdio.h> #include "Packet.h" using namespace std; int main(int argc, char** argv) { cout << "#################################" << endl; cout << "# Internal Use Only #" << endl; cout << "# Codename PACKETSTORM #" << endl; cout << "#################################" << endl; cout << endl; Packet packet = Packet(); packet.SetOpcode(0x1f4d); cout << "Current opcode is: " << packet.GetOpcode() << endl << endl; packet.add(uint8_t(5)) .add(uint16_t(4000)) .add(uint8_t(5)); for(uint8_t i=0; i<10;i++) printf("Byte %u = %x\n", i, packet._buffer[i]); printf("\nReading them out: \n1 = %u\n2 = %u\n3 = %u\n4 = %s", packet.readUint8(), packet.readUint16(), packet.readUint8()); return 0; } Packet.h #ifndef _PACKET_H_ #define _PACKET_H_ #include <iostream> #include <vector> #include <stdio.h> #include <stdint.h> #include <string.h> using namespace std; class Packet { public: Packet() : m_opcode(0), _buffer(0), _wpos(0), _rpos(0) {} Packet(uint16_t opcode) : m_opcode(opcode), _buffer(0), _wpos(0), _rpos(0) {} uint16_t GetOpcode() { return m_opcode; } void SetOpcode(uint16_t opcode) { m_opcode = opcode; } Packet& add(uint8_t value) { if(_buffer.size() < _wpos + 1) _buffer.resize(_wpos + 1); memcpy(&_buffer[_wpos], &value, 1); _wpos += 1; return *this; } Packet& add(uint16_t value) { if(_buffer.size() < _wpos + 2) _buffer.resize(_wpos + 2); memcpy(&_buffer[_wpos], &value, 2); _wpos += 2; return *this; } uint8_t readUint8() { uint8_t result = _buffer[_rpos]; _rpos += sizeof(uint8_t); return result; } uint16_t readUint16() { uint16_t result; memcpy(&result, &_buffer[_rpos], sizeof(uint16_t)); _rpos += sizeof(uint16_t); return result; } uint16_t m_opcode; std::vector<uint8_t> _buffer; protected: size_t _wpos; // Write position size_t _rpos; // Read position }; #endif // _PACKET_H_

    Read the article

  • Dynamic loaded libraries and shared global symbols

    - by phlipsy
    Since I observed some strange behavior of global variables in my dynamically loaded libraries, I wrote the following test. At first we need a statically linked library: The header test.hpp #ifndef __BASE_HPP #define __BASE_HPP #include <iostream> class test { private: int value; public: test(int value) : value(value) { std::cout << "test::test(int) : value = " << value << std::endl; } ~test() { std::cout << "test::~test() : value = " << value << std::endl; } int get_value() const { return value; } void set_value(int new_value) { value = new_value; } }; extern test global_test; #endif // __BASE_HPP and the source test.cpp #include "base.hpp" test global_test = test(1); Then I wrote a dynamically loaded library: library.cpp #include "base.hpp" extern "C" { test* get_global_test() { return &global_test; } } and a client program loading this library: client.cpp #include <iostream> #include <dlfcn.h> #include "base.hpp" typedef test* get_global_test_t(); int main() { global_test.set_value(2); // global_test from libbase.a std::cout << "client: " << global_test.get_value() << std::endl; void* handle = dlopen("./liblibrary.so", RTLD_LAZY); if (handle == NULL) { std::cout << dlerror() << std::endl; return 1; } get_global_test_t* get_global_test = NULL; void* func = dlsym(handle, "get_global_test"); if (func == NULL) { std::cout << dlerror() << std::endl; return 1; } else get_global_test = reinterpret_cast<get_global_test_t*>(func); test* t = get_global_test(); // global_test from liblibrary.so std::cout << "liblibrary.so: " << t->get_value() << std::endl; std::cout << "client: " << global_test.get_value() << std::endl; dlclose(handle); return 0; } Now I compile the statically loaded library with g++ -Wall -g -c base.cpp ar rcs libbase.a base.o the dynamically loaded library g++ -Wall -g -fPIC -shared library.cpp libbase.a -o liblibrary.so and the client g++ -Wall -g -ldl client.cpp libbase.a -o client Now I observe: The client and the dynamically loaded library possess a different version of the variable global_test. But in my project I'm using cmake. The build script looks like this: CMAKE_MINIMUM_REQUIRED(VERSION 2.6) PROJECT(globaltest) ADD_LIBRARY(base STATIC base.cpp) ADD_LIBRARY(library MODULE library.cpp) TARGET_LINK_LIBRARIES(library base) ADD_EXECUTABLE(client client.cpp) TARGET_LINK_LIBRARIES(client base dl) analyzing the created makefiles I found that cmake builds the client with g++ -Wall -g -ldl -rdynamic client.cpp libbase.a -o client This ends up in a slightly different but fatal behavior: The global_test of the client and the dynamically loaded library are the same but will be destroyed two times at the end of the program. Am I using cmake in a wrong way? Is it possible that the client and the dynamically loaded library use the same global_test but without this double destruction problem?

    Read the article

  • Segmentation fault, shared library

    - by user1306184
    I get Segmentation Fault when I try to run my program. Can someone please help me find out what Im doing wrong? Compiling with this: g++ sms_out.cpp -o sms_out g++ -c -fPIC SMSDispatch.cpp g++ -shared SMSDispatch.o -o libSMSDispatch.so It should be a shared library and dynamic linking. I get Segmentation Fault when I try to run sms_out. //sms_out.cpp #include <iostream> #include<cstdlib> #include<fstream> #include<sstream> #include<string> #include "SMSDispatch.h" using namespace std; string sms = ""; void sendSMS(string sms) { SMSDispatch* sPtr=0; sPtr->sendSMS(sms); } int main(int argc, char *argv[]) { if(argv[1]) { string input = argv[1]; string test = "--author"; if(input == test) { cout << "s149113" << endl; return 0; } } string line = ""; string file = "sms_out.txt"; ifstream myfile(file.c_str()); while(getline(myfile, line)) { string idnr, landcode, number, error; istringstream linestream(line); unsigned short errorcode; //Split the sentence getline(linestream, idnr, '\t'); getline(linestream, landcode, ':'); getline(linestream, number, '\t'); getline(linestream, error); if(idnr == "") break; //Make string to int try { errorcode = atoi(error.c_str() ); } catch (exception &) { } //Put together landcode and tlfnumber string nr = landcode + number; string txt = "Thank you for your vote!"; if(errorcode == 100) txt = "Invalid question, please try again"; else if(errorcode == 110) txt = "Sorry, only one vote pr. number"; else if(errorcode == 200) txt = "Invalid alternative, please try again"; else if(errorcode == 300) txt = "Missing a statement after other, please try again"; else if(errorcode == 999) txt = "An error occurred, please try again"; sms += "{\"ID\":" + idnr + ",\"nr\":" + nr + ",\"txt\":" + "\"" + txt + "\"" + "}\n"; } cout << sms << endl; sendSMS(sms); } //SMSDispatch.h #include <string> #ifndef SMSDISPATCH_H #define SMSDISPATCH_H using namespace std; class SMSDispatch{ public: virtual void sendSMS(string json); }; #endif //SMSDispatch.cpp #include <iostream> #include <fstream> #include "SMSDispatch.h" using namespace std; /*virtual*/void SMSDispatch::sendSMS(string json) { ofstream myfile; myfile.open ("sms_out.log"); myfile << json; myfile.close(); } int main() { }

    Read the article

  • Ambiguous constructor call

    - by Crystal
    I'm trying to create a simple date class, but I get an error on my main file that says, "call of overloaded Date() is ambiguous." I'm not sure why since I thought as long as I had different parameters for my constructor, I was ok. Here is my code: header file: #ifndef DATE_H #define DATE_H using std::string; class Date { public: static const int monthsPerYear = 12; // num of months in a yr Date(int = 1, int = 1, int = 1900); // default constructor Date(); // uses system time to create object void print() const; // print date in month/day/year format ~Date(); // provided to confirm destruction order string getMonth(int month) const; // gets month in text format private: int month; // 1 - 12 int day; // 1 - 31 int year; // any year int checkDay(int) const; }; #endif .cpp file #include <iostream> #include <iomanip> #include <string> #include <ctime> #include "Date.h" using namespace std; Date::Date() { time_t seconds = time(NULL); struct tm* t = localtime(&seconds); month = t->tm_mon; day = t->tm_mday; year = t->tm_year; } Date::Date(int mn, int dy, int yr) { if (mn > 0 && mn <= monthsPerYear) month = mn; else { month = 1; // invalid month set to 1 cout << "Invalid month (" << mn << ") set to 1.\n"; } year = yr; // could validate yr day = checkDay(dy); // validate the day // output Date object to show when its constructor is called cout << "Date object constructor for date "; print(); cout << endl; } void Date::print() const { string str; cout << month << '/' << day << '/' << year << '\n'; // new code for HW2 cout << setfill('0') << setw(3) << day; // prints in ddd cout << " " << year << '\n'; // yyyy format str = getMonth(month); // prints in month (full word), day, year cout << str << " " << day << ", " << year << '\n'; } and my main.cpp #include <iostream> #include "Date.h" using std::cout; int main() { Date date1(4, 30, 1980); date1.print(); cout << '\n'; Date date2; date2.print(); }

    Read the article

  • C++ class functions calling fortran subroutine

    - by user2863626
    Okay so I am trying to make my code work. It is a simple C++ program with a class "CArray". This class has 2 properties, the array size, and the value. I want the main C++ program to create two instances of the class CArray. In the class CArray, I have a function called "AddArray( CArray )" where it adds another array to the current array. The problem I am stuck with, is that I want the function "AddArray" to add the two arrays in fortran. I know, much more complicated, but that is what I need. I am having issues with linking the two inside the class code. #include <iostream> using namespace std; class CArray { public: CArray(); ~CArray(); int Size; int* Val; void SetSize( int ); void SetValues(); void GetArray(); extern "C" { void Add( int*, int*, int*, int*); void Subtract( int*, int*, int*, int*); void Muliply( int*, int*, int *, int* ); } void AddArray( CArray ); void SubtractArray( CArray ); void MultiplyArray( CArray ); }; Also here is the CArray function file. #include "Array.h" #include <iostream> using namespace std; CArray::CArray() { } CArray::~CArray() { } void CArray::SetSize( int s ) { Size = s; for ( int i=0; i<s; i++ ) { Val = new int[Size]; } } void CArray::SetValues() { for ( int i=0; i<Size; i++ ) { cout << "Element " << i+1 << ": "; cin >> Val[i]; } } void CArray::GetArray() { for ( int i=0; i<Size; i++ ) { cout << Val[i] << " "; } } void CArray::AddArray( CArray a ) { if ( Size == a.Size ) { Add(&Val, &a.Val); } else { cout << "Array dimensions do not agree!" << endl; } } void CArray::SubtractArray( CArray a ) { Subtract( &Val, &a, &Size, &a.Size); GetArray(); } Here is my Fortran code. module SubtractArrays use ico_c_binding implicit none contains subroutine Subtract(a,b,s1,s2) bind(c,name='Subtract') integer s1,s2 integer a(s1),b(s2) if ( s1.eq.s2 ) do i=1,s1 a(i) = a(i) - b(i) end return end end If someone could just help me with setting me up to send arrays of integers from C++ classes to fortran I would greatly appreciate it! Thank you, Josh Derrick

    Read the article

  • using cin and cout in textmate [migrated]

    - by That Guy
    I am usually a Java programmer, and have used textmate for that almost exclusively, but lately I started using C++ with it. but when i use even the most basic programs and incorporate the cin keyword, and run the program, I dont get an oppurtunity to put in anything during runtime and sometimes it inserts random values by itself! for example, if i ran this in textmate: #include <iostream> int stonetolb(int); int main() { using namespace std; int stone; cout << "enter the weight in stone"; cin >> stone; int pounds = stonetolb(stone); cout << stone << "stone = "; cout << pounds <<" pounds."; return 0; } int stonetolb(int sts) { return 14 * sts; } I would come out with the output: enter the weight in stone32767stone = 458738 pounds. Why is this happening, and how do I stop it?

    Read the article

  • Issue porting Cocos2d-x to Android

    - by Anil
    I've written a basic game using Cocos2D-x on XCode. It works fine on the iPhone. Now I'm trying to port it to Android. When I run the script ./build_native.sh inside the proj.android folder, it gives me the following error: jni/../../Classes/MemoryModeLayer.cpp: In member function 'void MemoryModeLayer::startNewGame()': jni/../../Classes/MemoryModeLayer.cpp:109:25: error: 'time' is not a member of 'std' jni/../../Classes/MemoryModeLayer.cpp:109:25: note: suggested alternative: /Users/abc/android-ndk-r9d/platforms/android-8/arch-arm/usr/include/time.h:40:17: note: 'time' jni/../../Classes/MemoryModeLayer.cpp:111:5: error: 'random_shuffle' is not a member of 'std' jni/../../Classes/MemoryModeLayer.cpp:112:5: error: 'random_shuffle' is not a member of 'std' make: *** [obj/local/armeabi/objs/cocos2dcpp_shared/__/__/Classes/MemoryModeLayer.o] Error 1 make: Leaving directory `/Users/abc/cocos2d-x-2.2.3/projects/Game/proj.android' In MemoryModeLayer.cpp I have the following: std::srand(unsigned(std::time(0))); std::random_shuffle(_xCod, _xCod + _numberOfRows); std::random_shuffle(_yCod, _yCod + _numberOfColumns); I've included the following headers as well: #include <string> #include <ctime> #include <algorithm> #include <iostream> #include <iomanip> Also added using namespace std in the header file. Is there anything else that I should do?

    Read the article

  • Allocating memory inside a function and returning it back

    - by user2651062
    I want to pass a pointer to my function and allocate the memory to which this pointer points. I've read in other posts that I should pass a double pointer to this function and I did so, but I keep getting segmentation fault: #include <iostream> #include <stdlib.h> using namespace std; void allocate(unsigned char** t) { *t=(unsigned char*)malloc(3*sizeof(unsigned char)); if(*t == NULL) cout<<"Allcoation failed"<<endl; else for(int m=0;m<3;m++) *(t[m])=0; } int main() { unsigned char* t; allocate(&t); cout<<t[0]<<" "<<t[1]<<endl; return 0; } the result is always this: Segmentation fault (core dumped) I don't think that there's anything missing from this code. What could be wrong?

    Read the article

  • Why can't I create direct3d objects?

    - by quakkels
    I've been programming professionally for years using languages like VBScript, JavaScript, and C#. As a hobby, I'm getting into some c/c++ and games programming with DirectX. I am running into an issue where I cannot create direct3d objects. I am using Visual C++ 2010 Express. After I installed vc++2010express I then installed the June 2010 release of DirectX. I am trying to include DirectX via #pragma statements. This is the code I have so far in my winmain.cpp source file: #include <Windows.h> #include <d3d11.h> #include <time.h> #include <iostream> using namespace std; #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "d3dx11.lib") // program settings const string AppTitle = "Direct3D in a Window"; const int ScreenWidth = 1024; const int ScreenHeight = 768; // direct3d objects LPDIRECT3D11 d3d = NULL; // this line is showing an error The type LPDIRECT3D11 is showing an error: Error: Identifier "LPDIRECT3D11" is undefined Am I missing something here to get VC++2010Express to recognize and load the DirectX libs? Thanks for any help.

    Read the article

  • Program instantly closing [migrated]

    - by Ben Clayton
    I made this program and when I compiled it there were no errors but the program just instantly closed, any answers would be appreciated. #include <iostream> //Main commands #include <string> // String commands #include <windows.h> // Sleep using namespace std; int main () { //Declaring variables float a; bool end; std::string input; end = false; // Making sure program doesn't end instantly cout << "Enter start then the number you want to count down from." << ".\n"; while (end = false){ cin >> input; cout << ".\n"; if (input.find("end") != std::string::npos) // Ends the program if user types end end = true; else if (input.find("start" || /* || is or operator*/ "restart") != std::string::npos) // Sets up the countdown timer if the user types start { cin >> a; cout << ".\n"; while (a>0){ Sleep(100); a = a - 0.1; cout << a << ".\n"; } cout << "Finished! Enter restart and then another number, or enter end to close the program" << ".\n"; } else // Tells user to start program cout << "Enter start"; } return 0; // Ends program when (end = true) }

    Read the article

  • The best way to have a pointer to several methods - critique requested

    - by user827992
    I'm starting with a short introduction of what i know from the C language: a pointer is a type that stores an adress or a NULL the * operator reads the left value of the variable on its right and use this value as address and reads the value of the variable at that address the & operator generate a pointer to the variable on its right so i was thinking that in C++ the pointers can work this way too, but i was wrong, to generate a pointer to a static method i have to do this: #include <iostream> class Foo{ public: static void dummy(void){ std::cout << "I'm dummy" << std::endl; }; }; int main(){ void (*p)(); p = Foo::dummy; // step 1 p(); p = &(Foo::dummy); // step 2 p(); p = Foo; // step 3 p->dummy(); return(0); } now i have several questions: why step 1 works why step 2 works too, looks like a "pointer to pointer" for p to me, very different from step 1 why step 3 is the only one that doesn't work and is the only one that makes some sort of sense to me, honestly how can i write an array of pointers or a pointer to pointers structure to store methods ( static or non-static from real objects ) what is the best syntax and coding style for generating a pointer to a method?

    Read the article

  • Weird behavior when using pointers [migrated]

    - by Kinan Al Sarmini
    When I run this code on MS VS C++ 2010: #include <iostream> int main() { const int a = 10; const int *b = &a; int *c = (int *)b; *c = 10000; std::cout << c << " " << &a << std::endl; std::cout << *c << " " << a << " " << *(&a) << std::endl; return 0; } The output is: 0037F784 0037F784 10000 10 10 The motivation for writing that code was this sentence from "The C++ Programming Language" by Stroustrup: "It is possible to explicitly remove the restrictions on a pointer to const by explicit type conversion". I know that trying to modify a constant is conceptually wrong, but I find this result quite weird. Can anyone explain the reason behind it?

    Read the article

  • Writing a program in C++ and I need help [migrated]

    - by compscinoob
    So I am a new to this. I am trying to write a program with a function double_product(vector< double a, vector< double b) that computes the scalar product of two vectors. The scalar product is $a_{0}b_{0}+a_{1}b_{1}+...a_{n-1}b_{n-1}$. Here is what I have. It is a mess, but I am trying! #include<iostream> #include<vector> using namespace std; class Scalar_product { public: Scalar_product(vector<double> a, vector<bouble> b); }; double scalar_product(vector<double> a, vector<double> b) { double product = 0; for (int i=0; i <=a.size()-1; i++) for (int i=0; i <=b.size()-1; i++) product = product + (a[i])*(b[i]); return product; } int main() { cout << product << endl; return 0; }

    Read the article

  • C++ function templates, function name confusion. This is funny [migrated]

    - by nashmaniac
    Alright so heres the program and works absolutely right #include <iostream> using namespace std; template <typename T> void Swap(T &a , T &b); int main(){ int i = 10; int j = 20; cout<<"i, j = " << i <<" , " <<j<<endl; Swap(i,j); cout<<"i, j = " << i <<" , " <<j<<endl; } template <typename T> void Swap(T &a , T &b){ T temp; temp = a ; a = b; b= temp; } but when I change the function's name from Swap to swap it generates an error saying error: call of overloaded 'swap(int&, int&)' is ambiguous| note: candidates are: void swap(T&, T&) [with T = int]| ||=== Build finished: 1 errors, 0 warnings ===| what happened is it a rule to start functions using templates to start with a capital letter ?

    Read the article

  • 7 drived classes with one common base class

    - by user144905
    i have written the following code, //main.cpp #include<iostream> #include<string> #include"human.h" #include"computer.h" #include"referee.h" #include"RandomComputer.h" #include"Avalanche.h" #include"Bureaucrat.h" #include"Toolbox.h" #include"Crescendo.h" #include"PaperDoll.h" #include"FistfullODollors.h" using namespace std; int main() { Avalanche pla1; Avalanche pla2; referee f; pla1.disp(); for (int i=0;i<5;i++) { cout<<pla2.mov[i]; } return 0; } in this program all included classes except referee.h and human.h are drived from computer.h. each drived calls has a char array variable which is initialized when a member of a drived class is declared. the problem is that when i declare tow diffrent drived class memebers lets say Avalache and ToolBox. upon printing the char array for one of them using for loop it prints nothing. However if i declare only one of them in main.cpp the it works properly. and the file for computer.h is as such: #ifndef COMPUTER_H #define COMPUTER_H class computer { public: int nump; char mov[]; void disp(); }; #endif ToolBox.h is like this: #ifndef TOOLBOX_H #define TOOLBOX_H #include"computer.h" class Toolbox: public computer { public: Toolbox(); }; #endif finally Avalanche.h is as following: #ifndef AVALANCHE_H #define AVALANCHE_H #include"computer.h" class Avalanche: public computer { public: Avalanche(); }; #endif

    Read the article

  • Do Loops kind of Reset every time you go through it?... [closed]

    - by JacKeown
    #include <iostream> using namespace std; int main (void) { cout << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl << "" << endl; for (int c = 1; c < 10; c++) { cout << c << "| "; for (int i = 1; i < 10; i++) { cout << i * c << '\t'; } cout << endl; } return 0; } Hey so this code produces a times table...I found it on Google Code's C++ class online...I'm confused about why "i" in the second for loop resets to 1 every time you go through that loop...or is it being declared again in the first parameter? Thanks in advance!

    Read the article

  • I’m new to C++ and unsure about how to improve this code [migrated]

    - by Laian Alsabbagh
    The purpose of the following code is to get a random number of 100 nodes and to distribute these nodes randomly in range 500*500 …(X,Y).. this was the first step #include<iostream> #include <fstream> #include<cmath> using namespace std; int main() { const int x = 0, y = 1; int nodes[100][2]; ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; for (int i=0; i<100 ;i++) { nodes[i][x] = rand() % 501; nodes[i][y] = rand() % 501; myfile <<nodes[i][x]<<" "<<nodes[i][y]; } myfile.close(); } now the next step is to improve this code to distribute these nodes in order ( "Imust divide both xy_coordinates as : x= 0-100-200-300-400-500 & y=0-100-200-300-400-500) next is to distribute the nodes (regardless number of nodes) in order range Starting from (0,100 )….(100,100)..(100,200)…….untile i reach the last point (500,500),, ") I’m really confused of how to do it correctly I start to think to define 2 dimensional array , and then to define 2 for loops enter code here Int no_nodes=100; Int XY_coordinate [500][500]; For (int i=0;i<no_nodes; i++) { For (int j=0;j<no_nodes; j++)

    Read the article

  • Google Code C++ [closed]

    - by JacKeown
    I was on this website: http://code.google.com/edu/languages/cpp/basics/getting-started.html#learn-by-example and I saw this code: // Description: Illustrate the use of cin to get input // and how to recover from errors. #include <iostream> using namespace std; int main() { int input_var = 0; // Enter the do while loop and stay there until either // a non-numeric is entered, or -1 is entered. Note that // cin will accept any integer, 4, 40, 400, etc. do { cout << "Enter a number (-1 = quit): "; // The following line accepts input from the keyboard into // variable input_var. // cin returns false if an input operation fails, that is, if // something other than an int (the type of input_var) is entered. if (!(cin >> input_var)) { cout << "Please enter numbers only." << endl; cin.clear(); cin.ignore(10000,'\n'); } if (input_var != -1) { cout << "You entered " << input_var << endl; } } while (input_var != -1); cout << "All done." << endl; return 0; } I was wondering... what is the significance of cin.clear() and cin.ignore() ...and also why the 10000 and /n parameters are necessary...?...

    Read the article

  • Binary Search Tree Implementation

    - by Gabe
    I've searched the forum, and tried to implement the code in the threads I found. But I've been working on this real simple program since about 10am, and can't solve the seg. faults for the life of me. Any ideas on what I'm doing wrong would be greatly appreciated. BST.h (All the implementation problems should be in here.) #ifndef BST_H_ #define BST_H_ #include <stdexcept> #include <iostream> #include "btnode.h" using namespace std; /* A class to represent a templated binary search tree. */ template <typename T> class BST { private: //pointer to the root node in the tree BTNode<T>* root; public: //default constructor to make an empty tree BST(); /* You have to document these 4 functions */ void insert(T value); bool search(const T& value) const; bool search(BTNode<T>* node, const T& value) const; void printInOrder() const; void remove(const T& value); //function to print out a visual representation //of the tree (not just print the tree's values //on a single line) void print() const; private: //recursive helper function for "print()" void print(BTNode<T>* node,int depth) const; }; /* Default constructor to make an empty tree */ template <typename T> BST<T>::BST() { root = NULL; } template <typename T> void BST<T>::insert(T value) { BTNode<T>* newNode = new BTNode<T>(value); cout << newNode->data; if(root == NULL) { root = newNode; return; } BTNode<T>* current = new BTNode<T>(NULL); current = root; current->data = root->data; while(true) { if(current->left == NULL && current->right == NULL) break; if(current->right != NULL && current->left != NULL) { if(newNode->data > current->data) current = current->right; else if(newNode->data < current->data) current = current->left; } else if(current->right != NULL && current->left == NULL) { if(newNode->data < current->data) break; else if(newNode->data > current->data) current = current->right; } else if(current->right == NULL && current->left != NULL) { if(newNode->data > current->data) break; else if(newNode->data < current->data) current = current->left; } } if(current->data > newNode->data) current->left = newNode; else current->right = newNode; return; } //public helper function template <typename T> bool BST<T>::search(const T& value) const { return(search(root,value)); //start at the root } //recursive function template <typename T> bool BST<T>::search(BTNode<T>* node, const T& value) const { if(node == NULL || node->data == value) return(node != NULL); //found or couldn't find value else if(value < node->data) return search(node->left,value); //search left subtree else return search(node->right,value); //search right subtree } template <typename T> void BST<T>::printInOrder() const { //print out the value's in the tree in order // //You may need to use this function as a helper //and create a second recursive function //(see "print()" for an example) } template <typename T> void BST<T>::remove(const T& value) { if(root == NULL) { cout << "Tree is empty. No removal. "<<endl; return; } if(!search(value)) { cout << "Value is not in the tree. No removal." << endl; return; } BTNode<T>* current; BTNode<T>* parent; current = root; parent->left = NULL; parent->right = NULL; cout << root->left << "LEFT " << root->right << "RIGHT " << endl; cout << root->data << " ROOT" << endl; cout << current->data << "CURRENT BEFORE" << endl; while(current != NULL) { cout << "INTkhkjhbljkhblkjhlk " << endl; if(current->data == value) break; else if(value > current->data) { parent = current; current = current->right; } else { parent = current; current = current->left; } } cout << current->data << "CURRENT AFTER" << endl; // 3 cases : //We're looking at a leaf node if(current->left == NULL && current->right == NULL) // It's a leaf { if(parent->left == current) parent->left = NULL; else parent->right = NULL; delete current; cout << "The value " << value << " was removed." << endl; return; } // Node with single child if((current->left == NULL && current->right != NULL) || (current->left != NULL && current->right == NULL)) { if(current->left == NULL && current->right != NULL) { if(parent->left == current) { parent->left = current->right; cout << "The value " << value << " was removed." << endl; delete current; } else { parent->right = current->right; cout << "The value " << value << " was removed." << endl; delete current; } } else // left child present, no right child { if(parent->left == current) { parent->left = current->left; cout << "The value " << value << " was removed." << endl; delete current; } else { parent->right = current->left; cout << "The value " << value << " was removed." << endl; delete current; } } return; } //Node with 2 children - Replace node with smallest value in right subtree. if (current->left != NULL && current->right != NULL) { BTNode<T>* check; check = current->right; if((check->left == NULL) && (check->right == NULL)) { current = check; delete check; current->right = NULL; cout << "The value " << value << " was removed." << endl; } else // right child has children { //if the node's right child has a left child; Move all the way down left to locate smallest element if((current->right)->left != NULL) { BTNode<T>* leftCurrent; BTNode<T>* leftParent; leftParent = current->right; leftCurrent = (current->right)->left; while(leftCurrent->left != NULL) { leftParent = leftCurrent; leftCurrent = leftCurrent->left; } current->data = leftCurrent->data; delete leftCurrent; leftParent->left = NULL; cout << "The value " << value << " was removed." << endl; } else { BTNode<T>* temp; temp = current->right; current->data = temp->data; current->right = temp->right; delete temp; cout << "The value " << value << " was removed." << endl; } } return; } } /* Print out the values in the tree and their relationships visually. Sample output: 22 18 15 10 9 5 3 1 */ template <typename T> void BST<T>::print() const { print(root,0); } template <typename T> void BST<T>::print(BTNode<T>* node,int depth) const { if(node == NULL) { std::cout << std::endl; return; } print(node->right,depth+1); for(int i=0; i < depth; i++) { std::cout << "\t"; } std::cout << node->data << std::endl; print(node->left,depth+1); } #endif main.cpp #include "bst.h" #include <iostream> using namespace std; int main() { BST<int> tree; cout << endl << "LAB #13 - BINARY SEARCH TREE PROGRAM" << endl; cout << "----------------------------------------------------------" << endl; // Insert. cout << endl << "INSERT TESTS" << endl; // No duplicates allowed. tree.insert(0); tree.insert(5); tree.insert(15); tree.insert(25); tree.insert(20); // Search. cout << endl << "SEARCH TESTS" << endl; int x = 0; int y = 1; if(tree.search(x)) cout << "The value " << x << " is on the tree." << endl; else cout << "The value " << x << " is NOT on the tree." << endl; if(tree.search(y)) cout << "The value " << y << " is on the tree." << endl; else cout << "The value " << y << " is NOT on the tree." << endl; // Removal. cout << endl << "REMOVAL TESTS" << endl; tree.remove(0); tree.remove(1); tree.remove(20); // Print. cout << endl << "PRINTED DIAGRAM OF BINARY SEARCH TREE" << endl; cout << "----------------------------------------------------------" << endl; tree.print(); cout << endl << "Program terminated. Goodbye." << endl << endl; } BTNode.h #ifndef BTNODE_H_ #define BTNODE_H_ #include <iostream> /* A class to represent a node in a binary search tree. */ template <typename T> class BTNode { public: //constructor BTNode(T d); //the node's data value T data; //pointer to the node's left child BTNode<T>* left; //pointer to the node's right child BTNode<T>* right; }; /* Simple constructor. Sets the data value of the BTNode to "d" and defaults its left and right child pointers to NULL. */ template <typename T> BTNode<T>::BTNode(T d) : left(NULL), right(NULL) { data = d; } #endif Thanks.

    Read the article

  • GetUserDefaultLocaleName() API is crashing

    - by Santhosha
    I have one application which reads user default locale in Windows Vista and above. When i tried calling the API for getting User default Locale API is crashing. Below is the code, It will be helpfull if any points the reason #include <iostream> #include <WinNls.h> #include <Windows.h> int main() { LPWSTR lpLocaleName=NULL; cout << "Calling GetUserDefaultLocaleName"; int ret = GetUserDefaultLocaleName(lpLocaleName, LOCALE_NAME_MAX_LENGTH); cout << lpLocaleName<<endl; }

    Read the article

  • 1>Project : error PRJ0003 : Error spawning 'rc.exe'.

    - by user320950
    1Project : error PRJ0003 : Error spawning 'rc.exe'.. this is the error i get when i try to run this small practice program of reading and writing files which i cant do because of the reason of me not being able to get the files to open correctly. i use microsoft visual c++ 2008 and i have used the file path to try to open the file as well and i cant can someone help? #include <iostream> #include <fstream> using namespace std; int main () { ifstream infile; ofstream myfile; infile.open("ex.txt"); myfile.open ("example.txt"); myfile.close(); return 0; }

    Read the article

  • Cygwin socket & thread & other programming issues (some question about Cygwin)

    - by SjB
    I have some question about cygwin : Can I use Cygwin develop socket based code? Does Cygwin have read() and write() functions that work with file descriptors? Can I use Pthread library in Cygwin? Does code that compiles in Cygwin also compile in Linux without any change or with little change? Will an executable file that built by Cygwin run in Linux ? Why does Cygwin not need the linker option -lpthread when I use pthread library? why in #include <iostream> don't I need to use using namespace std; ? Can I work with QT in Cygwin? If so, How?

    Read the article

  • Why callback functions needs to be static when declared in class

    - by Dave17
    I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why? #include <iostream> using std::cout; using std::endl; class Test { public: Test() {} void my_func(void (*f)()) { cout << "In My Function" << endl; f(); //Invoke callback function } static void callback_func() {cout << "In Callback function" << endl;} }; int main() { Test Obj; Obj.my_func(t.callback_func); }

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >