Материал из C\C++ эксперт
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Assign elements in vector a value through an iterator
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
int main()
{
vector<char> v(10); // create a vector of length 10
vector<char>::iterator p; // create an iterator
int i;
// assign elements in vector a value
p = v.begin();
i = 0;
while(p != v.end()) {
*p = i + "a";
p++;
i++;
}
return 0;
}
Delete the first element of the vector
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> INTVECTOR;
const int ARRAY_SIZE = 4;
int main(void)
{
INTVECTOR theVector;
// Intialize the array to contain the members [100, 200, 300, 400]
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back((cEachItem + 1) * 100);
cout << "First element: " << theVector.front() << endl;
cout << "Last element: " << theVector.back() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
// Delete the first element of the vector.
theVector.erase(theVector.begin());
cout << "New first element is: " << theVector.front() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
}
Delete the last element of the vector
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> INTVECTOR;
const int ARRAY_SIZE = 4;
int main(void)
{
INTVECTOR theVector;
// Intialize the array to contain the members [100, 200, 300, 400]
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back((cEachItem + 1) * 100);
cout << "First element: " << theVector.front() << endl;
cout << "Last element: " << theVector.back() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
cout << "Deleting last element." << endl;
theVector.erase(theVector.end() - 1);
cout << "New last element is: " << theVector.back() << endl;
}
Get the last element in a vector
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> INTVECTOR;
const int ARRAY_SIZE = 4;
int main(void)
{
INTVECTOR theVector;
// Intialize the array to contain the members [100, 200, 300, 400]
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back((cEachItem + 1) * 100);
cout << "Last element: " << theVector.back() << endl;
}