Learning C++ Example Problems [closed] - c++

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();
}
*/

Related

warning C4018: '<': signed/unsigned mismatch ONLY when I include Identical Functions

I am lost, when I ran my program last night it ran fine. When I added the power() function, suddenly lines which ran fine without adding the new code now trigger an error message:
warning C4018: '<': signed/unsigned mismatch
Why?
I feel I don't have the chops to explain this, so please follow the code below.
PLEASE RUN THE CODE WITH AND WITHOUT THIS power() FUNCTION. When run with the power() function, it makes error C4018 on the for loops in the exam() function! When run without the power() function, it runs FINE!!
#include <string>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
///the offending function///
double power(double base, int exponent)
{
double product;
//double base; int exponent;
std::cout << "enter a value for base: " << endl;
std::cin >> base;
std::cout << "enter exponenent: " << endl;
std::cin >> exponent;
double result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * base;
//product = base exponent;
}
std::cout << product;
return product;
}
///after here, things run fine if you X out the aforementioned function! Wow!
void exam()
{
std::vector<int> scores;
int F;
F = 0; //string names;
std::cout << "enter exam scores int:" << endl;
//std::vector <string> names;
while (F != -1)
{
std::cout << "Enter a new exame score:" << endl;
std::cin >> F;
scores.push_back(F);
}
if (F == -1)
{
std::cout << "end of score entering" << endl;
}
for (int i = 0; i < scores.size(); i++)
{
std::cout << scores[i];
}
/*
while (i < scores.size())
{
std::cout << scores[i];
i++;
}
*/
std::cout << "yay you made this work!!!!!!!!!!!!!" << endl;
}
int multiply()
{
int a;
int b;
a = 8;
b = 4;
std::cout << a * b << endl;
std::cout << "f*** yeah" << endl << endl;
return 0;
}
void test()
{
std::vector<int> newvector;
int T;
std::cout << "enter vector variables: " << endl;
std::cin >> T;
newvector.push_back(T);
while (T != -1)
{
std::cout << "enter new vector variables T " << endl;
std::cin >> T;
newvector.push_back(T);
if (T == -1)
{
newvector.pop_back();
}
}
std::cout << "end of NewVector data inputs:" << endl;
for (int W = 0; W < newvector.size(); W++)
{
std::cout << newvector[W] << endl;
}
}
int main()
{
power(2, 3);
exam();
/*int result = multiply();
std::cout << "endl ;" << endl;
test();
system("pause"); */
multiply();
string name;
int a;
std::cout << "enter a variable for your name: " << endl;
std::getline(cin, name);
if (name == "aaron")
{
std::cout << " what a dumb name, aAron?" << endl;
}
else if (name == "todd")
{
std::cout << "what a dottly name, Todd" << endl;
}
else
{
std::cout << "your name = " << name << endl;
}
//std::vector <string>
std::vector<int> asdf;
std::cout << "enter an int for a" << endl;
std::cin >> a;
asdf.push_back(a);
while (a != -1)
{
std::cout << "enter another A: " << endl;
std::cin >> a;
asdf.push_back(a);
if (a == -1)
{
asdf.pop_back();
}
} //set var; checks if d<size(); if so, JUMP to std::cout<<; when finished with body, find after size(); == "d++", then refer back to declaration)
/*/ for(int G = 0; G<asdf.size(); G++)
{
std::cout << asdf[G] << endl;
} */
for (int i = 0; i < asdf.size(); i++)
{
std::cout << asdf[i] << "f*** it works!!!!!! " << endl;
}
for (int d = 0; d < asdf.size(); d++)
{ //htt ps://youtu.be/_1AwR-un4Hk?t=155
std::cout << asdf[d] << ", ";
}
std::cout << endl;
std::cout << std::accumulate(asdf.begin(), asdf.end(), 0);
//std::cout<<
system("pause");
return 0;
}
The presence of the power function should have no effect on this problem. Possibly you aren't seeing the warnings because without the power function the program does not compile.
In
for (int W = 0; W < newvector.size(); W++)
newvector.size() returns an unsigned integer. int W is a signed integer. You're getting exactly what you asked for.
You can change int W to vector<int>::size_type W (but the less verbose size_t W should also work) to make the error message go away, but this is an error where you would likely have to add more than 2 billion items to the vector to see manifest.
Solution:
for (vector<int>::size_type W = 0; W < newvector.size(); W++)
However this is a good place for a range-based for loop
for (const auto &val: newvector)
{
std::cout << val << endl;
}
By letting the compiler figure out all the sizes and types your life is much easier.
This is repeated several times throughout the code.
Re: WHEN RUN, It makes error C4018 -
YOU made that error (warning, actually), not "it".
That warning is reported by compiler, so you haven't run anything yet...
Your newly added function uses uninitialized variable product; in my version of Visual Studio it is an error.

What should i do to optimize this C++ code? I don't have any idea which statement is taking more execution time

I was to solve one question on hackerrank related to lower bound in C++. My code was able to pass all the test cases which had no time limit but failed in all time bound test cases. You can find the hackerrank question from this link:
https://www.hackerrank.com/challenges/cpp-lower-bound/problem?utm_campaign=social-buttons&utm_medium=linkedin&utm_source=challenge
Below is my code. Please tell me how I can optimize it.
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<int> v;
int elementCount = 0, queryCount = 0, tempElement = 0;
std::cin >> elementCount;
for(int i=0; i<elementCount; ++i)
{
std::cin >> tempElement;
v.push_back(tempElement);
}
std::vector<int>::iterator elementPosition;
const std::vector<int>::iterator midElement = v.begin() + v.size()/2;
std::cin >> queryCount;
for(int q=0; q<queryCount; ++q)
{
std::cin >> tempElement;
if(tempElement <= *midElement)
{
elementPosition = find(v.begin(), midElement+1, tempElement);
if(elementPosition == (midElement+1))
{
elementPosition = lower_bound(v.begin(), midElement, tempElement);
std::cout << "No " << (elementPosition-v.begin())+1 << std::endl;
}
else
{
std::cout << "Yes " << (elementPosition-v.begin())+1 << std::endl;
}
}
else
{
elementPosition = find(midElement+1, v.end(), tempElement);
if(elementPosition != v.end())
{
std::cout << "Yes " << (elementPosition-v.begin())+1 << std::endl;
}
else
{
elementPosition = lower_bound(midElement+1, v.end(), tempElement);
std::cout << "No " << (elementPosition-v.begin())+1 << std::endl;
}
}
}
return 0;
}
You have over complicated the solution with unnecessary find() + lower_bound.
Just use lower_bound() to find the element
If found, print yes
If not, print no
auto elementPosition = lower_bound(v.begin(), v.end(), tempElement);
size_t pos = std::distance(v.begin(), elementPosition);
if (v[pos] == tempElement) {
//print yes
} else {
// print no
}

Operator Overloading solution

i have made a c++ code. An MList that holds items in it. I overloaded the << operator to print the values in MList in a particular format. Here is the code:
friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
string s = "";
s += "Size " + to_string(m.size_) + "\n";//out << m.size() << endl;
s += "Cap " + to_string(m.capacity_) + "\n"; //out << m.capacity() << endl;
for (int i = 0; i < m.size_; i++)
{
if (i < m.size_ - 1)
s += m.ary[i].element + ",";//out << m.ary[i].element << ",";
else
s += m.ary[i].element;
}
//cout << "String : " << s;
return out << s;
}
But it does not print correct value. It prints the size and capacity right but not the values. Instead of values, it prints some signs like heart:
You can see it prints size and capacity right but not the values. Here is the relevant code. I am executing case 2 only right now:
#include<iostream>
using std::cout; using std::endl;
using std::ostream; using std::cin; using std::boolalpha;
#include<string>
using std::string;
using namespace std;
template <class V>
struct SetElement
{
V element;
int cnt;
SetElement() = default;
SetElement(V v) : element(v){}
};
template <class V>
ostream &operator<<(ostream & o,const SetElement<V> &p)
{
return o << p.element;
}
template <class V>
class MSet
{
private:
SetElement<V> *ary;
size_t capacity_;
size_t size_;
public:
MSet(V val)
{
capacity_ = 2;
ary = new SetElement<V>[capacity_];
ary[0].element = val;
ary[0].cnt = 1;
size_ = 1;
}
SetElement<V>* find(V val)
{
SetElement<V> *found = nullptr;
bool yes = false;
for (int i = 0; i < size_ && !yes; i++)
{
if (ary[i].element == val)
{
found = &ary[i];
yes = true;
}
}
return found;
}
friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
string s = "";
s += "Size " + to_string(m.size_) + "\n";//out << m.size() << endl;
s += "Cap " + to_string(m.capacity_) + "\n"; //out << m.capacity() << endl;
for (int i = 0; i < m.size_; i++)
{
if (i < m.size_ - 1)
s += m.ary[i].element + ",";//out << m.ary[i].element << ",";
else
s += m.ary[i].element;
}
//cout << "String : " << s;
return out << s;
}
};
int main(){
int test;
long l1, l2, l3;
cin >> test;
cout << boolalpha;
switch (test){
// ...
case 2: {
cin >> l1 >> l2;
MSet<long> m_l(l1);
auto p = m_l.find(l1);
if (p != nullptr)
cout << *p << endl;
else
cout << "Val:" << l1 << " not found " << endl;
p = m_l.find(l2);
if (p != nullptr)
cout << *p << endl;
else
cout << "Val:" << l2 << " not found " << endl;
//cout << "MList \n";
cout << m_l;
break;
}
// ...
}
}
You're adding the values into a temporary string, which may involve implicit conversions depending of the template type (here your numerical values were converted into characters).
Just print the values, without the temporary string:
friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
out << "Size " << m.size_ << endl;
out << "Cap " << m.capacity_ << endl;
for (int i = 0; i < m.size_; i++)
{
if (i < m.size_ - 1)
out << m.ary[i].element << ",";
else
out << m.ary[i].element;
}
return out;
}

How do I sort array of pointers to structs without changing original array?

I am fairly new to C++ and pointers, and would greatly appreciate any help. I am trying to print a sorted array of pointers without changing the original array of structs. I cannot properly sort the pointers. I am using the std::sort that worked on the original array, but I fail at using it on pointers. To make things worse, my failed attempts all change the original. Thank you for your time.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
struct Student
{
int age;
char name[30];
};
void displayStudent(Student s)
{
cout << endl<< s.age<< " "<< s.name;
}
int main()
{
Student s1;
s1.age = 10;
strcpy(s1.name, "Guy");
Student s2;
s2.age = 33;
strcpy(s2.name, "Buddy");
Student s3;
s3.age = 16;
strcpy(s3.name, "Friend");
Student s4;
s4.age = 55;
strcpy(s4.name, "Pal");
Student myClass[4];
myClass[0] = s1;
myClass[1] = s2;
myClass[2] = s3;
myClass[3] = s4;
Student *myClassPt;
myClassPt = &myClass[0];
Student *SBN[4];
Student *SBG[4];
Student *SBA[4];
for (int i = 0; i < 4; i++)
{
SBN[i] = &(myClassPt[i]);
SBA[i] = &(myClassPt[i]);
}
cout << "Original" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(myClass[i]);
}
std::sort(*SBN, *SBN + 4, [](Student &a, Student &b){ return a.name < b.name; });
std::sort(*SBA, *SBA + 3, [](Student const &a, Student const &b){ return a.age < b.age; });
cout <<endl<<endl<< "Sorted by name" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(*SBN[i]);
}
cout << endl << endl << "Sorted by age" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(*SBA[i]);
}
cout << endl <<endl<< "Original" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(myClass[i]);
}
return 0;
}
It seems you want to sort the pointers according to the objects they point to. So you need to sort the pointers according to the objects they point to, instead of trying to sort the objects they point to directly:
std::sort(SBN, SBN + 4, [](const Student* a, const Student* b)
{ return a->name < b->name; });
Here's a working example:
#include <iostream>
#include <algorithm>
struct student { int age; };
int main()
{
student ss[] = { {23}, {12}, {42}, {9}};
std::cout << "students\n";
for (const auto& s : ss) std::cout << s.age << " ";
std::cout << std::endl;
student* ps[] = { &ss[0], &ss[1], &ss[2], &ss[3]};
std::cout << "pointers to student\n";
for (auto p : ps) std::cout << p->age << " ";
std::cout << std::endl;
std::sort(ps, ps + 4, [](const student* a, const student* b)
{ return a->age < b->age;});
std::cout << "pointers to student after sorting\n";
for (auto p : ps) std::cout << p->age << " ";
std::cout << std::endl;
}
Output:
students
23 12 42 9
pointers to student
23 12 42 9
pointers to student after sorting
9 12 23 42

C++: transfer a vector into a subprogram

In my example there are three similar vectors which I would like to print.
Could you help me understand how to transfer a vector into a subprogram so that not to
repeat myself?
#include "stdafx.h";
#include <vector>;
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
struct SPoint
{
int X;
int Y;
};
vector<SPoint> points;
vector<SPoint> selected;
vector<SPoint> cleared;
void print_points()
{
cout << "Points: "<< endl;
for (int i = 0; i < points.size(); i++)
{
cout << '('<<points[i].X <<',' <<points[i].Y <<')'<< endl;
}
cout << endl;
}
void print_selected()
{
cout << "Selected: "<< endl;
for (int i = 0; i < selected.size(); i++)
{
cout << '('<<selected[i].X <<',' <<selected[i].Y <<')'<< endl;
}
cout << endl;
}
void print_cleared()
{
cout << "Cleared: "<< endl;
for (int i = 0; i < cleared.size(); i++)
{
cout << '('<<cleared[i].X <<',' <<cleared[i].Y <<')'<< endl;
}
cout << endl;
}
int main ()
{
SPoint temp = {0, 0};
for (int i = 0; i < 11;i++)
{
temp.X = i;
temp.Y = i;
points.push_back(temp);
}
for (int i = 5; i< 11;i++)
{
temp.X = i;
temp.Y = i;
points.push_back(temp);
}
print_points();
print_selected();
print_cleared();
system ("pause");
return 0;
}
You could do something like this:
void
print(const std::vector<SPoint>& vect, const std::string& message)
{
std::cout << message << ":" << std::endl;
for (int i = 0, size = vect.size(); i < size; ++i)
std::cout << vect[i].X << ":" << vector[i].Y << " ";
std::endl;
}
print(points, "Points");
print(points, "Selected");
print(points, "Cleared");
Good luck
To pass a vector as an argument to a function you do something like this:
void func(const vector<SPoint>& points) {
... do stuff
}
Then you call the function in you code like this:
...some stuff
vector<SPoint> a;
func(a);
Just use a const reference to a vector and pass it to the function:
void print(const vector<SPoint> &data) const {
}
...
print(points);
Here is a full C++ style approach:
struct SPoint
{
int X;
int Y;
};
std::ostream& operator <<( std::ostream& stream, SPoint const& point )
{
stream << '(' << point.X << ',' <<point.Y << ')';
return stream;
}
void print_vector( std::ostream& stream, std::vector< SPoint > const& vector )
{
std::copy(
points.begin(), points.end()
, std::ostream_iterator< SPoint >( std::cout, '\n' )
);
}
and then:
print_vector( std::cout, points );
print_vector( std::cout, selected );
print_vector( std::cout, cleared );