# Getting Record entries

I have a class Record which keeps entries of strings(implemented using vector of strings). I want to keep the data member private to the class. To get entries, I have defined a member function get_entry which accepts a reference to vector of strings to store results.

Below is the code.

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

class Record {
public:
{
static int seq = 1;
entries.push_back(std::to_string(seq++) + " "+ entry);
}
void get_entry(std::vector<std::string>& res) const
{
for (auto &v: entries)
res.push_back(v);
}

private:
std::vector<std::string> entries;
};

int main()
{
Record name;
std::vector<std::string> res;
name.get_entry(res);
for (auto &v : res)
std::cout << v << "\n";
return 0;
}


Are there other better ways to get entries from such a class? I don't want to make entries data member public and access it directly.

The obvious downside of your current approach is that you do a lot potentially unnecessary copying. One common solution is to return (const) iterators to the entries, i.e.,:

class Record
{
public:
// ...

auto cbegin() const { return entries.cbegin(); }
auto cend() const { return entries.cend(); }

// Perhaps similar methods for getting non-const iterators ...
};


This solution allows you to use e.g., standard algorithms on the entries, but you can't manipulate the underlying range from the outside (due to const-ness).

To support your earlier use case, you can still do std::vector<std::string> res(r.cbegin(), r.cend()); if you wish, where r is an object of type Record.

Just return entries by value. It will make a deep copy automatically:

std::vector<std::string> get_entries() const
{
return entries;
}