return with for loop using class



  • ** `I am trying to write a class code which should give me bool value as return according as if condition.

    However, I am always getting false as return value. Would you please help me and find the mistake I have done in the following code?` **

    // prog: test 
    // command line: ./test --ped test.ped 
    /* 
    	*RESULT DISPLAYING:
    	t.find(--ped): 0
    	t.vec[0]: test
    	t.vec[1]: --ped
    	t.vec[2]: test.ped
    
    	* CORRECT RESULT would be 
    	t.find(--ped): 1
    	t.vec[0]: test
    	t.vec[1]: --ped
    	t.vec[2]: test.ped
    
    	*/
    
    #include<iostream>
    #include<vector>
    #include<string>
    
    using namespace std;
    
    class test {
    public: 
    		test(int, char**);
    		vector <string> vec;
    		bool find( string  s);
    
    };
    [quote]Thank you very much in Advance /[quote]
    int main( int argc, char** argv){ 
    
    	test t (argc, argv);
    	cout << "t.find(--ped): " << t.find("--ped") <<endl; 
            // it is always showing 0 I do not know why. 
    	// howwever the following code show me that --ped is there 
    	cout << "t.vec[0]: " << t.vec[0] <<endl;
    	cout <<"t.vec[1]: " << t.vec[1] <<endl;
    	cout <<"t.vec[2]: " << t.vec[2] <<endl;
    
    return 0;}
    
    test::test(int argc, char** argv){
    	vec.resize(argc);
    	for (int i=0;i<vec.size(); i++){ vec[i]=argv[i];}
    
    }
    
    bool test::find (string s){
    		for (int i=0;i<vec.size();i++) 
    		{
    		if((string(vec[i])==s))  return true; 
    		return false;
    		}
    	}
    

    Thak you very much in Advance!



  • bool test::find (string s){
    		for (int i=0;i<vec.size();i++) 
    		{
    		if((string(vec[i])==s))  return true; 
    		//return false;
    		}
                    return false;
    	}
    


  • return false; shouldn't be inside the loop.
    As it is now, the function will return false immediately if the first element is not a match and the remaining elements will never be checked.

    Note that this functionality is covered by std::find:
    http://www.cplusplus.com/reference/algorithm/find/

    Edit: too slow.



  • Thank you !!


Anmelden zum Antworten