Home > Blockchain >  Don't print space after last value with iterator
Don't print space after last value with iterator

Time:07-16

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;
    }

CodePudding user response:

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;
}
  • Related