Get an unsigned int milliseconds out of chrono::duration - c++11

For a winapi wrapper I want to use chrono for a duration given to the call. The code example:
bool setTimer(std::chrono::duration<std::chrono::milliseconds> duration)
{
unsigned int dwDuration = Do some chrono magic here
SetTimer(m_hWnd,1,dwDuration,0);
}
dwDuration has to be in milliseconds.
First question: How do to the magic.
Second question: Is the parameter declaration okay?

The name of the type is std::chrono::milliseconds, and it has a member function count() that returns the number of those milliseconds:
bool setTimer(std::chrono::milliseconds duration)
{
unsigned int dwDuration = duration.count();
return std::cout << "dwDuration = " << dwDuration << '\n';
}
online demo: http://coliru.stacked-crooked.com/a/03f29d41e9bd260c
If you want to be ultra-pedantic, the return type of count() is std::chrono::milliseconds::rep
If you want to deal with fractional milliseconds, then the type would be std::chrono::duration<double, std::milli> (and the return type of count() is then double)

You can use the following code:
auto now = chrono::high_resolution_clock::now();
auto timeMillis = chrono::duration_cast<chrono::milliseconds>(now.time_since_epoch()).count();

Related

Confused why it got solved by using friend function

I have this question in assignment.
Question:
Implement + and - operators for the Date class where u give dates using constructor and also give and additional n value. Now we have to use operator + and operator - to change the previously taken date by n value.
I have done this and it given an error: operator+(Date&, int) must take either zero or one argument
class Date
{
int day;
int month;
int year;
public:
Date(int d,int m,int y)
{
day=d;
month=m;
year=y;
}
Date operator-(Date &x,int y)
{
return Date(x.day-y, x.month, x.year);
}
Date operator+(Date &x,int y)
{
return Date(x.day+y, x.month, x.year);
}
void display()
{
cout<<"Date:"<<day<<"-"<<month<<"-"<<year<<endl;
}
};
After i searched in web and found this:
class Date{
private:
int day;
int mth;
int year;
public:
Date(int a,int b,int c){
day = a;
mth = b;
year = c;
}
friend Date operator +(Date &,int);
friend Date operator -(Date &,int);
void print(void){
cout <<"Date: " << day << " - " << mth << " - " << year << endl;
}
};
Date operator +(Date& a,int n){
Date d(a.day+n,a.mth,a.year);
return(d);
}
Date operator -(Date& a,int n){
Date d(a.day-n,a.mth,a.year);
return(d);
}
My Doubt: Both are same but he used friend function and it got solved. In both cases the operator overloading function is same and error is also pointing towards the function. How this friend function solved the issue or anything wrong in my Operator overload function?
In the first code snippet, the operator functions are member functions, so they should be operator+(int) instead of operator+(Date&, int), since the first argument of type Date & is implicit.
In the second code snippet, the operator functions aren't member functions, so you need a friend qualifier to access the private members of Date.

c++ : unordered map with pair of string_viewes

Here is a code snippet I have :
struct PairHasher {
size_t operator()(const std::pair<std::string_view, std::string_view>& stop_stop) const {
return hasher(stop_stop.first) + 37*hasher(stop_stop.second);
}
std::hash<std::string_view> hasher;
};
BOOST_FIXTURE_TEST_CASE(unordered_map_string_view_pair_must_be_ok, TestCaseStartStopMessager)
{
const std::vector<std::string> from_stops = {"from_0", "from_1", "from_2"};
const std::vector<std::string> to_stops = {"to_0", "to_1", "to_2"};
std::unordered_map<std::pair<std::string_view, std::string_view>, std::int32_t, TransportCatalogue::PairHasher> distance_between_stops;
for ( std::size_t idx = 0; idx < from_stops.size(); ++idx) {
std::cout << from_stops[idx] << " : " << to_stops[idx] << std::endl;
distance_between_stops[std::pair(from_stops[idx], to_stops[idx])] = idx;
}
std::cout << "MAP CONTENT :" << std::endl;
for (auto const& x : distance_between_stops)
{
std::cout << x.first.first << " : " << x.first.second << std::endl;
}
}
I expect to see 3 pairs inside the container, but there is only 1 concerning to the output :
MAP CONTENT :
from_2 : to_2
So, where are two more pair lost? What am I doing wrong?
Moving my comment to an answer.
This is pretty sneaky. I noticed in Compiler Explorer that changing:
distance_between_stops[std::pair(from_stops[idx], to_stops[idx])] = idx;
to
distance_between_stops[std::pair(std::string_view{from_stops[idx]}, std::string_view{to_stops[idx]})] = idx;
fixes the bug. This hints that the problem lies in some implicit string -> string_view conversion. And indeed that is the case, but it is hidden behind one extra layer.
std::pair(from_stops[idx], to_stops[idx]) creates a std::pair<std::string, std::string>, but distance_between_stops requires a std::pair<std::string_view, std::string_view>. When we insert values into the map, this conversion happens implicitly via overload #5 here:
template <class U1, class U2>
constexpr pair(pair<U1, U2>&& p);
Initializes first with std::forward<U1>(p.first) and second with std::forward<U2>(p.second).
This constructor participates in overload resolution if and only if std::is_constructible_v<first_type, U1&&> and std::is_constructible_v<second_type, U2&&> are both true.
This constructor is explicit if and only if std::is_convertible_v<U1&&, first_type> is false or std::is_convertible_v<U2&&, second_type> is false.
(For reference, std::is_constructible_v<std::string_view, std::string&&> and std::is_convertible_v<std::string&&, std::string_view> are both true, so we know this overload is viable and implicit.)
See the problem yet? When we use the map's operator[], it has to do an implicit conversion to create a key with the proper type. This implicit conversion constructs a pair of string_views that are viewing the temporary memory from the local pair of strings, not the underlying strings in the vector. In other words, it is conceptually similar to:
std::string_view foo(const std::string& s) {
std::string temp = s + " foo";
return temp;
}
int main() {
std::string_view sv = foo("hello");
std::cout << sv << "\n";
}
Clang emits a warning for this small example, but not OP's full example, which is unfortunate:
warning: address of stack memory associated with local variable 'temp' returned [-Wreturn-stack-address]
return temp;
^~~~

How do you perfectly hash a union of a possibly unicode char with a 32-bit integer?

I've never really had the need to create hash function before but right now it seems like the best solution for this.
I haven't tried anything, but I guess what I would try first is to hash take the unicode integer as the least significant 32-bits of a long. Then in the most significant 32-bits, store the integer.
struct Symbol
{
private:
enum Type {
Terminal,
Variable,
}
union {
char m_term;
int m_var;
}
Type m_type;
public:
this(char term) {
m_type = Type.Terminal;
m_term = term;
}
this(int var) {
m_type = Type.Variable;
m_var = var;
}
}
Symbol is the struct I'd like to hash. It contains a union which we should hash to achieve this. Was just wondering if my approach above is correct.
Thanks to commenters.
bool opEquals(Symbol sym) const {
if (m_type == Type.Terminal)
return m_term == sym.m_term;
else
return m_var == sym.m_var;
}
ulong toHash() {
ulong bit = m_type;
ulong key;
if (m_type == Type.Terminal)
key = cast(ulong) m_term;
else
key = m_var;
return bit | (key << 1);
}

feeding a stringstream to a class member function

I am a newbie trying to learn by doing. I want to feed a stringstream into a class member function called "print()" but I get errors. Once this works, I can proceed to write more class member functions that work with the data I feed them.
For now I have created a class that has a member function 'print'.
class Month
{
public:
string m_month;
void print()
{
cout << m_month << endl;
}
};
Next, I initialized 12 months:
Month month1 = { "January" };
Month month2 = { "February" };
Month month3 = { "March" };
etc.
When I call "month1.print();" it prints January which is correct.
I used stringstream and a for loop to concatenate month + 1 to 12 and I want to feed the stringstream to the print function.
stringstream os;
string mValue = "month";
int iValue = 1;
for(int i = 0; i < 12; ++i)
{
os << mValue << "" << iValue << "\n";
iValue += 1;
}
However, the stringstream can't be combined with the print function.
os.print(); and os.str().print();
result in "error: ‘std::stringstream {aka class std::__cxx11::basic_stringstream}’ has no member named ‘print’"
Converting the stringstream to char and then feeding it into the print function results in "error: request for member ‘print’ in ‘cstr’, which is of non-class type ‘const char*’"
const string tmp = os.str();
const char* cstr = tmp.c_str();
cstr.print();
Long story short: What I am trying to do is concatenate month + 1 to 12 and feed that to the class member function "print". This seems trivial but I can't get it to work. Any suggestions?
Edit: Full code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Month
{
public:
string m_month;
void print()
{
cout << m_month << endl;
}
};
int main()
{
Month month1 = { "January" };
Month month2 = { "February" };
Month month3 = { "March" };
Month month4 = { "April" };
Month month5 = { "May" };
Month month6 = { "June" };
Month month7 = { "July" };
Month month8 = { "August" };
Month month9 = { "September" };
Month month10 = { "October" };
Month month11 = { "November" };
Month month12 = { "December" };
stringstream os; // Initialize stringstream "os"
string mValue = "month"; // Initialize mValue "month"
int iValue = 1; // Initialize iValue "1"
for(int i = 0; i < 12; ++i)
{
os << mValue << "" << iValue << "\n"; // Glue mValue and iValue
// together
iValue += 1; // Increment iValue by one
}
send stringstream "os" to the print function // mock code: Here I want to send month1.print(); month2.print(); etc. to the print function. The output should be January, February etc.
return 0;
}
This doesn't do what you think it does:
for(int i = 0; i < 12; ++i)
{
// iValue is actually unnecessary. You could have just used (i + 1)
os << mValue << "" << iValue << "\n";
iValue += 1;
}
All this does is fill the stringstream with the string:
"month1\nmonth2\nmonth3\nmonth4\nmonth5\nmonth6\nmonth7\nmonth8\nmonth9\nmonth10\nmonth11\nmonth12"
Your intent seemed to be to concat a number to the end of a "month" string, and have them act as the month1, month2... variables that you defined above. That's not how it works. You can't (and shouldn't) try to "dynamically" reference variables like that. In os.print();, the stringstream doesn't act as Month simply because it contains a string with the same name as a Month variable.
Instead, add the variables to some kind of container (like a std::vector), and loop over it:
std::vector<Month> months{ month1, month2, month3, ..., month12 }
for (unsigned int i = 0; i < months.size(); i++)
{
months[i].print();
}
A stringstream should be thought of as a stream like any other, except that it happens to be text and held in memory. So it's cheap to convert it to a string, and in fact they are often used for building strings.
But a "Print" method of a class has no business knowing that a stream is a stringstream. All it should care is that it gets a stream which is text, and is input. In fact the former is a bit hard to enforce due to historical weaknesses stretching back a long way. If you just read the stream byte by byte, pass to std::cout, and terminate on EOF then that's probably OK.

What Time Is This Returning

Deep in the sauce here. I haven't worked with time to much so I'm a little confused here. I know there is FILETIME and SYSTEMTIME. What I am trying to get at this point (because it might change) are file that are less than a 20 seconds old. This returning the files and their size and something in seconds, What I'd like to know is where it is filtering by time if it is, and how can I adjust it to suit my needs. Thank you.
using namespace std;
typedef vector<WIN32_FIND_DATA> tFoundFilesVector;
std::wstring LastWriteTime;
int getFileList(wstring filespec, tFoundFilesVector &foundFiles)
{
WIN32_FIND_DATA findData;
HANDLE h;
int validResult=true;
int numFoundFiles = 0;
h = FindFirstFile(filespec.c_str(), &findData);
if (h == INVALID_HANDLE_VALUE)
return 0;
while (validResult)
{
numFoundFiles++;
foundFiles.push_back(findData);
validResult = FindNextFile(h, &findData);
}
return numFoundFiles;
}
void showFileAge(tFoundFilesVector &fileList)
{
unsigned _int64 fileTime, curTime, age;
tFoundFilesVector::iterator iter;
FILETIME ftNow;
//__int64 nFileSize;
//LARGE_INTEGER li;
//li.LowPart = ftNow.dwLowDateTime;
//li.HighPart = ftNow.dwHighDateTime;
CoFileTimeNow(&ftNow);
curTime = ((_int64) ftNow.dwHighDateTime << 32) + ftNow.dwLowDateTime;
for (iter=fileList.begin(); iter<fileList.end(); iter++)
{
fileTime = ((_int64)iter->ftLastWriteTime.dwHighDateTime << 32) + iter->ftLastWriteTime.dwLowDateTime;
age = curTime - fileTime;
cout << "FILE: '" << iter->cFileName << "', AGE: " << (_int64)age/10000000UL << " seconds" << endl;
}
}
int main()
{
string fileSpec = "*.*";
tFoundFilesVector foundFiles;
tFoundFilesVector::iterator iter;
int foundCount = 0;
getFileList(L"c:\\Mapper\\*.txt", foundFiles);
getFileList(L"c:\\Mapper\\*.jpg", foundFiles);
foundCount = foundFiles.size();
if (foundCount)
{
cout << "Found "<<foundCount<<" matching files.\n";
showFileAge(foundFiles);
}
system("pause");
return 0;
}
I don't know what you've done to try to debug this but your code doesn't work at all. The reason is you're passing getFileList() a wstring but then passing that to the ANSI version of FindFirstFile(). Unless you #define UNICODE or use the appropriate compiler option, all system calls will expect char *, not UNICODE.
The easiest fix is to simply change the declaration of getFileList() to this:
int getFileList(const char * filespec, tFoundFilesVector &foundFiles)
Change the call to FindFirstFile() to this:
h = FindFirstFile((LPCSTR)filespec, &findData);
And then change the calls to it to this:
getFileList("c:\\Mapper\\*.txt", foundFiles);
getFileList("c:\\Mapper\\*.jpg", foundFiles);
Your other option is to switch all char strings to wide chars, but either way you need to be consistent throughout. Once you do that the program works as expected.
As for your final question, your program is not filtering by time at all.
Not quite an answer, but you might want to read about file system tunneling.
It may prevent you from what you're trying to do in some situations.

Resources