Reputation: 445
I have two classes, I'll call them "foo" and "bar". "foo" has two public members: (a string for its name and a vector of type "bar").
class bar {
//not important
};
class foo {
public:
std::string fooName;
std::vector<bar> bars;
}
If I have an element of bars, how can I access and print its corresponding fooName? I'm thinking about something along these lines, but I don't know how to fill in the blank:
std::cout << bars[index].__________.fooName;
When I try googling an answer, I can only find people asking about accessing private members of other classes.
Upvotes: 3
Views: 225
Reputation: 5503
So I'm not totally sure if this is what you're after but if your foo
object contains the collection of bar
objects then you should know which foo
objects name to print.
struct Bar
{ std::string name; };
struct Foo
{
Foo( std::string fooName )
: name{ std::move( fooName ) } { }
void AddBar( Bar bar )
{ bars.push_back( std::move( bar ) ); }
bool Contains( std::string_view barName ) const
{
return ( std::find_if( std::begin( bars ), std::end( bars ),
[ &barName ]( const Bar& bar ) {
return bar.name.compare( barName ) == 0;
}) != std::end( bars ) );
}
std::string name;
std::vector<Bar> bars;
};
int main( )
{
Foo foo{ "North America" };
foo.AddBar( { "New York" } );
foo.AddBar( { "LA" } );
foo.AddBar( { "Toronto" } );
foo.AddBar( { "Seattle" } );
foo.AddBar( { "BC" } );
foo.AddBar( { "Winnipeg" } );
// Check if a single foo instance contains the city.
if ( foo.Contains( "Toronto" ) )
std::cout << "City: Toronto Continent: " << foo.name << '\n';
Foo foo2{ "South America" };
foo2.AddBar( { "Lima" } );
foo2.AddBar( { "Santiago" } );
foo2.AddBar( { "Salvador" } );
foo2.AddBar( { "Fortaleza" } );
foo2.AddBar( { "Quito" } );
std::vector<Foo> foos{ std::move( foo ), std::move( foo2 ) };
// Check if any foo instance contains a specific city.
const std::string cityName{ "Toronto" };
auto it{ std::find_if( std::begin( foos ), std::end( foos ),
[ &cityName ]( const Foo& foo ) { return foo.Contains( cityName ); } ) };
if ( it != std::end( foos ) )
std::cout << "Continent: " << it->name << '\n';
}
Upvotes: 1