Reputation: 41
For clarity, I am not asking how to iterate through a vector of strings (which is what all of my searches turn up), I want to iterate through a string contained in a vector of strings. I'm running into linker errors when trying to assign the string iterator a value from a string in a vector.
The code below takes a reference to a const vector of strings. The purpose of the function is to reverse the order of the letters and the elements so if you passed in a vector of strings containing { "abc", "def", "ghi" } it would reorder them and return a vector of strings containing { "ihg", "fed", "cba" }. It should be noted that the function is declared as static in the header file. I'm running into a problem when I try to attempt to initialize the string iterator in the for loop. I get a linker error:
"No matching constructor for initialization of 'std::__1::__wrap_iter<char*>'
I thought accessing rbegin() through the -> from the vector iterator would work but... I'm stumped. Why does stringsVectorIterator->rend() cause a linker error when assigned to string::reverse_iterator rit?
vector<string> StringUtility::reverse(const vector<string> &strings)
{
// Create a vector of strings with the same size vector as the one being passed in.
vector<string> returnValue( strings.size() );
vector<string>::const_reverse_iterator stringsVectorIterator;
size_t returnVectorCounter;
for (stringsVectorIterator = strings.rbegin(), returnVectorCounter = 0;
stringsVectorIterator != strings.rend();
stringsVectorIterator++, returnVectorCounter++)
{
// the problem is in the initialization of the string iterator, it creates
// a linker error.
for (string::reverse_iterator rit = stringsVectorIterator->rbegin();
rit != stringsVectorIterator->rend();
++rit)
{
returnValue[returnVectorCounter].push_back(*rit);
}
}
return returnValue;
};
Upvotes: 0
Views: 137
Reputation: 254431
stringsVectorIterator
is a const
iterator, so its target string is const
. This means you can't get a non-const
iterator over the string.
Change the inner loop:
for (string::const_reverse_iterator rit = ...
^^^^^^
and all should be well.
In C++11 or later, you could use auto
to avoid these hassles.
Upvotes: 5