Searching for an int in a vector

This is a discussion on Searching for an int in a vector within the C++ Programming forums, part of the General Programming Boards category; Hi, I am needing to take a vector and search it for a certain integer. The goal: To search a ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    17

    Searching for an int in a vector

    Hi,

    I am needing to take a vector and search it for a certain integer.

    The goal:

    To search a vector and confirm or deny if a certain integer is there.

    The problem:

    I am having problems searching the vector. Here is what I have been trying to use to search the "bag" of numbers.

    Code:
    search (bag.begin(), bag.end(), match1);
    I have this part of my code below commented out so that the code will compile and run.


    So could somebody show me how to use this command for a vector? Or is this even the right command to be using or should I go about it a different way?







    Code:
    #include <iostream>
    #include <cstdlib>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    class Bag
    {
    	protected: 
    	vector<int> bag;
    	public:
    	Bag() {};
    	
    	bool isEmpty()
    	{
    		if (bag.empty())
    		{
    		cout << "Bag D is empty" << endl;	
    		}
    		else
    		{
    			cout << "Fail" << endl;
    		}
    		return 0;
    	};
    	
    	bool isElement(int x)
    	{
    		cout << "Enter a number to see if it's in the bag." << endl;
    		cin >> x;
    		
    		vector<int>::iterator it;
    		
    		
    		//int match1 = x;
                    //it = search (bag.begin(), bag.end(), match1);
    		
    		
    		
    		if (it!=bag.end())
    		{
                      cout << "match1 found at position " << int(it-bag.begin()) << endl;
                    }
            else
            {
              cout << "match1 not found" << endl;
    		}
    		return 0;
    	};
    	
    	void add(int x)
    	{
    		int y;
    		cout << "How many items would you like to put in the bag?" << endl;
    		cin >> y;
    		bag.resize(y);
    		cout << "Enter in " << y << " intergers." << endl;
    		for (int i=0; i<y; i++)
    		cin >> bag[i];
    		
    	};
    	
    	void list()
    	{
    		 cout << "Here's what's in the bag:" << endl;
    		 for (int i=0; i< bag.size(); i++)
    		 cout << bag[i] << endl;
    		
    	};
    	
    	void remove()
    	{
    		
    	};
    };
    
    
    int main()
    {
    	int x;
    	Bag D;
    	D.isEmpty();
    	D.add(x);
    	D.list();
    	
    	
    	return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    It sounds like you want to use std::find instead of std::search, e.g.,
    Code:
    if (find(bag.begin(), bag.end(), match1) != bag.end())
    {
        // match1 found
    }
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    17
    Thanks! I had seen that one and messed around with it too but couldn't get it to work. What's the difference between find and search?

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    Quote Originally Posted by go_loco
    What's the difference between find and search?
    std::find is used to find an element in the range that is equal to a particular value, or an element in the range for which a unary predicate evaluates to true.

    std::search is concerned with searching for the first match of a subrange of elements in the range.

    By the way, this is how I would define isElement:
    Code:
    bool isElement(int x) const
    {
        return std::find(bag.begin(), bag.end(), x) != bag.end();
    }
    The code that requests for input and reads it can be placed elsewhere, e.g., in the global main function. That code will call isElement on a Bag object. Notice also that isElement is declared const since it does not change the observable state of the Bag object.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Mar 2010
    Posts
    17
    Thanks guys I really appreciate the help!!

    I have one more question and I should be home free.

    I have a function called "remove" I am needing to search the vector and then remove that integer that the user wants removed.

    I found the std::remove function but the examples show removing of the xth element. Is it possible to have it actually remove a defined number? As in...remove the number 6 no matter where it is?

  7. #7
    Registered User
    Join Date
    Mar 2010
    Posts
    17
    EDIT:

    Hey, sorry I didn't see your post before I replied. I agree I would much rather put the prompts for filling the bag and what not in the main. However, the instructor wants us to prompt the user inside the function. I do like how you wrote that. Much easier. Much thanks!

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    Quote Originally Posted by go_loco
    I found the std::remove function but the examples show removing of the xth element. Is it possible to have it actually remove a defined number? As in...remove the number 6 no matter where it is?
    Use std::find to find the element, then use the erase() member function of std::vector<int> to remove it, if it exists. If you ever use std::remove in the future, note that you should still need to use the erase() member function.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Mar 2010
    Posts
    17
    hm.... so here is what I have of my remove function:


    Code:
    void remove(int x)
    	{
    		cout << "What integer would you like to remove from the bag?" << endl;
    		cin >> x;
    		
    		int match1 = x;
    		
    		 if (find(bag.begin(), bag.end(), match1) != bag.end())
            {
               bag.erase (bag.begin(), bag.end(), x);
            }
    		else
    		{
    		   cout << match1 << " not found. :( " << endl;	
    		}
    		
    	};
    It's throwing an error with my statement:

    Code:
    bag.erase (bag.begin(), bag.end(), x);
    Obviously I don't have that set up correctly. Am I close at all?

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    Yeah, you are referring to documentation on the interface of std::vector, right? Notice that there are two versions of the erase() member function: one takes an iterator denoting an element, the other takes two iterators denoting a range.

    What you need to do is to store the iterator returned by std::find in a variable, and then pass that iterator as the argument to erase().
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Mar 2010
    Posts
    17
    I apologize but I'm pretty new to C++ and I'm trying to learn stuff the prof. hasn't taught us yet. I understand an iterator to be like a pointer. So what your saying is that I need to create an iterator and then set that iterator equal to the value I just searched the vector for? Then in turn put that iterator in the std::remove function?

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    Quote Originally Posted by go_loco
    So what your saying is that I need to create an iterator and then set that iterator equal to the value I just searched the vector for?
    No, std::find returns an iterator to the element found. So, given that iterator, you can erase the corresponding element. Use the erase() member function, not std::remove.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Mar 2010
    Posts
    17
    Oh, ok. I think I get it. So no need to create one because it has already been created for me. I then just need to take that iterator that was just created by the std::find and place it into the erase() member function.

    Would you mind clarifying the erase function for me, as far as setting it up goes? I've seen things likse erase(bag. begin(), bag.end()). What I'm wanting to know is what these do. I don't know if you understand what I'm trying to ask.

    Kinda like....

    erase( the start of the vector, the end of the vector, value you want erased)

    something like that.

    Well I ended up kinda figuring it out. I couldn't find out where it stored the iterator when I searched for it. So I basically ended up searching for it again and then storing the results in a iterator I created called "it". Here's the segment of code.



    Code:
    void remove(int x)
    	{
    		cout << "What integer would you like to remove from the bag?" << endl;
    		cin >> x;
    		
    		 match1 = x;
    		
    		vector<int> :: iterator it;
    		 if (find(bag.begin(), bag.end(), match1) != bag.end())
            {
              it=find(bag.begin(), bag.end(), match1);
              bag.erase(it);
            }
    		else
    		{
    		   cout << match1 << " not found. :( " << endl;	
    		}
    		
    		
    		
    	};
    Last edited by go_loco; 04-20-2010 at 01:43 PM.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    Quote Originally Posted by go_loco
    Would you mind clarifying the erase function for me, as far as setting it up goes? I've seen things likse erase(bag. begin(), bag.end()). What I'm wanting to know is what these do.
    That version of erase() erases a range of elements from the vector.

    Quote Originally Posted by go_loco
    I couldn't find out where it stored the iterator when I searched for it. So I basically ended up searching for it again and then storing the results in a iterator I created called "it".
    To avoid finding the same thing twice, it should be something like this:
    Code:
    void remove(int x)
    {
        cout << "What integer would you like to remove from the bag?" << endl;
        cin >> x;
    
        vector<int>::iterator it = find(bag.begin(), bag.end(), x);
        if (it != bag.end())
        {
            bag.erase(it);
        }
        else
        {
            cout << x << " not found. :( " << endl;
        }
    }
    By the way, are you really supposed to have x as a parameter? Having x as a parameter does not make sense unless you do it my way. The way you are doing it now, according to your teacher's instructions, requires the caller to pass a value to the remove member function, but this value is completely ignored.
    Last edited by laserlight; 04-21-2010 at 01:22 AM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Feb 2010
    Posts
    38
    I feel like you can do erase(vector.begin()+n) a lot of the time.

    Edit: was totally thinking of something else :
    Last edited by nicoqwertyu; 04-22-2010 at 06:14 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Moving Average Question
    By GCNDoug in forum C Programming
    Replies: 4
    Last Post: 04-23-2007, 11:05 PM
  3. Game Won't Compile
    By jothesmo in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2006, 03:24 PM
  4. Converted from Dev-C++ 4 to Dev-C++ 5
    By Wraithan in forum C++ Programming
    Replies: 8
    Last Post: 12-03-2005, 06:45 AM
  5. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 12:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21