C++: transfer a vector into a subprogram - c++

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 );

Related

The problem approaching private number of class

My program receives width and breadth of rectangle
My output would be rectangle and specific point which can get from second line input. If number is odd , it will represent 'y' coordinate, else it will represent 'x' coordinate.
My problem is
pt.mark(pt.get_p(), pt.get_q());
this one.
In my method "mark",
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
x() represents " 0 " . So , my rectangle looks like
I don't know why this happen , because my approach to the private number of Class "Point" is not wrong using method x().
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <sstream>
using namespace std;
class Point
{
private:
int _x, _y;
public:
Point(int x=0, int y=0): _x(x), _y(y) {}
int x() { return _x; }
int x(int n) {return _x = n;}
int y() { return _y; }
int y(int n) {return _y=n;}
};
class MovingPoint: public Point
{
private:
int p, q;
vector<int> nums;
public:
MovingPoint(int x = 0, int y = 0): Point(x, y) {}
MovingPoint(vector<int> a) : nums(a) {}
void mark(int x, int y);
void calculate();
int get_p() {return p;}
int get_q() {return q;}
};
ostream& operator <<(ostream& out, MovingPoint p)
{
return out << "(" << p.x() << ", " << p.y() << ")";
}
void MovingPoint::mark(int a, int b)
{
ostringstream buf;
vector<int> lengths;
vector<string> words;
int cnt;
char prev = buf.fill('-');
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
char pres = buf.fill(' ');
for (int i = 0; i < y() ; i++)
{
if (i == b - 1)
buf << "| " << setw(a) << "." << setw(x() - a) << " |" << endl;
else
buf << "| " << setw(x()) << " |" << endl;
}
char prev1 = buf.fill('-');
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
buf.fill(prev1);
cout << buf.str();
}
void MovingPoint::calculate()
{
p = 0;
q = 0;
for (int i = 0; i < nums.size() ; i++)
{
if (nums[i] % 2 == 0)
p++;
else
q++;
}
}
int main()
{
int x;
int y;
vector<int> nums;
cin >> x >> y;
MovingPoint pt(x, y);
while (cin >> x)
{
nums.push_back(x);
}
pt = MovingPoint(nums);
pt.calculate();
pt.mark(pt.get_p(), pt.get_q());
}
You might do, with some renaming:
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <sstream>
struct Rectangle
{
unsigned int width;
unsigned int height;
};
struct Point
{
unsigned int x;
unsigned int y;
};
void draw(const Rectangle& rect, const Point& pt)
{
std::ostringstream buf;
buf.fill('-');
buf << "+-" << setw(x() - 2) << "" << "-+" << endl;
buf.fill(' ');
for (unsigned int i = 0; i < rect.height() ; i++)
{
if (i == pt.y - 1)
buf << "| " << setw(pt.x) << "." << setw(rect.width() - pt.x) << " |" << endl;
else
buf << "| " << setw(rect.width()) << " |" << endl;
}
char prev1 = buf.fill('-');
buf << "+-" << setw(rect.width() - 2) << "" << "-+" << endl;
buf.fill(prev1);
std::cout << buf.str();
}
Point calculate(const std::vector<int>& v)
{
Point p{0, 0};
for (auto e : v)
{
if (e % 2 == 0)
p.x++;
else
p.y++;
}
return p;
}
int main()
{
Rectangle r;
std::cin >> r.width >> r.height;
std::vector<int> nums;
int n;
while (std::cin >> n)
{
nums.push_back(n);
}
Point pt = calculate(nums);
draw(r, pt);
}

'auto' declaration issue in C++

I have a problem in using auto declarations. I write a program in Visual Studio 2017 as follow:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
public:
struct mystruct {
vector<int> vi;
};
vector<mystruct> TheStructV;
void AddStructV() {
TheStructV.push_back(mystruct());
};
};
int main()
{
MyClass MyObj[3];
for (int a = 0; a < 3; a++) {
MyObj[a].AddStructV();
for (int i = 1; i <= 5; i++) {
MyObj[a].TheStructV[MyObj[a].TheStructV.size() - 1].vi.push_back(i * 10 + idx);
}
idx++;
}
for (int b = 0; b<3; b++) {
cout << "MyObj[" << b << "] struct vector size:" << MyObj[b].TheStructV.size() << endl;
cout << "MyObj[" << b << "] struct vi size:" << MyObj[b].TheStructV[0].vi.size() << endl;
}
for (int i = 0; i < 3; i++) {
cout << "MyObj[" << i << "].vi:";
for (int j = 0; j < 5; j++) {
cout << MyObj[i].TheStructV[0].vi[j] << "-";
}
cout << endl;
}
return 0;
}
It works as expected, and the output is:
MyObj[0] struct vector size:1
MyObj[0] struct vi size:5
MyObj[1] struct vector size:1
MyObj[1] struct vi size:5
MyObj[2] struct vector size:1
MyObj[2] struct vi size:5
MyObj[0].vi:11-21-31-41-51-
MyObj[1].vi:12-22-32-42-52-
MyObj[2].vi:13-23-33-43-53-
However, if I change the code to this:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
public:
struct mystruct {
vector<int> vi;
};
vector<mystruct> TheStructV;
void AddStructV() {
TheStructV.push_back(mystruct());
};
};
int main()
{
MyClass MyObj[3];
int idx = 1;
for (auto M : MyObj) {
M.AddStructV();
for (int i = 1; i <= 5; i++) {
M.TheStructV[M.TheStructV.size() - 1].vi.push_back(i * 10 + idx);
}
idx++;
}
for (int b = 0; b<3; b++) {
cout << "MyObj[" << b << "] struct vector size:" << MyObj[b].TheStructV.size() << endl;
cout << "MyObj[" << b << "] struct vi size:" << MyObj[b].TheStructV[0].vi.size() << endl;
}
idx = 1;
for (auto MC : MyObj) {
cout << "MyObj[" << idx - 1 << "].vi:";
for (auto thisStruct : MC.TheStructV) {
cout << thisStruct.vi[0] << "-";
cout << thisStruct.vi[1] << "-";
cout << thisStruct.vi[2] << "-";
cout << thisStruct.vi[3] << "-";
cout << thisStruct.vi[4] << "-";
}
cout << endl;
idx++;
}
return 0;
}
It compiles without problem, but I get an error when I run it, and the output is:
MyObj[0] struct vector size:0
The program is stuck here.
It seems that I am missing something. I even tried replacing auto M with MyClass M, but still the same problem.
This line will make a copy of your object
for (auto M : MyObj)
change it to a reference so you can modify it
for (auto& M : MyObj)

C++ - error: 'function' was not declared in this scope

I have the following Problem:
error: 'kleiner' was not declared in this scope
My Professor told me, that my code just works fine for him.
The directories are all included in bulid options (I am using Code::Blocks).
Can someone please tell me what the problem might be?
main.cpp
#include <iostream>
#include "vector.h"
using namespace std;
int main(int argc, char *argv[])
{
Vector v1;
cout << "v1: " << v1 << endl;
Vector v2(8);
cout << "v2: " << v2 << endl;
cout << "Minimum von v2: " << v2.min() << endl;
Vector v3(v2);
cout << "v3: " << v3 << endl;
cout << "Anzahl von v3: " << v3.getAnzahl() << endl;
if ( kleiner( v3[2], v2[5] ) )//<<--<<--<<-- HERE IS THE PROBLEM
cout << v3[2] << " ist kleiner als " << v2[5] << endl;
int arr[5] = { 10, 5, 2, 3, 12 };
Vector v4;
cout << "v4: " << v4 << endl;
v4.setVector( arr, 4 );
cout << "v4 nach set: " << v4 << endl;
cout << "Minimum von v4: " << v4.min() << endl;
cout << "Anzahl von v4: " << v4.getAnzahl() << endl;
return 0;
}
vector.h
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
using namespace std;
class Vector
{
int* v;
int anzahl;
public:
Vector(int anzahl = 10);
Vector( const Vector& vec ); // Kopierkonstruktor
~Vector();
friend bool kleiner( const int& a, const int& b );
int min() const;
int getAnzahl() const;
int operator[]( const int i ) const;
void setVector( int* sv, int sanzahl);
friend ostream& operator<< ( ostream& os, const Vector& v );
};
#endif
vector.cpp
#include "vector.h"
Vector::Vector( int a ) : anzahl(a)
{
v = new int[a];
for ( int i = 0; i < a; i++ )
v[i] = i;
}
Vector::Vector( const Vector& vec )
{
anzahl = vec.getAnzahl();
v = new int[anzahl];
for ( int i = 0; i < anzahl; i++ )
v[i] = vec[i];
}
Vector::~Vector()
{
delete[] v;
v = NULL;
}
bool kleiner( const int& a, const int& b )
{
return ( a < b );
}
int Vector::min() const
{
int min = v[0];
for ( int i = 1; i < anzahl; i++ )
{
if ( v[i] < min )
min = v[i];
}
return min;
}
int Vector::getAnzahl() const
{
return anzahl;
}
int Vector::operator[] ( const int i ) const
{
return v[i];
}
void Vector::setVector( int* sv, int sanzahl )
{
delete[] v; // alten Inhalt loeschen
anzahl = sanzahl;
v = new int[anzahl];
for ( int i = 0; i < anzahl; i++ )
v[i] = sv[i];
return;
}
ostream& operator<< ( ostream& os, const Vector& v )
{
for ( int i = 0; i < v.anzahl; i++ )
os << v[i] << ", ";
return os;
}
Declare the function outside of the class as well as specifying as a friend.
Reference; http://en.cppreference.com/w/cpp/language/friend
A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not accessible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided - see namespaces for details.
I think you and your Professor have different compilers?
Declare the friend function also outside the class definition in the header. It is not visiable until it will be declared outside the class.

Implementing Dijkstra's algorithm with vector of pointers

I'm working on a program involving Dijkstra's algorithm.
After searching long and far, I have only found help pertaining to Dijkstra's algorithm using Queues or Heaps, however, I am not using these. I have been tasked to used a vector of pointers to Vertex objects (a custom class I have defined).
I have attempted to convert the Queue pseudo code (from my textbook) to the best of my ability below:
void Dijkstra(vector<Vertex*> & V, int startNum)
{
vector<Vertex*> sortedVertices = V;
sortedVertices[startNum]->setDV(0);
insertionSort(sortedVertices);
while(sortedVertices.size() != 0)
{
sortedVertices[sortedVertices.size() - 1]->setKnown(true);
sortedVertices.pop_back();
insertionSort(sortedVertices);
Vertex * v = V[1]; // Will always bring the first element off the list
v->setKnown(true);
for(int m = 0; m < sortedVertices->getAdjacentVertices().size(); m++)
{
int dist = getAdjacentVertices()[m].getWeight();
if((sortedVertices[1].getDV() + dist) < sortedVertices[m+1]->getAdjacentVertices()[m].getDV())
{
//WE WILL DECREASE THE VALUE HERE by finding the distance between two vertices
cout << "It works so far" << endl;
// BOOK has this, somehow need to change it: w.path = v
}
}
}
}
However, when I attempt to compile, I keep receiving the following errors:
Main.cpp: In function 'void Dijkstra(std::vector<Vertex*>&, int)':
Main.cpp:154:42: error: base operand of '->' has non-pointer type 'std::vector<Vertex*>'
Main.cpp:156:44: error: 'getAdjacentVertices' was not declared in this scope
Main.cpp:157:35: error: request for member 'getDV' in 'sortedVertices.std::vector<_Tp, _Alloc>::operator[]<Vertex*, std::allocator<Vertex*> >(1ul)', which is of pointer type '__gnu_cxx::__alloc_traits<std::allocator<Vertex*> >::value_type {aka Vertex*}' (maybe you meant to use '->' ?)
Main.cpp:157:99: error: '__gnu_cxx::__alloc_traits<std::allocator<Edge> >::value_type' has no member named 'getDV'
I am trying to reduce the amount of Code in this post, but if need to be, my entire code is below:
Main.cpp:
#include "Vertex.h"
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;
void shortestPath(vector<Vertex> & v);
template <typename Comparable>
void insertionSort(vector<Comparable> & a);
template <typename Comparable>
void insertionSort( vector<Comparable> & a, int left, int right );
///overload the less than operator in order to use the stl sort for vector
///print out the path for each vertex
int main()
{
/////READ ALL THE STUFF INTO THE GRAPH////
ifstream file;
file.open("graph.txt");
cout << "Opening file..." << endl;
if(!file)
{
cout << "System failed to open file.";
}
else
{
cout << "File successfully opened" << endl;
}
int numVertices;
int numEdges;
int num;
int adjacentVertex;
int weight;
file >> numVertices;
cout << "The number of vertices that are being read into the graph from the file: " << numVertices;
cout << endl;
vector<Vertex*> vertices;
//vector<Vertex> vertices(numVertices + 1);
Vertex * newVertex;
vertices.push_back(NULL);
cout << "SIZE: " << vertices.size() << endl;
cout << "NUM VERTICES: " << numVertices << endl;
for(int i=1;i < numVertices + 1; i++)
{
file >> numEdges;
cout << "At vertex " << i << " the number of edges is " << numEdges << endl;
newVertex = new Vertex();
//Using the i counter variable in the outer for loop to identify
//the what vertex what are currently looking at in order to read in the correct adjacent vertex and weight
cout << "LENGTH OF VERTICES[i]: " << vertices.size() << endl;
newVertex->setVertexNum(i);
//newVertex.setVertexNum(i);
for(int j=1;j<=numEdges;j++)
{
file >> adjacentVertex;
cout << "The adjacent vertex is: " << adjacentVertex << endl;
file >> weight;
cout << "The weight is: " << weight << endl;
cout << endl;
newVertex->setAdjacentVertex(adjacentVertex, weight);
}
//cout << "LENGTH OF VERTICES[i]: " << vertices.size() << endl;
vertices.push_back(newVertex);
}
file.close();
vector<Vertex*> sortedVertices = vertices;
insertionSort(sortedVertices);
cout << "SIZE: " << vertices.size() << endl;
for(int i=0;i<vertices.size();i++)
{
cout << "V" << i << ": ";
cout << endl;
if(vertices[i] != NULL)
{
cout << "DV Value: " << vertices[i]->getDV();
cout << endl;
cout << "Known Value: " << vertices[i]->getKnown();
cout << endl;
}
}
cout << "Sorted: " << endl;
for(int i=0;i<sortedVertices.size();i++)
{
cout << "V" << i << ": ";
cout << endl;
if(vertices[i] != NULL)
{
cout << "DV Value: " << sortedVertices[i]->getDV();
cout << endl;
cout << "Known Value: " << sortedVertices[i]->getKnown();
cout << endl;
}
}
//CALL THE SHORTEST PATH FUNCTION ON THE GRAPH/////
}
/*
const bool myFunction(const Vertex & x, const Vertex & y)
{
return (x.getDV() >= y.getDV());
}
*/
bool operator < (const Vertex & v1, const Vertex & v2)
{
return v1.getDV() > v2.getDV();
}
void Dijkstra(vector<Vertex*> & V, int startNum)
{
vector<Vertex*> sortedVertices = V;
sortedVertices[startNum]->setDV(0);
insertionSort(sortedVertices);
while(sortedVertices.size() != 0)
{
sortedVertices[sortedVertices.size() - 1]->setKnown(true);
sortedVertices.pop_back();
insertionSort(sortedVertices);
Vertex * v = V[1]; // Will always bring the first element off the list
v->setKnown(true);
for(int m = 0; m < sortedVertices->getAdjacentVertices().size(); m++)
{
int dist = getAdjacentVertices()[m].getWeight();
if((sortedVertices[1].getDV() + dist) < sortedVertices[m+1]->getAdjacentVertices()[m].getDV())
{
//WE WILL DECREASE THE VALUE HERE by finding the distance between two vertices
cout << "It works so far" << endl;
// BOOK has this, somehow need to change it: w.path = v
}
}
}
}
////////INSERTION SORT////////////
template <typename Comparable>
void insertionSort( vector<Comparable> & a )
{
for( int p = 1; p < a.size( ); ++p )
{
Comparable tmp = std::move( a[ p ] );
int j;
for( j = p; j > 0 && tmp < a[ j - 1 ]; --j )
a[ j ] = std::move( a[ j - 1 ] );
a[ j ] = std::move( tmp );
}
}
template <typename Comparable>
void insertionSort( vector<Comparable> & a, int left, int right )
{
for( int p = left + 1; p <= right; ++p )
{
Comparable tmp = std::move( a[ p ] );
int j;
for( j = p; j > left && tmp < a[ j - 1 ]; --j )
a[ j ] = std::move( a[ j - 1 ] );
a[ j ] = std::move( tmp );
}
}
Vertex.h:
#include "Edge.h"
#include <vector>
#include <climits>
#include <fstream>
using namespace std;
class Vertex
{
private:
int vertexNum; //number of the vertex for identification purposes
int degree;
bool known;
vector<Edge> adjacentVertices; //vector of vertices that are adjacent to the vertex we are currently looking at
int dv; //distance
int pv; //previous vertex
Vertex *vertex;
public:
Vertex()
{
dv = INT_MAX;
known = false;
}
void setKnown(bool Known)
{
known = Known;
}
bool getKnown()
{
return known;
}
void setVertexNum(int VertexNum)
{
vertexNum = VertexNum;
}
void setDegree(int Degree)
{
degree = Degree;
}
vector<Edge> & getAdjacentVertices()
{
return adjacentVertices;
}
int getVertexNum()
{
return vertexNum;
}
int getDegree()
{
return degree;
}
int getDV() const
{
return dv;
}
int setDV(int Dv)
{
dv = Dv;
}
void setAdjacentVertex(int AdjacentVertex, int Weight)
{
Edge newEdge;
newEdge.setWeight(Weight);
newEdge.setAdjVertex(AdjacentVertex);
adjacentVertices.push_back(newEdge);
}
friend ostream & operator <<(ostream & outstream, Vertex *vertex)
{
outstream << vertex->getVertexNum() << endl;
outstream << vertex->getDegree() << endl;
outstream << vertex->getKnown() << endl;
vector<Edge> E = vertex->getAdjacentVertices();
for(int x=0;x<E.size();x++)
{
outstream << E[x].getAdjVertex() << endl;
outstream << E[x].getWeight() << endl;
}
return outstream;
}
friend bool operator < (const Vertex & v1, const Vertex & v2);
};
Edge.h:
#include <cstdlib>
class Edge
{
private:
int adjVertex; //represents the vertex that the edge leads to
int weight;
public:
Edge()
{
adjVertex = 0;
weight = 0;
}
void setWeight(int Weight)
{
weight = Weight;
}
void setAdjVertex(int adjacent)
{
adjVertex = adjacent;
}
int getAdjVertex()
{
return adjVertex;
}
int getWeight()
{
return weight;
}
};
From g++ to English:
Main.cpp: In function 'void Dijkstra(std::vector<Vertex*>&, int)':
Main.cpp:154:42: error: base operand of '->' has non-pointer type 'std::vector<Vertex*>'
Main.cpp:156:44: error: 'getAdjacentVertices' was not declared in this scope
Main.cpp:157:35: error: request for member 'getDV' in 'sortedVertices.std::vector<_Tp, _Alloc>::operator[]<Vertex*, std::allocator<Vertex*> >(1ul)', which is of pointer type '__gnu_cxx::__alloc_traits<std::allocator<Vertex*> >::value_type {aka Vertex*}' (maybe you meant to use '->' ?)
Main.cpp:157:99: error: '__gnu_cxx::__alloc_traits<std::allocator<Edge> >::value_type' has no member named 'getDV'
Explanation:
for(int m = 0; m < sortedVertices->getAdjacentVertices().size(); m++) <- this is 154. sortedVertices is not a pointer. It is a std::vector of some pointers.
int dist = getAdjacentVertices()[m].getWeight(); <- 156. What is getAdjacentVertices?
sortedVertices[1].getDV() <- 157 sortedVertices[1] is a pointer. Look at operator[]
sortedVertices[m+1]->getAdjacentVertices() is a vector of Edge. Edge does not have a getDV() method defined.
Is this really your code?
As an author you should not have trouble understanding the error messages. Those are simple mistakes, that took 5 minutes for a stranger to understand. You need to put more effort in understanding what you write, and what compiler tells you. Or get some sleep to get some focus.
I would also suggest to spend some time working out what std::vector really is and how to understand std::vector<Vertex*> vector_of_vertices; object.
vector<Vertex*> sortedVertices = V;
sortedVertices[startNum]->setDV(0)
Here you create variable of type vector<Vertex*> on the stack. This is not a pointer. This is a container containing pointers of type Vertex* and that's completely different. You use -> operator which is only used on pointers.

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