Thread: Vector elements

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    50

    Vector elements

    I have a number and a vector;
    How can I check if a number is an element of a vector?
    Thank you

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Use the std::find algorithm.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Code:
    for (int i=0; i<vec.size(); ++i)
    {
       if (vec[i] == number)
       {
          cout << number << " is an element of vector." << endl;
          break;
       }
    }

  4. #4
    Registered User
    Join Date
    Dec 2004
    Posts
    50

    no vector size

    Is there any way that I could do it without a loop or vector size?

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Not really. My method avoids calling size() and has no visible loop, but it's just hidden.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Is there any way that I could do it without a loop or vector size?
    Use find() from header <algorithm> like CornedBee suggested.

Popular pages Recent additions subscribe to a feed