Pointers or just objects?
You cannot put references in an array in C ++. You can create an array of pointers, but I would prefer the container and the actual objects, rather than pointers, because:
- Inability to leak, exception safety is easier to handle.
- - , .
, , ( , ) ( ) , ( , ), , . .
#include <vector>
struct foo {
virtual void it() {}
};
struct bar : public foo {
int a;
virtual void it() {}
};
int main() {
std::vector<foo> v;
v.push_back(bar());
std::vector<foo*> v2;
v2.push_back(new bar());
}
, , .
.
NULL , / ( delete), , , . if- , :
std::for_each(v2.begin(),v2.end(), std::mem_fun(&foo::it));
NULL , . , std::vector erase, , :
v2.erase(v2.begin());
v2.begin()+1 . " n- ", std::vector - - , , .
:
#include <utility>
#include <iterator>
#include <algorithm>
#include <iostream>
int main() {
int arr[] = {1,2,3,4};
int len = sizeof(arr)/sizeof(*arr);
std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
std::swap(arr[1], arr[len-1]);
len -= 1;
std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
std::swap(arr[0], arr[len-1]);
len -= 1;
std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
, std::vector. , , , !