How can i pass a file as a parameter in C++? - c++

I want to do is basically writing a function which takes a parameter as a file name and if have multiple files, it will just take file name as a parameter and it should do this repetitively with a function. How can i do this?
Thanks.
Txt files are like this
for example, sorular.txt:
//What is the most crowded country in the world?
//China
//USA
//Germany
//Australia
//China
int main (){
string array [5];
string line;
string answer;
static int trueCount = 0;
static int falseCount = 0;
ifstream file("/Users/User/QuizMaker/Quiz Maker V2/sorular.txt");
if(file.is_open()){
cout << "Questions are loading... Please wait.."<<endl<<" ."<<endl<<" ."<<endl<<" ."<<endl;
while (!file.eof()) {
for (int i = 0; i<6; i++) {
getline(file,array[i]);
}
for (int a = 0; a<5; a++) {
cout << array[a] << endl;
}
cin >> answer;
if(answer == "C" || answer == "c") {
cout << true;
trueCount++;
}
else falseCount++;
}
cout << "You answered "<<trueCount << " questions as true" << endl;
cout << "You answered "<<falseCount << " questions as false" << endl;
file.close();
} else cout << " not ıoen";
cin.get();
return 0;
}

First let me say, that array cannot hold elements 0, 1, 2, 3, 4, and 5. It has only allocated 5 elements.
This may stretch your horizons a bit, but I think the right solution is a class here. So i'm going to hack this together, if you're interested you can research what I've done a bit and if you don't understand something feel free to ask in a comment.
class foo : public iterator<input_iterator_tag, string> {
const initializer_list<const char*> _files;
decltype(_files)::const_iterator _filesIt;
ifstream _file;
string _line;
void get() {
string array[6];
auto i = begin(array);
while (i != end(array) && getline(_file, *i)) {
advance(i, 1);
}
if (i == end(array)) {
_line = accumulate(cbegin(array), cend(array), string(), [](const auto& a, const auto& b) { return a.empty() ? b : a + '\n' + b; });
} else if(++_filesIt != cend(_files)) {
_file.close();
_file.open(*_filesIt);
get();
}
}
public:
foo() : _filesIt(cend(_files)) {}
foo(foo& rhs) : _files(rhs._files), _filesIt(next(cbegin(_files), distance(cbegin(rhs._files), rhs._filesIt))), _line(rhs._line) {
if (_filesIt != cend(_files)) {
_file.open(*_filesIt);
_file.seekg(rhs._file.tellg());
}
}
foo(const initializer_list<const char*>&& files) : _files(files), _filesIt(cbegin(_files)), _file(*_filesIt) { get(); }
const string& operator*() const { return _line; }
const foo& operator++() {
get();
return *this;
}
const foo operator++(int) {
foo result;
get();
return result;
}
bool operator==(const foo& rhs) { return distance(_filesIt, cend(_files)) == distance(rhs._filesIt, cend(rhs._files)); }
bool operator!=(const foo& rhs) { return distance(_filesIt, cend(_files)) != distance(rhs._filesIt, cend(rhs._files)); }
};
Though this class may seem overwhelming it greatly simplifies the rest of what you're trying to acompilsh. With this class the rest of your code will read:
auto true_count = 0;
auto false_count = 0;
for_each(foo({"/Users/User/QuizMaker/Quiz Maker V2/sorular.txt", "foo.txt", "bar.txt"}), foo(), [&](const auto& i) {
string answer;
cout << i << endl;
cin >> answer;
if(answer == "C" || answer == "c") {
cout << 1;
true_count++;
} else {
false_count++;
}
});
cout << "You answered "<< trueCount << " questions as true" << endl << "You answered " << falseCount << " questions as false" << endl;

Related

Saving vector of objects using SDL2

Im learning SDL2 and now im trying to save a game ranking into a .bin file. I have placed the ranking data into a vector. But im unable to save the data. Perhabs it has to do with file size, but im unable to solve that. This is the code that im using now:
class Player {
private:
std::string name, faction, dific;
int points;
public:
Player() {};
virtual ~Player() {};
void addName(std::string s);
void addFacti(std::string s);
void addDific(std::string s);
void addPoint(int p);
std::string getName() const;
std::string getFacti() const;
std::string getDific() const;
int getPoint() const;
bool operator>(const Player& p) const;
};
Player p1; Player p2;//just two examples
//add properties to each object
std::vector<Player>classi;
classi.push_back(p1); classi.push_back(p2);
std::sort(classi.begin(), classi.end(), std::greater<Player>());
//load file
SDL_RWops* rankfile = SDL_RWFromFile("ranking.bin", "r+b");
for (int i = 0; i < classi.size(); ++i) { SDL_RWread(rankfile, &classi[i], sizeof(Player), 1); }
SDL_RWclose(rankfile);
//im able to render the objects
//save file - but it doesnt save anything
rankfile = SDL_RWFromFile("ranking.bin", "w+b");
for (int i = 0; i < classi.size(); ++i) { SDL_RWwrite(rankfile, &classi[i], sizeof(Player), 1); }
SDL_RWclose(rankfile);
Here's an example of how I might serialize a struct containing std::string to/from binary. It doesn't use the SDL functions because I don't use SDL but it wouldn't be difficult to modify if desired.
You may have a different problem since you say your file is empty, and I am concerned that you try and read the file before you write it, but you could try something like this and see if it helps.
#include <iostream>
#include <string>
#include <fstream>
#include <tuple>
template <typename T>
std::ostream &writeBinary(std::ostream &f, T data)
{
return f.write(reinterpret_cast<char *>(&data), sizeof(data));
}
std::ostream &writeBinary(std::ostream &f, const std::string &str)
{
// If file size is a concern you might use a smaller type like uint16_t.
// Just make sure to mirror the change in readBinary.
std::string::size_type sz = str.size();
if (f)
{
f.write(reinterpret_cast<char *>(&sz), sizeof(sz));
}
if (f)
{
f.write(str.data(), str.size());
}
return f;
}
template <typename T>
std::istream &readBinary(std::istream &f, T &data)
{
if (f)
{
f.read(reinterpret_cast<char *>(&data), sizeof(data));
}
return f;
}
std::istream &readBinary(std::istream &f, std::string &str)
{
std::string::size_type sz = 0;
if (f)
{
f.read(reinterpret_cast<char *>(&sz), sizeof(sz));
}
if (f)
{
str.resize(sz);
f.read(str.data(), sz);
}
return f;
}
struct Thing
{
std::string shortString;
int i;
double d;
std::string longString;
Thing()
: i(99)
, d(99.99)
{ }
bool operator==(const Thing &rhs) const
{
return std::tie(shortString, i, d, longString)
== std::tie(rhs.shortString, rhs.i, rhs.d, rhs.longString);
}
bool write(std::ofstream &f)
{
if (!writeBinary(f, shortString))
{
return false;
}
if (!writeBinary(f, i))
{
return false;
}
if (!writeBinary(f, d))
{
return false;
}
if (!writeBinary(f, longString))
{
return false;
}
return true;
}
bool read(std::ifstream &f)
{
if (!readBinary(f, shortString))
{
return false;
}
if (!readBinary(f, i))
{
return false;
}
if (!readBinary(f, d))
{
return false;
}
if (!readBinary(f, longString))
{
return false;
}
return true;
}
};
std::ostream &operator<<(std::ostream &o, const Thing &t)
{
return o << "'" << t.shortString << "'" << ", "
<< t.i << ", " << t.d << ", "
<< "'" << t.longString << "'";
}
int main()
{
Thing t1;
// Shorter string to hopefully fit in any short string optimization buffer in the string.
t1.shortString = "Short";
t1.longString = "Long string that should be long enough to not fit in the SSO buffer.";
t1.i = 42;
t1.d = 42.42;
std::cout << "t1 Before Write: " << t1 << "\n";
std::ofstream out("thing.bin", std::ios::binary);
if (!t1.write(out))
{
std::cout << "Error writing t1!\n";
return -1;
}
out.close();
std::cout << "t1 After Write: " << t1 << "\n";
Thing t2;
std::cout << "t2 Before Read: " << t2 << "\n";
std::ifstream in("thing.bin", std::ios::binary);
if (!t2.read(in))
{
std::cout << "Error reading t2!\n";
return -1;
}
in.close();
std::cout << "t2 After Read: " << t2 << "\n";
std::cout << "t1 == t2: " << std::boolalpha << (t1 == t2) << "\n";
return 0;
}

abnormal behaviour while displaying char array in C++ after object initialization

main():
char inp[] = "(A+B)/(C*D))";
Infix i;
cout << "In main: " << inp /* + ')' */ << endl << endl;
Here is Infix constructor:
Infix() {
push('(');
cout << "Element In Stack: " << *returnElement(returnTop()) << endl;
outputString = "";
strcpy(operatorArray, "/*-+%");
cout << "Operator Array: " << operatorArray << endl;
}
Infix is inheriting from a class 'Stack':
class Stack{
int top = -1;
char arr[100];
public:
bool push(char);
char pop();
char peek();
bool isEmpty();
void displayAll();
char returnTop() { return top;}
char* returnElement(int i) {
if(i > 98){
cout << "StackOutOfIndex";
return nullptr;
}
return &arr[i];
}
};
When I run the code in main, it displays unusual output:
Element In Stack: (
Operator Array: /*-+%
In main: +%
Stack Object Destroyed!
But, when in main, if the comment the line declaring 'Infix' object declaration, the code runs fine:
In main: (A+B)/(C*D))
EDITS:
Stack Class
#include<iostream>
using namespace std;
class Stack{
int top = -1;
char arr[100];
public:
bool push(char);
char pop();
char peek();
bool isEmpty();
void displayAll();
char returnTop() { return top;}
char* returnElement(int i) {
if(i > 98){
cout << "StackOutOfIndex";
return nullptr;
}
return &arr[i];
}
};
bool Stack:: push(char elementToPush) {
if(top > 98) {
cout << "\nStack Overflow!!";
return false;
} else {
arr[++top] = elementToPush;
return true;
}
}
char Stack:: pop() {
if(top <= -1) {
cout << "\nStack Underflow!!";
return ' ';
} else {
return (arr[top--]);
}
}
char Stack:: peek() {
if(top > 98) {
cout << "\nStack Overflow!!";
return ' ';
} else {
return arr[top];
}
}
bool Stack:: isEmpty() {
return (top <= 0);
}
void Stack:: displayAll() {
if(top <= -1) {
cout << "null";
return;
}
int i = top;
while (i >= 0) {
cout << arr[i] << " ";
--i;
}
cout << "\n";
}
Infix Class
#include<iostream>
#include<cstring>
#include<D:\Programs\11Stack.cpp>
using namespace std;
class Infix : public Stack {
string outputString;
char operatorArray[];
public:
Infix() {
push('(');
cout << "Element In Stack: " << *returnElement(returnTop()) << endl;
outputString = "";
strcpy(operatorArray, "/*-+%");
cout << "Operator Array: " << operatorArray << endl;
}
string infixToPostfix(char *, int);
bool manupulateOperator(char, int);
int checkPrecedence(char);
~Infix() {
cout << "\nStack Object Destroyed!" << endl;
}
};
string Infix:: infixToPostfix(char *str, int size) {
cout << "\nGiven String: " << str << endl;
int x;
for(int i = 0; i < size; ++size) {
x = str[i];
if(x != ' ') {
if(x == ')') {
while(returnTop() != '(') {
cout << pop() << " popped!\n";
}
cout << pop() << " popped!\n";
} else if(isalpha(x)) {
cout << x;
} /* else{ // scanned character is an operator
if(manupulateOperator(x, i)) {
} else {
return " ";
}
} */
}
}
return outputString;
}
bool Infix::manupulateOperator(char c, int position) {
try {
char topElement = *returnElement(returnTop());
if(checkPrecedence(c) == -1) {
cout << "\nErr\n";
}else if((checkPrecedence(c) > checkPrecedence(topElement)) || returnTop() == 0) {
push(c);
cout << c << " pushed!\n";
}
} catch(std::exception e) {
std::cerr << e.what() << '\n';
return false;
} catch (char* Ce) {
cout << Ce << endl;
}
return true;
}
int Infix::checkPrecedence(char c) {
/*
+ -> 1
- -> 1
* -> 2
/ -> 2
% -> 2
*/
switch(c) {
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '%':
return 2;
default:
// throw "Illegal Operator Detected!";
cout << "Illegal Operator Detected: " << c << endl;
return -1;
}
}
int main() {
cout << endl;
int x = 1;
char inp[] = "(A+B)/(C*D))";
//Infix i;
cout << "In main: " << inp /* + ')' */ << endl << endl;
// cout << i.infixToPostfix(input + ')', sizeof(input));
/* for(int i = 0; i < strlen(inp); ++i) {
cout << inp[i];
}
*/
return 0;
}
You are declaring operatorArray as an array of char but you are not assigning any memory for it! So, when you then call strcpy(operatorArray, "/*-+%"); in your Infix constructor, you are causing undefined behaviour by attempting to copy the given string constant to memory that hasn't been assigned - and this appears to be overwriting the inp[] array declared in your main.
To fix this, I would suggest giving your operatorArray member a specific size, which will be large enough to accommodate whatever string you want to copy to it - 8 characters will work in the sample code you've given:
class Infix : public Stack {
string outputString;
char operatorArray[8]; // Make this member a REAL array of characters.
//..
Your variable char operatorArray[] have no memory allocated when your constructor is called. When you use strcpy, you write to a place where you don't have permissions in your memory, and therefore on other informations.
To find these kinds of mistakes, I recommend using valgrind.
char operatorArray[]; is not allowed in Standard C++.
If you didn't see an error message then I would recommend adjusting compiler settings to follow the standard form of the language, this would have saved you a lot of time.

Homework task: Checking the equality of two arrays

I am stuck on a homework question which requires me to create/modify a function which will set two arrays equal to each other. The question asks:
"Use the copy assignment (=) operator to set the two arrays equal to each other, this can be checked with the following:
y = x;
cout << "x equals y? " << (x == y) << endl; //Should return "True"
And is set within the following rules:
"Note that two Array objects should be considered equal only if they have the same length and the same element values."
This is the code I have, I have implemented two debugging sections which shows that they are indeed equal both in the assignment function and the main function, so my best guess is that the lengths don't match up. I am not allowed to modify any of the code which was provided (All the class and function stuff, or anything above the debugger in main), so I'm not sure how to set the lengths equal to each other in order to satisfy the condition (x==y)
#include <iostream>
using namespace std;
// definition
#define MAX_LENGTH 100
#define INIT_VALUE 0
class Array {
public:
Array(int length);
Array& operator=(const Array& other);
int length() const;
int& operator[](int index);
bool operator==(const Array& other) const;
bool operator!=(const Array& other) const;
private:
int length_;
int elements_[MAX_LENGTH];
};
// implementation
Array::Array(int length) {
length_ = length;
if (length_ > MAX_LENGTH) length_ = MAX_LENGTH;
for (int i = 0; i < length_; ++i) {
elements_[i] = INIT_VALUE;
}
}
Array& Array::operator=(const Array& other)
{
/*DEBUG*/cout << endl << endl << "<<NOW IN ASSIGNMENT FUNCTION>>" << endl << endl;
for (int i = 0; i < other.length_; ++i)
{
elements_[i] = other.elements_[i];
/*DEBUG*/cout << endl << "Elements: " << elements_[i] << " | Other Elements: " << other.elements_[i] << endl;
}
return *this;
}
int Array::length() const {
return length_;
}
int& Array::operator[](int index) {
// Q3 code goes here
return elements_[index];
}
bool Array::operator==(const Array& other) const
{
if (length_ != other.length_) return false;
for (int i = 0; i < other.length_; ++i) {
if (elements_[i] != other.elements_[i]) return false;
}
return true;
}
bool Array::operator!=(const Array& other) const
{
if (length_ != other.length_)
{
return true;
}
for (int j = 0; j < other.length_; ++j)
{
if (elements_[j] != other.elements_[j]) return true;
}
return false;
}
// testing
int main()
{
Array x(10);
x[3] = 42;
cout << "x contains ";
for (int i = 0; i < x.length(); ++i) {
cout << x[i] << " ";
}
cout << endl;
Array y(5);
cout << boolalpha;
cout << "x equals y? " << (x == y) << endl;
cout << "x notequals y? " << (x != y) << endl;
y = x;
//DEBUG SECTION
cout << endl << endl << "<<NOW IN MAIN>>" << endl << endl;
for (int i = 0; i < x.length(); ++i)
{
cout << endl << "Elements: " << x[i] << " | Other Elements: " << y[i] << endl;
}
//END OF DEBUG SECTION
cout << "x equals y? " << (x == y) << endl;
}
So the question is, how can I get these arrays to have the same length without modifying them in 'main'? Can I do this through the assignment function?
You just forgot to assign the same length in the the Array::operator=.
This can be done by writing this->length_ = other.length_; in the
Array& Array::operator=(const Array& other) before overwriting the array.
As mentioned before, you did not asign the length correctly in the = operator.
Fix like this:
Array& Array::operator=(const Array& other)
{
length_ = other.length_;
for (int i = 0; i < length_; ++i)
{
elements_[i] = other.elements_[i];
}
return *this;
}
Also you can simplify your != operator drastically
bool Array::operator!=(const Array& other) const
{
return !(*this == other);
}
However, in my opinon even more important, you should also make use of the std-containers which allow dynamic sizes such as std::vector. This also would have avoided your bug.
In my opinion you should use these std-containers as soon as possible and get used to them. They are almost always the right choice when in doubt.
With std::vector your program could look like this:
#include <iostream>
#include <vector>
using namespace std;
// definition
#define INIT_VALUE 0
class Array {
public:
Array(int length);
Array& operator=(const Array& other);
int length() const;
int& operator[](int index);
bool operator==(const Array& other) const;
bool operator!=(const Array& other) const;
private:
std::vector<int> elements_;
};
// implementation
Array::Array(int length)
:
elements_(length, INIT_VALUE)
{
}
Array& Array::operator=(const Array& other)
{
/*DEBUG*/cout << endl << endl << "<<NOW IN ASSIGNMENT FUNCTION>>" << endl << endl;
elements_ = other.elements_;
return *this;
}
int Array::length() const {
return static_cast<int>(elements_.size());
}
int& Array::operator[](int index) {
// Q3 code goes here
return elements_[index];
}
bool Array::operator==(const Array& other) const
{
return elements_ == other.elements_;
}
bool Array::operator!=(const Array& other) const
{
return !(*this == other);
}
// testing
int main()
{
Array x(10);
x[3] = 42;
cout << "x contains ";
for (int i = 0; i < x.length(); ++i) {
cout << x[i] << " ";
}
cout << endl;
Array y(5);
cout << boolalpha;
cout << "x equals y? " << (x == y) << endl;
cout << "x notequals y? " << (x != y) << endl;
y = x;
//DEBUG SECTION
cout << endl << endl << "<<NOW IN MAIN>>" << endl << endl;
for (int i = 0; i < x.length(); ++i)
{
cout << endl << "Elements: " << x[i] << " | Other Elements: " << y[i] << endl;
}
//END OF DEBUG SECTION
cout << "x equals y? " << (x == y) << endl;
}

Constructor with a array type of another class

This is the photo of the model I have to resolve:
I have this class:
#include<iostream>
#include<fstream>
using namespace std;
class Word
{
protected:
char *value;
char type[20];
int noChars;
static int noWords;
public:
Word(char *value, char *type)
{
this->noChars = 0;
this->value = new char[strlen(value) + 1];
strcpy(this->value, value);
strcpy(this->type, type);
Word::noWords++;
}
Word()
{
this->noChars = NULL;
this->value = NULL;
strcpy(this->type,"Nedeterminat");
}
void operator=(Word &x)
{
this->noChars = x.noChars;
strcpy(this->type, x.type);
this->value = new char[strlen(x.value) + 1];
strcpy(this->value, x.value);
}
Word(const Word& x){
this->noChars = x.noChars;
strcpy(this->type, x.type);
this->value = new char[strlen(x.value) + 1];
strcpy(this->value, x.value);
}
char* getValue()
{
return this->value;
}
void setType(char* x)
{
if (x == NULL)
{
throw new exception("Tip gresit!");
}
else
{
strcpy(this->type, x);
}
}
char &operator[](int i)
{
if (i >= 0 && i <= (strlen(this->value) - 1))
{
return this->value[i];
}
else
cout << endl << "Eroare indice: " << i;
}
static int getNoWords()
{
return Word::noWords;
}
operator int()
{
return this->noChars;
}
friend ostream& operator<<(ostream&, Word&);
friend istream& operator>>(istream&, Word&);
};
ostream& operator<<(ostream& consola, Word& x)
{
consola << "Value: " << x.getValue() << endl;
consola << "Type: " << x.type << endl;
consola << "NoChars: " << x.noChars << endl;
return consola;
}
istream& operator>>(istream& consola, Word& x){
cout << "Value: "; consola >> x.value;
cout << "Type: "; consola >> x.type;
cout << "NoChars: "; consola >> x.noChars;
return consola;
}
int Word::noWords = 0;
class Dictionary{
private:
char *language;
int noWords;
bool isOnline;
Word v[100];
public:
Dictionary(char *language, Word w, int noWords, bool isOnline)
{
this->language = new char[strlen(language) + 1];
strcpy(this->language, language);
for (int i = 0; i < 100; i++)
{
this->v[i] = w;
}
this->noWords = noWords;
this->isOnline = isOnline;
}
};
int main()
{
//1
Word w1("exam", "noun");
/*Word w2;*/
Word w3 = w1;
cout << w3;
//2
cout << endl << "Word value: " << w3.getValue();
Word w2("to take", "noun");
w2.setType("verb");
//3
w3 = w2;
cout << endl << w3;
Word *pw = new Word("pointer", "noun");
delete pw;
//4
cin >> w3; cout << w3;
char character = w3[2];
cout << endl << character;
//5
double noChars = (int)w1;
cout << endl << noChars;
cout << endl << Word::getNoWords() << endl;
//6
Dictionary dictionary1("English", NULL, 0, false);
}
I have this main:
Dictionary dictionary1("English", NULL, 0, false);
How should I change the constructor to work? I receive a error :
Arrgument types are:(const char[8],int,int,bool);
And how should I write the default constructor?
NULL cannot be assigned to Word. Try Word() instead which will call the default constructor to Word. Consider changing that function parameter to const Word& - anonymous temporaries are allowed to bind to const references.
I'd prefer to see a std::string as the type for the member variable language; using a const std::string& as the function parameter. Then you will not have to worry about a subsequent delete call, and defining your own assignment operators and copy constructors. Currently, your class leaks memory.
You can not Assign null to the type Word. If you want to default it you should pass something like word()
Dictionary dictionary1("English", word(), 0, false);
EDIT:
The better approach,IMO, that will work for the same main() you have is like this:
class Dictionary{
private:
std::string language;
int noWords;
bool isOnline;
std::array<Word,100> v;
public:
Dictionary(std::string const& language, Word* w, int noWords, bool isOnline): language (language),isOnline(isOnline ),noWords(noWords)
{
for (int i = 0; i < 100; i++){
this->v[i] = (w==NULL)?word():*w;
}
}
};

Learning C++ Example Problems [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 months ago.
Improve this question
I am currently going though the process of learning C++ though reading programming books. I understand the concept but find a few days after reading, the concepts start to drift from my memory.
The only thing that keeps them there is working through examples/questions.
Are there any good sites or books that can be recommend which give a large number of examples/questions to work through, with explanations of what each example should help you learn?
If your books don't give you tasks to chew on, get better books.
Look at those mentioned here.
This site and this site may be worth looking for you.
You're right. Reading books is not likely to help unless you practice what you learn.
You didn't say what kind of examples you need, and obviously it's important to choose examples which mean something to you - that is, applications which you can see the value of.
Can you suggest some topics which interest you? Like business applications or games, scientific or otherwise?
Just for coment, some examples, i trying add some code....
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iterator>
#include <algorithm>
#include <iomanip>
#include <iostream>
using namespace std;
bool Porovnej(int &p1) {
if (p1 > 5)
{
return true;
}
return false;
}
struct osoba{
int vek;
string jmeno;
set<char> mnozinaPismen;
public:
void Vypis();
};
void osoba::Vypis() {
cout << vek << endl;
cout << jmeno << endl;
for (auto m : mnozinaPismen){
cout << m << endl;
}
cout << "" << endl;
};
int Vytrid(int &prvek) {
if(prvek !=30){
return prvek;
}
return -(prvek);
}
struct JaKralJeliman{
int vek;
string jmeno;
string titul;
public:
void Vypis();
};
void JaKralJeliman::Vypis() {
cout << vek << endl;
cout << titul << endl;
cout << jmeno << endl;
}
class Vytridit{
public:
int operator()(int &prvek) const{
if (prvek > 2) {
return prvek;
}
}
};
int Pricti(int &prvek){
prvek = prvek + 1;
return prvek;
}
class NasobeniHodnot {
private: int _hodnota;
public: NasobeniHodnot(int hodnota) :_hodnota(hodnota) {}
void operator() (int &prvek) const { prvek *= _hodnota; }
};
int GenerujPrvky(){
int prvek = 0;
prvek += rand();
return prvek;
}
class Pair {
private:
int _key, _value;
public:
int GetKey() const { return _key; }
int GetValue() const { return _value; }
void SetKey(int key) { _key = key; }
void SetValue(int value) { _value = value; }
};
istream& operator>>(istream &is, Pair &objekt) {
int cislo;
is >> cislo; /* Využiji již přetížených operátorů pro primitivní datové typy.*/
objekt.SetKey(cislo);
is >> cislo;
objekt.SetValue(cislo);
return is;
}
ostream& operator<<(ostream &os, const Pair &objekt) {
os << objekt.GetKey() << objekt.GetValue();
return os;
}
int main()
{
vector<int> v;
vector<int>::iterator it;
vector<int> v2(100);
vector<int> v3(10);
for (int i = 1; i < 10; i++)
{
v.push_back(i+1);
}
it = find(v.begin(), v.end(), 5);
cout << *it << endl;
back_inserter(v) = 30;
back_inserter(v) = 32;
back_inserter(v) = 32;
back_inserter(v) = 30;
back_inserter(v) = 30;
v.reserve(2 * v.size());
copy(v.begin(), v.end(), back_inserter(v));
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
// for_each(v.begin(), v.end(), ostream_iterator<int>(cout));
it = min_element(v.begin(), v.end());
it = max_element(v.begin(), v.end());
int pocetTricitek = count(v.begin(), v.end(), 30);
cout << "Pocet hodnoty 30 v kontejneru v je:" << pocetTricitek << endl;
cout << "Nejvetsi hodnota" << *it <<endl;
it = find_if(v.begin(), v.end()-1, Porovnej);
cout << "Hodnota iteratoru:" << *it << endl;
it = search_n(v.begin(), v.end()-1, 3, 32);
cout << "Hodnota iteratoru:" << *it << endl;
transform(v.begin(), v.end(), v2.begin(), Vytrid);
fill_n(v3.begin(), 5, 10);
replace(v.begin(), v.end(), 30, 1); //nahradí číslo 30 číslem 1
reverse(v.begin(), v.end());
rotate(v.begin(), v.begin() + 3, v.end());
sort(v.begin(), v.end());
//partial_sort(v.begin(), v.begin() + 10, v.end());
it = lower_bound(v.begin(), v.end(), 15); //>= než 15
vector<int> kolekce(10);
generate(kolekce.begin(), kolekce.end(), GenerujPrvky);
NasobeniHodnot nh(2);
for_each(kolekce.begin(), kolekce.end(), nh);
for_each(kolekce.begin(), kolekce.end(), NasobeniHodnot(2));
int c = 1000, b = 9;
cout << setw(3) << "b=" << b << endl << "c=" << c << endl;
cout << setw(3) << setfill('#') << hex << "c=" << c;
cout << endl;
Pair pair;
cin >> pair;
cout << "Objekt byl:" << endl << pair;
system("pause");
return 0;
}
/*String
string s = "ahoj Oldo";
string::size_type idx;
int pocet = 0;
string s2("Ahoj karle", 6);
cout << s2;
idx = s.find("o");
cout << "idx:" << idx << "string s:" << s << endl;
if (idx == std::string::npos) {
cout << "Není obsažen v řetězci";
} else{
cout << "Je obsažen v řetězci na pozici:" << idx;
}
--------------------//////////////---------------------------
Kontejnery:
string pole[] = { "2", "50" ,"99", "1000" };
list<string> seznam(pole, pole+sizeof(pole)/sizeof(pole[0]));
vector<string> vektorRetezcu;
vektorRetezcu.push_back("a");
vektorRetezcu.push_back("b");
vektorRetezcu.push_back("c");
vektorRetezcu.push_back("d");
vektorRetezcu.push_back("e");
vektorRetezcu.push_back("e");
vektorRetezcu.push_back("a");
list<string> seznam2(vektorRetezcu.begin(), vektorRetezcu.end());
for (auto s : seznam2)
{
cout << s << endl;
}
swap(seznam, seznam2);
for (auto s : seznam2)
{
cout << s << endl;
}
string s1 = "ahoj";
string s2 = "olda";
cout << s1 << s2 << endl;
swap(s1, s2);
cout << s1 << s2 << endl;
--------------------////////////-/////----------------
List
list<osoba> listOsob;
osoba clovek;
for (int i = 0; i < 3; i++)
{
cout << "Zadej cloveka:" << endl;
cin >> clovek.jmeno;
cin >> clovek.prijmeni;
cin >> clovek.vek;
listOsob.push_back(clovek);
}
for (auto osoby : listOsob)
{
cout << "Clovek cislo " << endl;
cout << osoby.jmeno << endl;
}
///////////////////////////////////////////////---------------------mnozicn
struct osoba{
int vek;
string jmeno;
set<char> mnozinaPismen;
public:
void Vypis();
};
void osoba::Vypis() {
cout << vek;
cout << jmeno;
for (auto m : mnozinaPismen)
{
cout << m << endl;
}
}
int main()
{
vector<osoba> vectorLidi;
osoba clovek;
for (int i = 0; i < 3; i++)
{
cin >> clovek.vek;
cin >> clovek.jmeno;
for (int i = 0; i < clovek.jmeno.length(); i++)
{
clovek.mnozinaPismen.insert(clovek.jmeno[i]);
}
vectorLidi.push_back(clovek);
}
for (auto v : vectorLidi)
{
v.Vypis();
}
system("pause");
return 0;
}
-----------------////////////-------------------
vector<osoba> vectorLidi;
osoba clovek;
for (int i = 0; i < 3; i++)
{
cin >> clovek.vek;
cin >> clovek.jmeno;
for (int i = 0; i < clovek.jmeno.length(); i++)
{
clovek.mnozinaPismen.insert(clovek.jmeno[i]);
}
vectorLidi.push_back(clovek);
}
cout << "Nacte no -------------" << endl;
for (auto v : vectorLidi)
{
v.Vypis();
}
*/