cruxi cruxi - 3 months ago 10
C++ Question

C++ pointer, reference and function call

I am really new to C++ and I am a bit confused about pointers, adresses and function calls in C++.

I have the following function call:

config.pages= avail_pages(config.books_path, &config.books.front());


the config class has multiple
std::vectors<uint16_t>
, e.g.
config.books
holds the book ids (which are the file names from books_path).

Now I want to get the available pages of the first book (every page is a file). Therefore, avail_pages shall look for the files in books_path and for the first book.

A valid path to book 1234 and page 12 looks like this: books_path/1234/12

std::vector<uint16_t> avail_pages(std::string books_path, uint16_t* book) {

std::vector<uint16_t> pages;

std::string first_book;
first_book = books_path + std::to_string(*book); //pointer or not? string concatenation?
boost::filesystem::path p(first_book);

for (auto i = boost::filesystem::directory_iterator(p); i != boost::filesystem::directory_iterator(); i++)
{
std::string s = i->path().filename().string();
pages.push_back(std::stoi(s));
}
return pages;
}


The question is: if I use the vector function front() it returns a reference to the first element.


  1. Do I call it like this:
    &config.books.front()
    ?

  2. How do I pass the reference to a function? Do I have to use a pointer, like this:
    std::vector<uint16_t> avail_pages(std::string books_path, uint16_t* book)
    ?

  3. How can I access the actual value and cast it from an integer to a
    string?



At the moment I am getting an error at the function call for the front() function which shows that I didnt understand the reference/ pointer thing.
Thanks in advance!

Answer

It'd be better if you provided definitions of config and books. This being said, you need to understand than the vector function front() returns a reference to the front object held by the vector, this means you will typically call a class member after front. Consider this :

class book
{
public :
std::string books_path;
uint16_t book_id;
};
std::vector <book> config;
//your declared function :
std::vector<uint16_t> avail_pages(std::string books_path, uint16_t* book);
//you'd call this as such :
avail_pages(config.front().books_path, &config.front().book_id);