I am trying to overload the [] operator so that when a programmer wishes to retrieve and set specific characters of a string, which is contained in a spot of a vector, the number passed into [] would reference the ith char from the beginning of the vector, to the end.
For example: Here is a vector. Starting from the beginning (0), the contents are as follows:
dog
cat
parrot
where 'dog' is the first string in the vector, and 'parrot' is the last. I want the [] operator to function as follows:
searchable_vector vec;
vec.push_back("dog");
vec.push_back("cat");
vec.push_back("parrot");
std::cout << vec[3] << " should say 'c' ";
Here is my searchable_vector.hpp:
#pragma once
#include <vector>
class searchable_vector : public std::vector<std::string>
{
public:
char& operator [] (int n);
private:
std::vector<std::string> vector;
};
Here is searchable_vector.cpp:
char& searchable_vector::operator[] (int i)
{
// 'for each' string in vector member, count
// the length and add it to a counter until
// the counter is at desired 'length' (given from i)
unsigned int counter = 0;
unsigned int spot_in_string = 0;
std::string holding_string = "";
std::vector<std::string>::iterator it;
it = vector.begin();
while (it != vector.end() && counter != i)
{
if (counter == i) // it is where it needs to be
break;
else
{
spot_in_string = it->length() - 1;
if (counter != 0)
counter += spot_in_string + 1;
else
counter += spot_in_string;
if (counter < i) // look in next string
{
it++;
}
else if (counter > i)
{
while (counter != i) // go 'back' one at a time
{
counter--;
spot_in_string--;
}
break; //should break out of master while loop
}
}
}
holding_string = *it;
return holding_string[spot_in_string];
}
I wouldn't worry too much about the logic going on inside of this code, but I don't think I've done something right with overloading, as I get a Linker 2019 error (using Visual Studio) in my test file for unit testing:
TEST_CASE("Test searchable_vector class [] operator", "[searchable_vector]")
{
searchable_vector vec;
vec.push_back("dog");
vec.push_back("cat");
vec.push_back("parrot");
char result = vec[3];
REQUIRE(result == 'c');
}
The error reads:
LNK2019 unresolved external symbol "public: char & __cdecl
searchable_vector::operator[](int)" (??Asearchable_vector@@QEAAAEADH@Z)
referenced in function "void __cdecl ____C_A_T_C_H____T_E_S_T____2(void)" (?
____C_A_T_C_H____T_E_S_T____2@@YAXXZ) unit_tests
followed by the directory which holds my VM_Module.obj
I think it's just something elementary with my over loading, not the logic itself. If that was broken this it should still link and run, just behave badly or crash.
Any constructive feedback would be appreciated.
Also, the reason I want to overload this is so that the code I am about to write will expect the searchable_vector object to behave as mentioned, returning the ith char in the vector, and if successfully implemented, should be clean and easy to write. Thanks.