Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Don't print space after last value with iterator

I’m having a problem with a beginner concept
in competitive programming extra space in print may cause wrong answer judgment
I want to iterate through a container like map or set but last value should not have a space

#include <iostream>
#include <set>

using namespace std;

int main()
{
    set<int> st = {1,2,3};
    for(auto x : st){
        cout<<x<<" ";
    }
    return 0;
}

why can’t I do this

set<int> st = {1,2,3};
    for(auto x = st.begin(); st!=end();x++){
        if(x!=st.end()-2) cout<<x<<" ";
        else cout<<x;
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The standard class templates std::set and std::map do not have random access iterators. So this expression

x!=st.end()-2

is invalid.

If you compiler supports C++ 20 then you may write for example

set<int> st = {1,2,3};
for( size_t i = 0; auto x : st){
    if ( i++ != 0 ) std::cout << ' ';
    cout << x ;
}

Or you could use a boolean variable instead of the variable i with the type size_t.

In any case you can declare the variable before the range-based for loop as for example

set<int> st = {1,2,3};
bool first = true;
for( auto x : st){
    if ( !first ) 
    { 
        std::cout << ' ';
    }
    else
    {
        first = false;
    }   
    cout << x ;
}

If to use an ordinary for loop with iterators then you can write

for ( auto it = st.begin(); it != st.end(); it++)
{
    if ( it != st.begin() ) std::cout << ' ';
    std::cout << *it;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading