vector class code example
Example 1: vector in c++
vector<int> g1;
for (int i = 1; i <= 5; i++)
g1.push_back(i);
cout << "Output of begin and end: ";
for (auto i = g1.begin(); i != g1.end(); ++i)
cout << *i << " ";
cout << "\nOutput of cbegin and cend: ";
for (auto i = g1.cbegin(); i != g1.cend(); ++i)
cout << *i << " ";
cout << "\nOutput of rbegin and rend: ";
for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << *ir << " ";
Example 2: vector in c++ class
#include <iostream>
#include <vector>
class Object
{
public:
Object()
{}
~Object()
{}
void AddInt(int num)
{
m_VectorOfInts.push_back(num);
}
std::vector<int> GetCopyOfVector()
{
return m_VectorOfInts;
}
void DisplayVectorContents()
{
for( unsigned int i = 0; i < m_VectorOfInts.size(); i++ )
{
std::cout << "Element[" << i << "] = " << m_VectorOfInts[i] << std::endl;
}
std::cout << std::endl;
}
private:
std::vector<int> m_VectorOfInts;
};
int main()
{
Object obj;
obj.AddInt(32);
obj.AddInt(56);
obj.AddInt(21);
obj.DisplayVectorContents();
std::vector<int> container1 = obj.GetCopyOfVector();
container1.push_back(342);
container1.push_back(64);
container1.push_back(123);
obj.DisplayVectorContents();
return 0;
}