STL find. Inne działanie niż opis

0
 
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {
  int myints[] = { 10, 20, 30 ,40 };
  int * p;

  // pointer to array element:
  p = find(myints,myints+4,33);
  cout << *p << endl;

  vector<int> myvector (myints,myints+4);
  vector<int>::iterator it;

  // iterator to vector element:
  it = find (myvector.begin(), myvector.end(), 33);
  cout  << *it << endl;

  return 0;
}

http://ideone.com/9VPBDu

u mnie na kompie pokazuje mi (GCC)
33
śmieci

na ideone pokazuje
śmieci
0

a według tego http://www.cplusplus.com/reference/algorithm/find/

powinno w obu przypadkach zwrócić 40

WTF?

1

Nie, zwraca last, czyli myints+4 czyli element poza tablicą.
to:
p = find(myints,myints+3,33);
zwróci 40.

0

nie zauważyłem tego. Rzeczywiście. A przykład brałem z http://www.cplusplus.com/reference/algorithm/find/ :D

0

@_13th_Dragon a jeszcze takie pytanie
http://ideone.com/RviCGF tutaj wychodze po za zakres i znajduje 40. OK
http://ideone.com/RY8MT2 tutaj nie wychodze po za zakres i nie znajduje 40 :o (wyświetla śmieci)
http://ideone.com/f5h7dN tutaj nie znajduje (i prawidłowo) i wyświetla 0 a nie 20 (ani śmieci). Jak to w końcu jest?

1

Bo działasz na wektorze, a wektor już NIE MA tej 40 za końcem.

  vector<int> myvector (myints,myints+4); // ma tą 40-tkę
  vector<int>::iterator it; 
  it = find (myvector.begin(), myvector.end()-1, 40); // szukamy bez 40-ki
  cout <<  *it << endl;

lub:

  vector<int> myvector (myints,myints+4);
  vector<int>::iterator it; 
  it = find (myvector.begin(), myvector.end(), 666);
  if(it==myvector.end()) cout<<"nie znaleziono"<<endl;
  else cout <<  *it << endl;

1 użytkowników online, w tym zalogowanych: 0, gości: 1