C-Programmierung
STL Beispiele
← STL Container | ● | STL Iteratoren →
Beispiel für std::Vector:
#include <iostream>
#include <Vector>
typedef struct{double r;} Apfel;
{
Vector<Apfel> aepfel;
Apfel jonagold;
aepfel.push_back(jonagold);
aepfel.push_back(jonagold);
aepfel.push_back(jonagold);
std::cout << aepfel.size() << std::endl; // -> 3
}
#include <Vector>
typedef struct{double r;} Apfel;
{
Vector<Apfel> aepfel;
Apfel jonagold;
aepfel.push_back(jonagold);
aepfel.push_back(jonagold);
aepfel.push_back(jonagold);
std::cout << aepfel.size() << std::endl; // -> 3
}
Beispiel für std::string:
#include <iostream>
#include <string>
{
std::string a("foo");
std::string b("bar");
std::string c = a+" "+b;
std::cout << c << std::endl; // -> "foo bar"
}
#include <string>
{
std::string a("foo");
std::string b("bar");
std::string c = a+" "+b;
std::cout << c << std::endl; // -> "foo bar"
}
Analoges Beispiel für C-Strings:
{
char a[] = "foo";
char b[] = "bar";
char s[] = " ";
char *c = new char[strlen(a)+strlen(s)+strlen(b)+1];
strcpy(c, a);
strcpy(c+strlen(a)+1, s);
strcpy(c+strlen(a)+strlen(s), b);
// c -> "foo bar";
delete c; //!! if forgotten, will cause huge memory leak
}
char a[] = "foo";
char b[] = "bar";
char s[] = " ";
char *c = new char[strlen(a)+strlen(s)+strlen(b)+1];
strcpy(c, a);
strcpy(c+strlen(a)+1, s);
strcpy(c+strlen(a)+strlen(s), b);
// c -> "foo bar";
delete c; //!! if forgotten, will cause huge memory leak
}
← STL Container | ● | STL Iteratoren →