Computing desk | ||
---|---|---|
< June 29 | << May | June | Jul >> | Current desk > |
Welcome to the Wikipedia Computing Reference Desk Archives |
---|
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages. |
Well, I don't know whether this is correct forum. But I tried Stack Overflow and they told me to read references and pointed to my bad coding practices but did not answer actual question. Problem is thaat arr.end() is behaving weirdly. Usual behaviour is that it should point after the last element, which it does before entering into if condition. But after if statements (and deletions inside it) it points to last element which is giving problems. ALso, I know dereferencing end() is undefined, but it actually is giving me last element which is weird, and I want to fix it and learn from it
[1]link to original question
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
ll N,K;
cin >>N >>K;
vector<ll> arr(N);
for(ll i=0;i<N;++i){
cin>>arr[i];
}
sort(arr.begin(),arr.end());
ll cnt=0;
auto itr = arr.begin();
auto temp = arr.begin()+1;
cout<<*arr.end();
while(temp!=arr.end() && arr.size()!=2 && arr.size()!=3){
cout<<" "<<*arr.end()<<" ";
if(*temp >= *itr + K ){
temp = arr.erase(temp);
itr = arr.erase(itr);
++cnt;
cout<<*arr.end()<<" ";
}
else{
++temp;
}
}
cout<<cnt;
}
2409:408D:4E99:46F1:B8F9:E360:B91A:14FF (talk) 2409:408D:4E99:46F1:B8F9:E360:B91A:14FF (talk) 10:15, 30 June 2023 (UTC)
arr.end()
is _not_ an iterator to the end of the array; it's an iterator to one-past-the-end-of-the array. It's illegal to deference ::end()
LongHairedFop (talk) 18:28, 1 July 2023 (UTC)end()
is not necessarily giving you the last element here; it might be, for example, that for whatever reason the vector is being represented in memory with the last element duplicated, and you're seeing that duplicate. I don't know why that would be faster, but it's hard to exclude that there could be a reason. In any case you just are not supposed to do that. --Trovatore (talk) 17:44, 7 July 2023 (UTC)