3

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;
    }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Jee
  • 35
  • 5

1 Answers1

5

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Could you please explain the logical concept of the boolean variable? when it becomes true? – Jee Jul 15 '22 at 12:23
  • @Jee Initially before the first iteration it is set to true. And then after the first iteration of the loop it is equal to false. – Vlad from Moscow Jul 15 '22 at 12:24