cpp vector class code example
Example 1: c++ vector
#include <vector>
int main() {
std::vector<int> v;
v.push_back(10);
v.push_back(20);
v.pop_back();
v.push_back(30);
auto it = v.begin();
int x = *it;
++it;
int y = *it;
++it;
bool is_end = it == v.end();
return 0;
}
Example 2: std vector include c++
#include <vector>
std::vector<std::string> x;
Example 3: 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;
}
Example 4: cpp vector structure
#include <vector>
typedef struct test1 {
int a;
char b;
} TOTO;
std::vector<TOTO> _v;
_v.push_back((TOTO){10, 'a'});
_v[0].a = 101;