I have a problem with my C++ code. I need to make the sum of the vectors component by component. For example, if I have A(2,1) and B(3,3) the result should be (5,4). I tried to do something but apparently I have a problem and I don't know what to do. The error is: ,,No member called push in std::_1vector" My code is:
#include <iostream>
#include "stack_base.h"
#include <vector>
using namespace std;
template<typename T>
class App {
public:
Stack<T> * stack;
App(Stack<T> &stack) {
this->stack = &stack;
}
T sum(){
Stack<T> *tempStack = stack;
T sum=0;
int size = stack->getTopLevel();
for(int i=0; i<=size; i++) {
sum+=tempStack->peek();
tempStack->pop();
}
return sum;
}
T substract(){
Stack<T> tempStack = *stack;
T substr=0;
for(int i=0; i<=stack->getTopLevel(); i++) {
substr-=tempStack.peek();
tempStack.pop();
}
return substr;
}
};
void display(vector<int> &v)
{
for(int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
cout << "\n" << endl;
}
int main(){
using namespace std;
Stack<int> myStack;
App<int> a(myStack);
unsigned int i = 0;
std::vector<int> v1;
std::vector<int> v2;
// Populate v1 and v2 here
// Check that v1 and v2 have the same length
if (v1.size() != v2.size())
{
// error here
}
std::vector<int> v3; // This will hold the resulting vector
// Preallocate the necessary memory if you like here, but it
// isn't necessary and doesn't gain you much.
for (auto i = 0ul; i < v1.size(); ++i)
{
v3.push_back(v1[i] + v2[i]);
}
int x;
cout << "Enter five integer values for v1" << endl;
for(int i; i<5; i++)
{
cin >> x;
v1.push_back(x);
}
cout << "Enter five integer values for v2" << endl;
for(int i; i<5; i++)
{
cin >> x;
v2.push_back(x);
}
cout << "Size of Vector= " << v2.size() << endl;
display(v3);
return 0;
}
This is Stack:
#include <iostream>
using namespace std;
#define NMAX 30 // pre-processing directive
template<typename T>
class Stack {
private:
// an array of NMAX dimension
T stackArray[NMAX];
/* the top of the stack, representing the INDEX of last element of the
stackArray:0, 1, 2,....*/
int topLevel;
public:
void push(T x) {
//puts an element in the stack array
//check if the stack array has the maximum dimension
if (topLevel >= NMAX - 1)
{
cout<<"The stack is full: we have already NMAX elements!\n";
//exit the function without making anything
return;
}
/*add an element=> the index of the last element of the stack Array
increases and put the value of the new element in the stack array*/
stackArray[++topLevel] = x;
}
int isEmpty() {
//returns 1, if topLevel>=0, meaning the stack array has elements
// returns 0, otherwise
return (topLevel < 0);
}
T pop() {
// extracts and element from the stack array and returns the new top
if (isEmpty()) {
// the extraction is made only if the array is not empty
cout<<"The stack is empty! \n";
T x;
return x;
}
// the topLevel decreases and the new top is changed
return stackArray[--topLevel];
}
T peek() {
// returns the top of the stack
if (isEmpty()) {
// the extraction is made only if the array is not empty
cout<<"The stack is empty! \n";
T x;
return x;
}
return stackArray[topLevel];
}
void display(){
for(int i=0;i<=topLevel;i++)
cout<<stackArray[i];
}
bool search(T num){
for(int i=0; i<=topLevel;i++)
if(num==stackArray[i])
return true;
return false;
}
int getTopLevel(){
return topLevel;
}
Stack() { // constructor
topLevel = -1; // the stack is empty in the beginning
}
void sort(T s){
if (!isEmpty()) {
T x = Pop(s);
sort(s);
push(s, x);
}
}
~Stack() { // destructor
}
};
You are never adding any elements to your vector. In the preceding three lines, you attempt to access elements that do not exist, but the vectors only do bounds checking if you call the 'at' method instead of using the bracket notation. What are you trying to accomplish in that for-loop?
To add two vectors of the same length pair-wise, which is what I think you want, you can do this:
std::vector<int> v1;
std::vector<int> v2;
// Populate v1 and v2 here
// Check that v1 and v2 have the same length
if (v1.size() != v2.size())
{
// error here
}
std::vector<int> v3; // This will hold the resulting vector
// Preallocate the necessary memory if you like here, but it
// isn't necessary and doesn't gain you much.
for (auto i = 0ul; i < v1.size(); ++i)
{
v3.push_back(v1[i] + v2[i]);
// Debugging statement
std::cout << "Added " << v1[i] << " and " << v2[i] << " to get " << v3[i] << " for index " << i << std::endl;
}
Related
I am attempting to create a function that returns a vector as an answer, ie [1,3]. I am confused about the process of manipulating that information once the function has been called. Should I set it equal to a new vector? How would I then display the contents of this new vector? Here is my code for reference. When I attempt to set the function call to a new vector and display it, I get an out of bounds error.
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
vector<int> twoNumberSum(vector<int> array, int targetSum);
int main()
{
int tSum = 10;
vector<int> test{3,5,-4,8,11,1,-1,6};
twoNumberSum(test,tSum);
}
//O^2 complexity
//Two number Sum
vector<int> twoNumberSum(vector<int> array, int targetSum)
{
for (int i=0; i<array.size() -1; i++)
{
int firstNum = array[i];
for(int j=i+1;i<array.size();i++)
{
int secondNum = array[j];
if(firstNum + secondNum == targetSum)
{
return vector<int>{firstNum,secondNum};
}
}
}
return {};
}
To print vector, you could use something like this:
void printVector(vector<int> v) {
cout << "{";
for(int item : v) {
cout << item << ", ";
}
cout << "}";
}
And use it as in a main function: print_vector(twoNumberSum(test, tSum));
Now, bug.
for(int j=i+1;i<array.size();i++)
You increase and check the value of variable i, but you need to use j there.
That will be correct: for(int j=i+1;j<array.size();j++)
The program works correctly and prints the result of function to the console:
void print_vector(vector<int> v);
vector<int> twoNumberSum(vector<int> array, int targetSum);
int main()
{
int tSum = 10;
vector<int> test{3,5,-4,8,11,1,-1,6};
print_vector(twoNumberSum(test, tSum));
}
vector<int> twoNumberSum(vector<int> array, int targetSum)
{
for (int i=0; i<array.size() -1; i++)
{
int firstNum = array[i];
for(int j=i+1;j<array.size();j++)
{
int secondNum = array[j];
if(firstNum + secondNum == targetSum)
{
return vector<int>{firstNum,secondNum};
}
}
}
return {};
}
void print_vector(vector<int> v) {
cout << "{";
for(int item : v) {
cout << item << ", ";
}
cout << "}";
}
I'm having problems with code I'm writing to solve give mazes using class Templates and stacks. The algorithm worked well enough before I implemented code to be able to read mazes from files. Now it doesn't solve the maze, it only outputs "Stack is full! Can not push" and prints the maze. The algorithm I'm adhering goes like:
Define the two-dimensional int array M as given
above, and two int stacks which will store the row
and column index of the locations we have checked.
Search the array M to locate the entry 2 to find your
starting point
Push the current location (i.e., the row and column
index) onto the () stacks.
Check if the value stored at the current location is
a 3; if it is, we are done. If not, set it to 2.
Check the current location's four neighbours in order (e.g., clockwise from north). If any is a 1 or a
3, pop that location onto the stack and move there
next.
If none of the neighbours store a 1, we are at a
dead-end: set the value at that location to 0, and
pop the new location from the stack.
Any help is appreciated!
#include <iostream>
#include <fstream>
#include <string>
#define MAX_STACK 10
void PrintMaze(int **Maze, int M, int N);
template <class T>
class MyStack {
private:
T *contents;
int top, maxsize;
public:
~MyStack(void);
MyStack (void);
MyStack (unsigned int StackSize);
bool checkEmpty(void);
bool checkFull(void);
void push(T c);
T pop(void );
int scon(void);
};
template <class T> MyStack<T>::~MyStack(void)
{
delete [] contents;
}
template <class T> MyStack<T>::MyStack(void)
{
top=0;
contents = new T [MAX_STACK];
maxsize = MAX_STACK;
}
template <class T> MyStack<T>::MyStack(unsigned int StackSize)
{
top=0;
maxsize = StackSize;
contents = new T[StackSize];
}
template <class T> bool MyStack<T>::checkEmpty(void)
{
return MAX_STACK == 0;
}
template <class T> bool MyStack<T>::checkFull(void)
{
return MAX_STACK == 10;
}
template <class T> void MyStack<T>::push(T c)
{
if(checkFull())
{
std::cout << "Stack is fulL! Can not push" << std::endl;
}
else
{
contents[top]=c;
top++;
}
}
template <class T> T MyStack<T>::pop(void)
{
top--;
return(contents[top]);
if(checkEmpty())
{
std::cout << "Stack empty! Can not pop" << std::endl;
return 0;
}
else
{
top--;
return(contents[top]);
}
}
template <class T> int MyStack<T>::scon(void)
{
return(*contents);
}
int main(void )
{
// Open the file
std::ifstream InFile;
InFile.open("C:/Users/Desktop/Computer Science/Maze6.txt");
if (InFile.fail())
{
std::cerr << "Error - cannot open Maze.txt" << std::endl;
return(1);
}
// Read the size of the maze
int Rows, Cols;
InFile >> Rows >> Cols;
std::cout << "The maze has " << Rows << " rows and " << Cols << " columns." << std::endl;
// Dynamically assign memory for the array
int **M = new int*[Rows];
for(int i = 0; i < Rows; ++i)
{
M[i] = new int[Cols];
}
/// Read in the data
for (int i=0; i<Rows; i++)
for (int j=0; j<Cols; j++)
{
char c;
InFile >> c;
M[i][j] = (int)(c-'0');
}
// Display the maze
std::cout << "Here is the maze: ";
PrintMaze(M, Rows, Cols);
//////////////////////////////
MyStack<int> s1;
MyStack<int> s2;
for(int Rows=0; Rows<sizeof(M); Rows++)
{
for(int Cols=0; Cols<sizeof(M); Cols++)
{
if(M[Rows][Cols] == 2)
{
s1.push(Rows);
s2.push(Cols);
if(Rows-1 == 1)
{
s1.push(Rows-1);
s2.push(Cols-1);
M[Rows-1][Cols] == 2;
}
if(Cols+1 == 1)
{
s1.push(Rows);
s2.push(Cols+1);
M[Rows][Cols+1] == 2;
}
if(Rows+1 == 1)
{
s1.push(Rows+1);
s2.push(Cols);
M[Rows-1][Cols] == 2;
}
if(Cols-1 == 1)
{
s1.push(Rows);
s2.push(Cols-1);
M[Rows][Cols-1] == 2;
}
else
{
M[Rows][Cols] = 0;
s1.pop();
s2.pop();
}
}
if(M[Rows][Cols] == 3)
{
std::cout << "Maze completed! Item found at row: " << Rows << " column: " << Cols << std::endl;
std::cout << "Column path: " << s2.scon() << std::endl;
std::cout << "Row path: " << s1.scon() << std::endl;
}
else
{
M[Rows][Cols] == 2;
}
}
}
//////////////////////////////
// Deallocate memory
for(int i =0; i<6; i++)
{
for(int j = 0; j<6; j++)
{
std::cout <<M[i][j] << ' ';
}
std::cout << std::endl;
}
return (0);
}
void PrintMaze(int **Maze, int M, int N)
{
std::cout << std::endl;
for(int i = 0; i<M; i++)
{
for(int j=0; j<N; j++)
{
std::cout << Maze[i][j];
}
std::cout << std::endl;
}
}
sizeof(M) is wrong, it will give you the size of the pointer M itself, not the size of what it points to. You need to explicitly use the Rows and Cols variables, using their original values, and use different values for iterating over the rows and the columns.
As in
//////////////////////////////
MyStack<int> s1;
MyStack<int> s2;
for(int i=0; i<Rows; i++)
{
for(int j=0; j<Cols; j++)
{
// Use i and j as indexes...
}
}
I need help in adding the user to enter value that becomes array size and will sort array by bubble sort its sorting however I need user to enter the value and it becomes value of an array ie. allocation memory dynamically
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort (std::vector<int> &array)
{
std::cout<<"Elements in the array: "<<array.size()<<std::endl;
//comparisons will be done n times
for (int i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for(int j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j+1])
Swap(&array[j], &array[j+1]);
}
}
}
//function to print the array
void PrintArray (std::vector<int> array)
{
for (int i = 0; i < array.size(); i++)
std::cout<<array[i]<<" ";
std::cout<<std::endl;
}
int main()
{
std::cout<<"Enter array to be sorted (-1 to end)\n";
std::vector<int> array;
int num = 0;
while (num != -1)
{
std::cin>>num;
if (num != -1)
//add elements to the vector container
array.push_back(num);
}
//sort the array
BubbleSort(array);
std::cout<<"Sorted array is as\n";
PrintArray(array);
return 0;
}
I tried cin using while however array doesn't print
I modified your version and show you, how you can get the number of elements to sort from the user and hot to dynamically allocate memory in your array.
You will simply use the std::vectors constructor to define a size. Looks then like: std::vector<int> array(numberOfElements);.
The whole adapted code:
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort(std::vector<int>& array)
{
std::cout << "Elements in the array: " << array.size() << std::endl;
//comparisons will be done n times
for (size_t i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for (size_t j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j + 1])
Swap(&array[j], &array[j + 1]);
}
}
}
//function to print the array
void PrintArray(std::vector<int> array)
{
for (size_t i = 0; i < array.size(); i++)
std::cout << array[i] << " ";
std::cout << std::endl;
}
int main()
{
std::cout << "Enter the number of data to sort: ";
size_t numberOfElements{ 0 };
std::cin >> numberOfElements;
std::vector<int> array(numberOfElements);
size_t counter{ 0 };
std::cout << "\nEnter "<< numberOfElements << " data\n";
int num = 0;
while ((counter < numberOfElements) &&(std::cin >> num) )
{
array[counter] = num;
++counter;
}
//sort the array
BubbleSort(array);
std::cout << "Sorted array is as\n";
PrintArray(array);
return 0;
}
But, I would recomend to use modenr C++ elements, like algorithms to solve the problem.
See:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t numberOfElements{ 0 };
std::vector<int> array{};
std::cout << "Enter the number of data to sort: ";
std::cin >> numberOfElements;
std::cout << "\nEnter " << numberOfElements << " data values:\n";
std::copy_n(std::istream_iterator<int>(std::cin), numberOfElements, std::back_inserter(array));
std::sort(array.begin(), array.end());
std::cout << "\n\nSorted data:\n\n";
std::copy(array.begin(), array.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
I am writing a program that displays integer arrays. I set the size of the array, but I am wondering how I can ask the user the index of the array that they want listed. Say the const SIZE = 10, and the user wants to see the first three in the array. I want to also write an exception that catches the error if the user input is over the size of the array. If you need to see some code, let me know. Any help is appreciated!
intergerarray.h
class IntArray
{
private:
int *aptr; // Pointer to the array
int arraySize; // Holds the array size
void subscriptError(); // Handles invalid subscripts
public:
class OutOfBoundException
{
public:
int index;
OutOfBoundException(){};
int getInde() { return index; }
};
IntArray(int); // Constructor
IntArray(const IntArray &); // Copy constructor
~IntArray(); // Destructor
int size() const // Returns the array size
{
return arraySize;
}
int &operator[](const int &); // Overloaded [] operator
};
IntergerArray.cpp
IntArray::IntArray(int s)
{
arraySize = s;
aptr = new int[s];
for (int count = 0; count < arraySize; count++)
*(aptr + count) = 0;
}
IntArray::IntArray(const IntArray &obj)
{
arraySize = obj.arraySize;
aptr = new int[arraySize];
for (int count = 0; count < arraySize; count++)
*(aptr + count) = *(obj.aptr + count);
}
IntArray::~IntArray()
{
if (arraySize > 0)
delete[] aptr;
}
void IntArray::subscriptError()
{
cout << "ERROR: Subscript out of range.\n";
exit(0);
}
int &IntArray::operator[](const int &sub)
{
if (sub < 0 || sub >= arraySize)
subscriptError();
return aptr[sub];
}
driver file.cpp
int main()
{
int SIZE = 10;
//int index;
//cout << "enter an index";
//cin >> index;
IntArray table(SIZE);
for (int x = 0; x < SIZE; x++)
table[x] = x;
for (int x = 0; x < SIZE; x++)
cout << table[x] << " ";
cout << endl;
//table[SIZE + 1] = 0;
return 0;
}
Isn't this what you are trying to do? why so much code for such a simple problem?
const int arraySize = 10;
int array[arraySize];
int elementToDis;
do
{
std::cout << "Number of array elements to display: ";
std::cin >> elementToDis;
} while (elementToDis > arraySize || elementToDis < 0); // this is your exeption
for (int ccc(0); ccc < elementToDis; ++ccc)
std::cout << "Index " << ccc << ": " << array[ccc] << '\n';
I think you want to display all elements lower than an index value entered by the user :
Let array[] be the array name of size=10,you can get an index value (say l) from the user and use that value inside a for loop for printing all elements in index lower than l
int array[size]
void disp_in(int l)
{
if(l>=size) // if l greater than or equal to size (as index start at 0)
throw l;
else
{
cout<<"Elements : ";
for(int i=0;i<=l;i++) //if we have say l=2 ,array values in indexes 0,1and 2 will be displayed
cout<<array[i];
}
}
int main ()
{
int l;
cout<<"Enter index : ";
cin>>l; //till this index value, the array value will be displayed
try
{
disp_in(l);
}
catch(int e)
{
cout<<"Index value greater than max index";
}
return 0;
}
You could try something like this:
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
void print_numbers( const std::vector<int>& array, int nNumbers, const char* pszSeparator )
{
if ( nNumbers > static_cast<int>(array.size()) )
{
throw std::exception();
}
std::copy( array.begin(), array.begin() + nNumbers, std::ostream_iterator<int>( std::cout, pszSeparator ) );
}
int main()
{
std::vector<int> array( 10 );
//Just for testing
{
int n = 0;
auto generator = [n]() mutable
{
return n++;
};
std::generate_n( array.begin(), array.size(), generator );
}
try
{
print_numbers(array, 11, "\n");
}
catch ( std::exception e )
{
std::cout << "Error message..." << std::endl;
}
return 0;
}
I'm trying to make a program that will erase an integer from a vector, containing a random sequence of integers only if it is found in the vector. I wrote code already, but I get an error when I call the erase() function to actually delete the same integers in the vector. Thoughts?
#include <iostream>
#include <vector>
using namespace std;
void removeX(vector<int>& wl, int x);
int main()
{
vector<int> m_list;
int num;
for(int i = 0; i <= 25; i++) //made the vector have values from 1 to 25.
{
m_list.push_back(i);
}
cout << "Enter a number you wish to find and remove: " << endl;
cin >> num;
removeX(m_list, num);
for (size_t i = 0; i < m_list.size(); i++)
{
cout << "Content at index: " << i << ": " << m_list[i] << endl;
}
return 0;
}
void removeX(vector<int>& wl, int x)
{
for(size_t i = 0; i < wl.size(); i++)
{
if (x == wl[i])
{
wl.erase(w[i]);
}
}
}
you show know that the parameter of function erase is iterator type, not size_t type.
void removeX(vector<int>& wl, int x)
{
vector<int>::iteratot iter = wl.begin();
while(iter != wl.end())
{
if (*iter == wl[i])
{
iter = wl.erase(iter);
}
else
iter++;
}
}