Suppose that you implement a sequence where the value_type has a comparison oper
ID: 3670248 • Letter: S
Question
Suppose that you implement a sequence where the value_type has a comparison operator < to determine when one item is "less than" another item. For example, intefers, double numbers, and characters all have such a comparison operator ( and clases that you implement yourself may also be given such a comparison). Rewrite the sequence class using a new class name, sorted_sequence. In a sorted sequence, the insert funtion always inserts a new item so that all the items stay in order from smallest to largest. There is no attach functon. All the other functions are the same as the original sequence class. (C++ language please)
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
template <class T>
class sorted_sequence{
private:
vector<T> elems;
public:
void insert(T val){
elems.push_back(val);
sort(elems.begin(), elems.end());
}
void print(){
for(int i = 0; i < elems.size(); i++){
cout << elems[i] << " " ;
}
cout << endl;
}
};
int main(){
sorted_sequence<int> V;
for(int i = 0; i < 10; i++){
cout << "Number Inserted: ";
int val = rand() %100;
cout << val << endl;
V.insert(val);
cout << "Array so far: " ;
V.print();
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.