Can I return String instead of std::ostream& ?!
Posted: Mon Mar 25, 2019 3:50 pm
Hello !
I have the following string ring buffer:
And I tried making it using String class from Arduino:
I need print() to return a String. The problem with my code is that instead of returning all the elements in the buffer, it returns just one element: the last one it has in the buffer at call time.
Do you have any advice on how to fix this ?
Thank you !
I have the following string ring buffer:
Code: Select all
#include <iostream>
#include <string>
#include <vector>
struct ring_buffer
{
ring_buffer( std::size_t cap ) : buffer(cap) {}
bool empty() const { return sz == 0 ; }
bool full() const { return sz == buffer.size() ; }
void push( std::string str )
{
if( last >= buffer.size() ) last = 0 ;
buffer[last] = str ;
++last ;
if( full() ) first = (first+1) % buffer.size() ;
else ++sz ;
}
std::string& operator[] ( std::size_t pos )
{
auto p = ( first + pos ) % buffer.size() ;
return buffer[p] ;
}
std::ostream& print( std::ostream& stm = std::cout ) const
{
if( first < last )
for( std::size_t i = first ; i < last ; ++i ) std::cout << buffer[i] << ' ' ;
else
{
for( std::size_t i = first ; i < buffer.size() ; ++i ) std::cout << buffer[i] << ' ' ;
for( std::size_t i = 0 ; i < last ; ++i ) std::cout << buffer[i] << ' ' ;
}
return stm ;
}
private:
std::vector<std::string> buffer ;
std::size_t first = 0 ;
std::size_t last = 0 ;
std::size_t sz = 0 ;
};
int main()
{
ring_buffer rb(8) ;
for( int i = 10 ; i < 30 ; ++i )
{
rb.push( std::to_string(i) ) ;
rb.print() << '\n' ;
}
}
Code: Select all
struct ring_buffer
{
ring_buffer(size_t cap) : buffer(cap) {}
bool empty() const { return sz == 0 ; }
bool full() const { return sz == buffer.size() ; }
void push( String str )
{
if(last >= buffer.size()) last = 0 ;
buffer[last] = str ;
++last ;
if(full())
first = (first+1) % buffer.size() ;
else ++sz ;
}
// String operator[] ( size_t pos )
// {
// auto p = ( first + pos ) % buffer.size() ;
// return buffer[p] ;
// }
String print() const {
if( first < last )
for( size_t i = first ; i < last ; ++i ) return (String)buffer[i] + "<br>";
else
{
for( size_t i = first ; i < buffer.size() ; ++i ) return (String)buffer[i] + "<br>";
for( size_t i = 0 ; i < last ; ++i ) return (String)buffer[i] + "<br>";
}
return String();
}
private:
std::vector<String> buffer ;
size_t first = 0 ;
size_t last = 0 ;
size_t sz = 0 ;
};
Do you have any advice on how to fix this ?
Thank you !