cplus
cplus
std::vector
std::vector
Index-based access:
std::vector<int> v{ 1, 2, 3 };
// using []
int a = v[1]; // a is 2
v[1] = 4; // v now contains { 1, 4, 3 }
// using at()
int b = v.at(2); // b is 3
v.at(2) = 5; // v now contains { 1, 4, 5 }
int c = v.at(3); // throws std::out_of_range
exception
at() method performs bounds checking and can throw exceptions, it is slower than [].
Accessing Elements
The front() and back() member functions allow easy reference access to the first and last element of the vector
std::vector<int> v{ 4, 5, 6 };
Note: empty() member function (which checks if the container is empty) before calling front() or back()
Accessing Elements
Iterators:
std::vector<int> v{ 4, 5, 6 };
auto it = v.begin();
int i = *it; // i is 4
++it;
i = *it; // i is 5
*it = 6; // v contains { 4, 6, 6 }
auto it = v.end();
++it;
it == v.end(); // false, it points to the element at position 2 (with
value 6)
++it;
it == v.end(); // true
Initializing a std::vector
std::vector<int> v{ 1, 2, 3 };
Deleting the last element:
v.pop_back(); // v becomes {1, 2}
std::vector<int> v{ 1, 2, 3, 4, 5, 6 };
Deleting all elements in a range:
v.erase(v.begin() + 1, v.begin() + 5); // v becomes
{1, 6}
Deleting elements
struct Point {
double x, y;
Point(double x, double y) : x(x), y(y) {}
};
std::vector<Point> v;
v.emplace_back(10.0, 2.0);
Inserting elements
std::vector<int> v{ 1, 2, 3 };
v.insert(v.begin(), 9); // v now contains {9, 1, 2, 3}
std::vector<int> v{ 1, 2, 3 };
v.emplace(v.begin()+1, 9); // v now contains {1, 9,
2, 3}
2) Write a C++ program that returns the element in a vector that is the first unique element
Example: 1 2 5 0 3 2 1 7 0 1
element that is the first unique: 5