Answers for "using c++ vectors"

C++
0

vector of vectors c++

#include <iostream> 
#include <vector> 
using namespace std; 
  
int main() 
{ 
	int n = 5;
	int m = 7;
	//Create a vector containing n vectors of size m and initalize them to 0.
	vector<vector<int>> vec(n, vector<int>(m, 0));

	for (int i = 0; i < vec.size(); i++) //print them out
	{
		for (int j = 0; j < vec[i].size(); j++)
		{
			cout << vec[i][j] << " ";
		}
		cout << endl;
	}
}
Posted by: Guest on May-12-2021
1

declare vectors c++

vector<int> vec;
//Creates an empty (size 0) vector
 

vector<int> vec(4);
//Creates a vector with 4 elements.

/*Each element is initialised to zero.
If this were a vector of strings, each
string would be empty. */

vector<int> vec(4, 42);

/*Creates a vector with 4 elements.
Each element is initialised to 42. */


vector<int> vec(4, 42);
vector<int> vec2(vec);

/*The second line creates a new vector, copying each element from the
vec into vec2. */
Posted by: Guest on May-25-2020
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