Reputation: 35
/* [What I have done in the following code is running forever, what should I edit to get the desired difference between consecutive set elements?] */
using namespace std;
int main() {
int temp;
set <int> sett ;
set <int>:: iterator itr;
int n=5 ;
itr= sett.begin();
for (int i=0;i<n ; i++){
cin>> temp ;
sett.insert(temp);
}
for( itr = sett.begin();itr!=sett.end();itr++){
if(itr!=sett.end()){
cout << (*itr++)-(*itr) << " difference"<< endl ;
}
}
return 0;
}
Upvotes: 2
Views: 789
Reputation: 238411
Can the iterator of a set be used to find difference between two consecutive elements of the set, in c++?
Yes.
for( itr = sett.begin();itr!=sett.end();itr++){ // ^^^^^ if(itr!=sett.end()){ cout << (*itr++)-(*itr) << " difference"<< endl ; // ^^^^^
The problem here is that you increment the iterator twice, so you skip elements. furthermore, in case of iterator to last element, you end up indirecting through the iterator past the last element (i.e. the end iterator).
There is actually a standard algorithm for this. Its name is generally considered confusing, but in this use case, it is actually quite appropriate. Meet std::adjacent_difference
:
std::adjacent_difference(std::begin(sett), std::end(sett),
std::ostream_iterator<int>(std::cout, " difference\n"));
Upvotes: 1
Reputation: 1524
welcome to SO.
in order to get the last element of your set you've to create a temporary variable, pointing to that element.
An example would look like this:
std::set<int> elements{};
if(!elements.empty()) {
auto it = elements.begin();
const int* last_element{&*(it++)}; /* if elements would be empty this would be undefined behaviour */
while(it != elements.end()) {
const auto now = *it++;
const auto diff = last_element - now;
}
}
Upvotes: 1