I seem to be having a peculiar error in the following code segment (ignore the excess header files and the blank main function, I just wanted to isolate this problem into a compileable .cpp file for posting here). It says error conversion from '[some type I defined]' to non-scalar type '[some type I defined]'.
The code in this particular example is supposed to take a set of list of strings as one input parameter (named input), and a reference to a list of strings as another (named output) and calculate the longest common prefix list of strings from among the lists in input and store the result into output.
The compiler error message (also included as a comment in the corresponding line is this:
lcp.cpp:28:47: error: conversion from ‘
std::list<std::basic_string<char> >::const_iterator {aka std::_List_const_iterator<std::basic_string<char> >}
’ to non-scalar type ‘std::list<std::basic_string<char> >::iterator {aka std::_List_iterator<std::basic_string<char> >}
’ requested
And here is the actual program:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
using namespace std;
void getLongestCommonPrefix(set <list <string> > & input, list <string> & output)
{
set <list <string> > :: iterator it = input.begin();
output = *it;
for(; it != input.end(); ++it)
{
if(output.size() > (*it).size())
{
list <string> :: iterator it1 = output.begin();
advance(it1, (*it).size()-1);
output.erase(it1, output.end());
}
list <string> :: iterator it1 = output.begin();
list <string> :: iterator it2 = (*it).begin(); //lcp.cpp:28:47: error: conv ersion from ‘std::list<std::basic_string<char> >::const_iterator {aka std::_List_const_iterator<std::basic_string<char> >}’ to non-scalar type ‘std::list<std::basic_string<char> >::iterator {aka std::_List_iterator<std::basic_string<char> >}’ requested
for(; it1 != output.end(); ++it1,++it2)
{
if(*it1 != *it2)
break;
}
output.erase(it1, output.end());
if(!output.size())
return;
}
}
int main()
{
return 0;
}
I would love to hear from the experts here as to why and when this sort of error happens and what the work-around could be.
Since C++11, std::set
has no non-constant iterator. When you say this:
(*it).begin();
you're dereferencing a constant iterator to get a constant object and calling begin()
on that object, which gives you another constant iterator since the object is constant. You then try to store this constant iterator into a non-constant iterator, hence the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With