开发者

Track/Display Array Index As Part Of Cout (C++)

I have a command line C++ program that lets you enter basic information about a person (ID number, name, age, etc.) and I want to output to a console in the following manner:

-------------------------------------------------------------------
Index   ID #        First Name          Last Name           Age
-------------------------------------------------------------------
0       1234        John                Smith               25   

The person objects are stored in an array of Persons and I've overload the ostream (<<) operator to print out all of t开发者_开发技巧he fields like you see. The dashed lines and header come from a displayHdg() function. Anyhow, I have not been able to figure out how to get the proper index value for the array. Ideally, I'd like to generate the indices for each line, but all my attempts have failed. The array is looped through and each object printed in the main() function, and the ostream is overloaded in a person class, so I tried to use global variables as well as static variables, and all of those produce incorrect numbering (i.e. show 0, 1 the first time (for 2 objects), then change to 1, 2 on the next display). Any ideas?


Wouldn't this work? (formatting of ID field ommitted)

vector<Person> v;

for (int i = 0; i < v.size(); ++i)
  cout << i + 1 << v[i] << endl;

This starts indexing at 1.


EDIT:

OK now I see what you want. You want to find an element in the vector!

std::vector<person>::iterator p = 
          std::find(Persons.begin(), Persons.end(), element);

if( p != Persons.end() )
{
  std::cout << "index of element is: " << p-Persons.begin();
}

If you have the correct formating, you should be able to do the following:

for(size_t i = 0; i < Persons.size(); ++i)
{
  cout << i << '\t' << Persons[i] << endl;
}

I would recommend taking a look at the formatting facilities in brief in this post. Using setw, left, right... manipulators is better than doing it manually.


You need to use "find" algorithms to find exact index of Person object in vector < Person>.


You could use wrapper class to hold index and print it according to your formatting in operator<<:

// wrapper to hold index
template<typename T>
struct Ti
{
    Ti( size_t index, const T& t ) : index(index), val(t) {}
    size_t index;
    const T& val;
};

// you class
struct X
{
    friend ostream& operator<<( ostream& out, Ti<X>& t );
protected:
    int some_data;
};

// operator<< for X
ostream& operator<<( ostream& out, Ti<X>& t )
{
    out << "test " << t.index << "  " << t.val.some_data;
    return out;     
}

int main()
{
    vector<X> xxx;
    for ( size_t i =0; i < xxx.size(); ++i)
        cout << Ti<X>(i+1, xxx[i]) << endl;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜