for loop not working as i wished
i'm currently a student learning programming and i have a part of the for loop where i couldn't get the output as i wanted = (
Code:
a[0] = aaa
a[1] = bbb
I'm actually iterating through a vector searching for a string.
void print() {
cout<<"Advisor name = "<<getName()<<endl;
for(int i = 0;i<a.size();i++)
{
if (a[i].getName() == b)
{
a[i].print();
break;
}
else
{
cout<<"There is no such advisor"<<endl;
}
/
}
if i key in aaa or bbb, my expected out put should key out aaa or bbb
but if i key in anything else, it would give and output of There is no such advisor
i can't seem to be able to figure out how to fix the coding part :(
anyone mind guiding me ??
Re: for loop not working as i wished
We have not enough information to help you.
What is a? What kind of variable is? How did you initialize it?
What is getName()? How is it implemented? What does it return?
Please post a small but complete piece of code that we can look at.
+ clearly describe your problem.
Re: for loop not working as i wished
sry for not being specific...
Code:
"a" is actually a vector of strings and "b" is a variable used to store another string that i key in
string getName() {
return name;
}
template <typename A , typename B>
void search_name(A a,B b){
for(int i = 0;i<a.size();i++)
{
if (a[i].getId() == b)
{
a[i].print();
break;
}
else
{
cout<<"There is no such advisor"<<endl;
}
break;
}
}
{
string search_name;
cout<<"Enter the name of the advisor you want to search for = ";
cin>>search_name;
sor.search_name(advisors,search_name);
}
"advisors" is the name of the vector
getName() is actually a method in a class i created
Re: for loop not working as i wished
Quote:
Originally Posted by
kahjun
i'm currently a student learning programming and i have a part of the for loop where i couldn't get the output as i wanted = (
First, re-edit your post so that the formatting of your code is not so messed up.
Second, it would help if you posted all of the code, and not bits and pieces.
Third, searching for a value in a vector can be accomplished by std::find_if().
Code:
#include <vector>
#include <algorithm>
#include <iostream>
struct foo
{
int someNumber;
int getNumber() const { return someNumber; }
foo(int num) : someNumber(num) { }
void print() { std::cout << someNumber << "\n";}
};
struct NumberFinder
{
NumberFinder(int num) : someNumber(num) { }
bool operator()(const foo& theFoo) { return theFoo.getNumber() == someNumber; }
int someNumber;
};
using namespace std;
int main()
{
vector<foo> a;
//...
a.push_back(foo(1));
a.push_back(foo(20));
a.push_back(foo(15));
a.push_back(foo(12));
vector<foo>::iterator it = find_if( a.begin(), a.end(), NumberFinder(15));
if ( it != a.end() )
// number was found
it->print();
}
The above example finds the object in the vector that has the number 15. This is not much different than what you need to do.
Regards,
Paul McKenzie