user1010563
user1010563

Reputation:

C++ How to iterate through a std::vector of objects and show content on console

For loop should iterate through std::vector and populate content.

First for loop gives me an error message saying:

NO BINARY OPERATOR FOUND << No convert possible

vector<MyClass>classVector;
    for (vector<MyClass>::iterator i = classVector.begin();
                           i != classVector.end();
                           ++i)
            {
                cout << *i << endl;
            }

MyClass.h:

class MyClass{

private:

    string newTodayTaskString;

public:
    MyClass(string t) : newTodayTaskString (t){}

    ~MyClass(){}
};

This for loop iterates through a vector of strings and works perfectly. Why?

vector<string>stringVector;
   for (vector<string>::iterator i = stringVector.begin(); 
                         i != stringVector.end(); 
                         ++i) 
            {
                cout<<*i<<endl;
            }

Upvotes: 3

Views: 10296

Answers (5)

Praveer Kumar
Praveer Kumar

Reputation: 1008

you are iterating through the vector of "MyClass", which is perhaps a user-defined type.So you must tell the compiler, in which data of "MyClass" class you are interested in. Below is a sample code- just for understanding purpose

// Temp_Practice.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<memory>
#include<ostream>
#include <vector>>
using namespace std;

// This example is just for understanding/Demo purpose.
// it will not run on any compiler
class MyClass {
public:
    std::string _name;
    std::string _address;
    int         _age;
    // Constructor
public:
    MyClass() {}
    MyClass(std::string name, std::string address, int age) :_name(name), _address(address), _age(age) {}

    //Destructor
    //..

    // other stuff
    friend ostream& operator << (ostream& os, std::string _input);

};
 ostream& operator << (ostream& os, std::string _input)
{
     os << _input.c_str();
     return os;
}

int main()
{
    std::vector<MyClass> vecMyClass;

    MyClass temp("AA", "BB", 1);
    vecMyClass.push_back(temp);

    MyClass temp1("CC", "DD", 2);
    vecMyClass.push_back(temp1);

    MyClass temp2("EE", "FF", 3);
    vecMyClass.push_back(temp2);

    MyClass temp3("GG", "HH", 4);
    vecMyClass.push_back(temp3);

    MyClass temp4("II", "JJ", 5);
    vecMyClass.push_back(temp4);

    MyClass temp5("KK", "LL", 6);
    vecMyClass.push_back(temp5);
    std::vector<MyClass>::iterator itr;
    for ( itr = vecMyClass.begin(); itr != vecMyClass.end(); ++itr)
    {
        // Compiler throws error; it does not know what programer wants to print. So its 
        // programer responsiblity to let compiler know what to be printed
         //std::cout << itr << std::endl; //  Error!!!!

        // Correct Code
        std::cout << itr->_name << itr->_address << itr->_age << std::endl;
    }
    return 0;
}

Upvotes: 1

Philipp
Philipp

Reputation: 11814

The question is unrelated to iteration, it's just because you can write

std::string s = "Hello";
std::cout << s;

but not

MyClass o("Hello");
std::cout << o;      

See How to properly overload the << operator for an ostream? on how to overload operator << to make it work!

Upvotes: 5

ForEveR
ForEveR

Reputation: 55887

You should overload output operator.

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

class MyClass{

private:
    std::string newTodayTaskString;

public:
    explicit MyClass(const std::string t) : newTodayTaskString (t){}
    std::ostream& print(std::ostream& os) const { return os << newTodayTaskString; }

    ~MyClass(){}
};

std::ostream& operator << (std::ostream& os, const MyClass& obj)
{
    return obj.print(os);
}

int main()
{
    std::vector<MyClass> vec = {MyClass("add"), MyClass("clear")};
    std::copy(vec.begin(), vec.end(), std::ostream_iterator<MyClass>(std::cout, "\n"));
}

Upvotes: 0

huysentruitw
huysentruitw

Reputation: 28091

I think you want to print a member of the class, not the class itself.

For example:

cout << (*i).Name << endl; 

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258568

You need to overload the stream operator for your class if you want to be able to directly call std::cout::operator <<.

You can either define it as:

 std::ostream& operator << (std::ostream& stream, const MyClass& obj)
 {
    stream << obj.newTodayTaskString;
 }

and declare this operator as friend so it has access to the private members of the class or provide a print function to your class and use that instead.

Upvotes: 3

Related Questions