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++;
}
}
Related
I have some code written but I'm not sure why the reversed array is not giving me the exact values I need. I created a second array the same size as the first and used nested for loops to fill the second with the contents of the first in reverse.
See below:
#include <iostream>
using namespace std;
int main()
{
// Ask for how big the array is
int n;
cout << "how big is the array?" << endl;
cin >> n;
// create array
int a[n];
// create second array
int b[n];
// ask for contents of the 1st array
cout << "what's in the array?" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
// reverse the array
for (int i = n - 1; i >= 0; i--)
{
for (int k = 0; k < n; k++)
{
b[k] = a[i];
break;
}
}
// print out the new array
for (int k = 0; k < n; k++)
{
cout << b[k] << endl;
}
return 0;
}
you don't need 2 bucles for fill the second array
try with:
//reverse the array
s = 0;
for (int i=n-1;i>=0;i--){
b[n]=a[s];
s++;
}
Try something like this:
#include <algorithm>
#include <iostream>
#include <vector>
namespace {
template <typename IStream>
[[nodiscard]] int readOneIntFrom(IStream& istream) {
int x;
istream >> x;
return x;
}
}
int main()
{
// Ask for how big the array is
std::cout << "how big is the array?" << std::endl;
auto n = readOneIntFrom(std::cin);
// create array
std::vector<int> a;
// ask for contents of the 1st array
std::cout << "what's in the array?" << std::endl;
for (int i = 0; i < n; i++)
{
a.emplace_back(readOneIntFrom(std::cin)); // Make a new entry at the end of a.
}
// Construct b from a backward. (Or do auto b = a; std::reverse(b.begin(), b.end());
auto b = std::vector<int>(a.rbegin(), a.rend());
// print out the new array
for (const auto& bi : b)
{
std::cout << bi << std::endl;
}
return 0;
}
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 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 getting an out of range exception with my while loop in my code.
I have tried to use an Array instead and the error does not occur with the same loop structure. I am confused why this would happen. I believe that the savedValue <= value[rank.at(current-1)]) statement is what is causing the error.
int suffixArray::size;
std::vector<int> suffixArray::rank;
int main( int argc, char* argv[]) {
std:: string test = "BANANA$";
suffixArray testString (test);
return 0;
}
#include <iostream>
#include <vector>
class suffixArray{
public: static int size;
public: static std::vector<int> rank;
public: suffixArray(std:: string concatenated ){
size =(int) concatenated.length();
std:: cout << size << std:: endl;
rank.resize(7);
char *suffixPointers[concatenated.length()];
int value[concatenated.length()];
for(int i =0; i <= size-1; i++){
suffixPointers[i] = &concatenated[i];
value[i] = (int)concatenated[i];
}
std::cout << "[";
for(int i = 0; i<= size-1; i++){
std::cout <<value[i] << " ";
}
std::cout << "]"<< std:: endl;
for(int i = 0; i<=size -1; i++){
if(i == 0){
rank.assign(i,i);
}
else if(value[i] > value[i-1]){
rank.assign(i,i);
}else{
int current =i;
int savedValue = value[i];
int prevSavedRank;
while(current-1 >= 0 && savedValue <= value[rank.at(current-1)]){
prevSavedRank= rank.at(current-1);
rank.assign(current-1, i);
rank.assign(current, prevSavedRank);
current--;
}
}
}
}
};
Adding more logging into your program reveals the problem: you rank.assign(0,0) - the first 0 specifies the new vector length, so this call removes all the elements in the vector (see std::vector::assign docs at cppreference) then call rank.at(0): 0 is not a valid index into an empty vector, so std::out_of_range.
You'll have to rethink your logic.
Program with extra logging:
#include <iostream>
#include <vector>
template <typename T>
struct Vector : std::vector<T>
{
void assign(size_t count, const T& value)
{
std::cout << "assign(count " << count << ", " << value << ")\n";
std::vector<T>::assign(count, value);
}
const T& at(size_t pos) const
{
std::cout << "at(" << pos << ")\n";
return std::vector<T>::at(pos);
}
};
class suffixArray{
public: static int size;
public: static Vector<int> rank;
public: suffixArray(std:: string concatenated ){
size =(int) concatenated.length();
std:: cout << size << std:: endl;
rank.resize(7);
char *suffixPointers[concatenated.length()];
int value[concatenated.length()];
for(int i =0; i <= size-1; i++){
suffixPointers[i] = &concatenated[i];
value[i] = (int)concatenated[i];
}
std::cout << "[";
for(int i = 0; i<= size-1; i++){
std::cout <<value[i] << " ";
}
std::cout << "]"<< std:: endl;
for(int i = 0; i<=size -1; i++){
if(i == 0){
rank.assign(i,i);
}
else if(value[i] > value[i-1]){
rank.assign(i,i);
}else{
int current =i;
int savedValue = value[i];
int prevSavedRank;
while(current-1 >= 0 && savedValue <= value[rank.at(current-1)]){
prevSavedRank= rank.at(current-1);
rank.assign(current-1, i);
rank.assign(current, prevSavedRank);
current--;
}
}
}
}
};
int suffixArray::size;
Vector<int> suffixArray::rank;
int main( int argc, char* argv[]) {
std:: string test = "BANANA$";
suffixArray testString (test);
}
Output:
7
[66 65 78 65 78 65 36 ]
assign(count 0, 0)
at(0)
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
I have tried to use an Array instead and the error does not occur with the same loop structure.
std::array and C-style arrays (T[]) are fixed sized containers, lacking an equivalent of the std::vector::assign you're using to resize your vector, so your program must have been modified quite heavily - not just a clean substitution of an array.
My assignment asks me to write a function that takes an array and the size of that array as a parameter, and to find the mode. If there are multiple modes, I am to find them all, and place them in a vector and print said vector in an ascending order.
For example, if I input the following integers:
3, 4, 2, 1, 2, 3
Then the output should display
2, 3
If I input the following integers:
1, 2, 3, 4
Then the output should display:
1, 2, 3, 4.
However, my program somehow only finds the first mode and displays it in a really awkward manner.
Here was my input:
3, 4, 2, 3, 2, 1
And this was the output:
3
3
3
3
3
Here is my code. Any help would be greatly appreciated. Thank you all for your time!
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int size; //array size
int* array; //array of ints
int arraycount; //counter for array loop
void findMode(int array[], int size); //function prototype
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
array = new int[size];
for (arraycount = 0; arraycount < size;
arraycount++)
cin >> array[arraycount];
//call function
findMode(array, size);
return 0;
}
void findMode(int array[], int size) {
int counter = 1;
int max = 0;
int mode = array[0];
int count;
vector <int> results;
//find modes
for(int pass = 0; pass < size - 1; pass++) {
if(array[pass] == array[pass+1]) {
counter++;
if(counter > max) {
max = counter;
mode = array[pass];
}
}
else {
counter = 1;
}
}
//push results to vector
for (count=0; count < size - 1; count++) {
if(counter == max) {
std::cin >> mode;
results.push_back(mode);
}
}
//sort vector and print
std::sort(results.begin(), results.end());
for (count=0; count < size - 1; count++) {
cout << mode << endl;
}
}
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int main() {
int size; //array size
int* array; //array of ints
std::vector<int> vecInput;
int arraycount; //counter for array loop
void findMode(std::vector<int> vec); //function prototype
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
array = new int[size];
for (arraycount = 0; arraycount < size; arraycount++)
{
int num;
cin >> num;
vecInput.push_back(num);
}
//call function
findMode(vecInput);
return 0;
}
void findMode(std::vector<int> vec)
{
std::sort(vec.begin(), vec.end());
std::map<int, int> modMap;
std::vector<int>::iterator iter = vec.begin();
std::vector<int> results;
int prev = *iter;
int maxCount = 1;
modMap.insert(std::pair <int,int>(*iter, 1));
iter++;
for (; iter!= vec.end(); iter++)
{
if (prev == *iter)
{
std::map<int, int>::iterator mapiter = modMap.find(*iter);
if ( mapiter == modMap.end())
{
modMap.insert(std::pair <int,int>(*iter, 1));
}
else
{
mapiter->second++;
if (mapiter->second > maxCount)
{
maxCount = mapiter->second;
}
}
}
else
{
modMap.insert(std::pair <int,int>(*iter, 1));
}
prev = *iter;
}
std::map<int, int>::iterator mapIter = modMap.begin();
for (; mapIter != modMap.end(); mapIter++)
{
if (mapIter->second == maxCount)
{
results.push_back(mapIter->first);
}
}
cout << "mod values are " <<endl;
std::vector<int>::iterator vecIter = results.begin();
for (; vecIter != results.end(); vecIter++)
cout<<*vecIter<<endl;
}
Thank you all for the help, I was able to get the code to work. Turns out the problem was the cin in my vector portion of the function. Here is my revised code:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <stdlib.h>
#include <vector>
using namespace std;
#define N 100
void findMode(int x[], int size); //function prototype
vector<int> results; //vector
int main(void) {
int* x;
int size=0;
int arraycount;
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
x = new int[size];
for (arraycount = 0; arraycount < size;
arraycount++)
cin >> x[arraycount];
//send array and size to function
findMode(x, size);
return 0;
}
//findMode function
void findMode(int x[], int size) {
int y[N]={0};
int i, j, k, m, cnt, count, max=0;
int mode_cnt=0;
int num;
int v;
vector<int> results;
vector<int>::iterator pos;
//loop to count an array from left to right
for(k=0; k<size; k++) {
cnt=0;
num=x[k]; //num will equal the value of x[k]
for(i=k; i<size; i++) {
if(num==x[i])
cnt++;
}
y[k]=cnt; //
}
//find highest number in array
for(j=0; j<size; j++) {
if(y[j]>max)
max=y[j];
}
//find how many modes there are
for(m=0; m<size; m++) {
if(max==y[m])
mode_cnt++;
}
//push results to vector
for (m=0; m < size; m++) {
if(max == y[m]) {
//after taking out this line the code works properly
// std::cin >> x[m];
results.push_back(x[m]);
}
}
//sort vector and print
std::sort(results.begin(), results.end());
cout << "The mode(s) is/are: ";
for (pos=results.begin(); pos!=results.end(); ++pos) {
cout << *pos << " ";
}
}