I am designing a data structure than can efficiently store and check if total of any three successively added elements is equal to given total.
For example MovingTotal () creates an empty container with no existing totals.append ([1,2,3]) appends elements [1,2,3] which means that there is only one exisitng total (1 + 2 + 3 = 6 ), append ([4]) appends element 4 and creates additional total from [2,3,4]. There would now be two totals (1 + 2 + 3 = 6 and 2 + 3 + 4 = 9). At this point contains (6) and contains (9) should return True, while contains (7) should return False.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <vector>
#include <stdexcept>
#include <iostream>
#include <string>
class MovingTotal{
private:
std::vector<int> list = std::vector<int>();
public:
virtual void append(std::vector<int> &list);
virtual bool contains(int total);
static void main(std::vector<std::wstring> & args);
};
void MovingTotal::append(const std::vector<int> addAll& list)
{
list.addAll(Arrays::asList(list));
throw std::logic_error("Waiting for implement");
}
bool MovingTotal:: contains(int total)
{
if((list[0] + list[1] + list[2]) == total)
{
return true;
}
return false;
throw std::logic_error("Waiting for implement");
}
#ifndef RunTests
int main()
{
MovingTotal *movingTotal = new MovingTotal();
movingTotal->append(std::vector<int> {1,2,3});
std::vector<int> first;
first.push_back(1);
first.push_back(2);
first.push_back(3);
movingTotal->append(first);
std::wcout << movingTotal->contains(6) << std::endl;
std::wcout << movingTotal->contains(9) << std::endl;
std::vector<int> second;
second.push_back(4);
movingTotal->append(second);
std::wcout << movingTotal->contains(9) << std::endl;
}
#endif
| |
Below are compilation errors:
void MovingTotal::append(const std::vector<int> addAll& list)
^
main.cpp:23:6: error: prototype for ‘void MovingTotal::append(std::vector)’ does not match any in class ‘MovingTotal’
void MovingTotal::append(const std::vector<int> addAll& list)
^~~~~~~~~~~
main.cpp:18:19: error: candidate is: virtual void MovingTotal::append(std::vector&)
virtual void append(std::vector<int> &list);
^~~~~~
main.cpp: In function ‘int main()’:
main.cpp:44:29: error: cannot bind non-const lvalue reference of type ‘std::vector&’ to an rvalue of type ‘std::vector’
movingTotal->append(std::vector<int> {1,2,3});
^~~~~~~~~~~~~~~~~~~
main.cpp:18:19: note: initializing argument 1 of ‘virtual void MovingTotal::append(std::vector&)’
virtual void append(std::vector<int> &list);
^~~~~~