2

I created Class and initialised a vector inside private field, then i initialised vector by useing methods of my Class. Now i need to delete elements in range of two numbers which i have to type on a keyboard

#include <iostream>
#include <vector>
#include <algorithm>

int randomNumber()
{
    return (0 + rand() % 50 - 10);
}

class Array {
vector<int>::iterator p;
public:
    vector<int>array;
    Array(int size)
    {
        array.resize(size);
        generate(array.begin(), array.end(), randomNumber);
    }
    void Print() {
        for (p = array.begin(); p != array.end(); p++) {
            cout << *p << ' ';
        }
        cout << endl;
    }
    void Condense() {
        int a, b;
        cout << "Enter your range: [";  
        cin >> a;
        cin >> b;
        cout << "]" << endl;
        for (p = array.begin(); p != array.end(); p++) {
            if (a < *p < b || a > *p < b) {

            }
        }
    }
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
AndrewMemo
  • 37
  • 4

1 Answers1

2

Here is a demonstrative program that shows how you can remove elements of a vector in the range ( a, b ).

#include <iostream>
#include <vector>
#include <tuple>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '\n';

    int a = 7, b = 2;

    std::tie( a, b ) = std::minmax( { a, b } );

    auto inside_range = [&]( const auto &item )
    {
        return a < item && item < b;
    };

    v.erase( std::remove_if( std::begin( v ), std::end( v ), inside_range ),
             std::end( v ) );

    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

Its output is

0 1 2 3 4 5 6 7 8 9 
0 1 2 7 8 9 

Instead of using std::minmax and std::tie to order a and b you could just write the condition like

    auto inside_range = [&]( const auto &item )
    {
        return a < item && item < b || b < item && item < a;
    };

As for your code then the condition in the if statement

if ( a < *p < b || a > *p < b) {

is incorrect, You mean

if (a < *p && *p < b || b < *p && *p < a ) {
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335