Answers for "vector class c++"

C++
36

c++ vector

#include <vector>

int main() {
  std::vector<int> v;
  v.push_back(10); // v = [10];
  v.push_back(20); // v = [10, 20];
  
  v.pop_back(); // v = [10];
  v.push_back(30); // v = [10, 30];
  
  auto it = v.begin();
  int x = *it; // x = 10;
  ++it;
  int y = *it; // y = 30
  ++it;
  bool is_end = it == v.end(); // is_end = true
  
  return 0;
}
Posted by: Guest on March-17-2020
0

c++ vector of class objects

#include <iostream>
#include <vector>
using namespace std;

class Site {
public:
    int i;
};

int main() {
    vector<Site> listofsites;
    Site *s1 = new Site;
    s1->i = 7;
    Site *s2 = new Site;
    s2->i = 9;
    listofsites.push_back(*s1);
    listofsites.push_back(*s2);
    vector<Site>::iterator it;
    for (it = listofsites.begin(); it != listofsites.end(); ++it) {
        cout << it->i;
    }
    return 0;
}
Posted by: Guest on November-22-2021
0

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()
{
	// Create our class an add a few ints
	Object obj;
	obj.AddInt(32);
	obj.AddInt(56);
	obj.AddInt(21);

	// Display the vector contents so far
	obj.DisplayVectorContents();

	// Creates a copy of the classes container you can only really view whats in 
	// the classes vector container. What ever changes you make here wont effect the class.
	std::vector<int> container1 = obj.GetCopyOfVector();
	// These elements wont be added as it's a copy of the container
	container1.push_back(342);
	container1.push_back(64);
	container1.push_back(123);


	// Display the classes container to see show nothing was added.
	obj.DisplayVectorContents();

	return 0;
}
Posted by: Guest on February-27-2020

Browse Popular Code Answers by Language