#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <random>
#include <iterator>
#include <experimental/filesystem>
using namespace std;
namespace fs = experimental::filesystem;
void fill_random(vector<char>& data)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 255);
generate(data.begin(), data.end(), [&]{ return dis(gen); });
}
int main()
{
vector<char> content(318);
fill_random(content); // для чистоты эксперимента
vector<char> content_copy;
if(fs::exists("temp"))
{
cout << "delete temp dir\n";
fs::remove_all("temp");
}
fs::create_directory("temp");
cout << "create temp dir\n";
if(auto file = ofstream("temp/file", ios_base::binary); file)
{
file.write(content.data(), content.size());
cout << "write " << content.size() << " bytes\n";
}
if(fs::exists("temp/file"))
{
cout << "create copy..." << "\n";
fs::copy_file("temp/file", "temp/file_copy");
}
if(fs::file_size("temp/file") == fs::file_size("temp/file_copy"))
{
auto file = ifstream("temp/file_copy", ios_base::binary);
content_copy.resize(fs::file_size("temp/file_copy"));
file.read(content_copy.data(), content_copy.size());
}
auto eq = memcmp(content.data(), content_copy.data(), content.size());
if(eq == 0)
{
cout << "temp/file eq temp/file_copy\n"
<< "file size == " << fs::file_size("temp/file") << "\n"
<< "file_copy size == " << fs::file_size("temp/file_copy") << endl;
}
if(auto text_file = ofstream("temp/text_file"); text_file)
{
copy(content.begin(), content.end(), ostream_iterator<char>(text_file));
}
if(fs::file_size("temp/file") == fs::file_size("temp/text_file"))
{
cout << "temp/file eq temp/text_file\n";
}
else
{
cout << "Surprise\n"
<< R"(fs::file_size("temp/file") == )" << fs::file_size("temp/file") << "\n"
<< R"(fs::file_size("temp/text_file") == )" << fs::file_size("temp/text_file") << endl;
}
cin.get();
}
Windows не POSIX.
Binary and text modes
A text stream is an ordered sequence of characters composed into lines (zero or more characters plus a terminating '\n'). Whether the last line requires a terminating '\n' is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert \n to \r\n on output, and convert \r\n to \n on input)
Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if all of the following is true:
the data consist only of printing characters and the control characters \t and \n (in particular, on Windows OS, the character '\0x1A' terminates input)
no \n is immediately preceded by a space character (space characters that are written out immediately before a \n may disappear when read)
the last character is \n
A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equals to the data that were earlier written out to that stream. Implementations are only allowed to append a number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state.
POSIX implementations do not distinguish between text and binary streams (there is no special mapping for \n or any other characters)
template<typename _CharT, typename _Traits>
inline basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s)
{
if (!__s)
__out.setstate(ios_base::badbit);
else
__ostream_insert(__out, __s,
static_cast<streamsize>(_Traits::length(__s)));
return __out;
}
Writes count characters to the output sequence from the character array whose first element is pointed to by s. The characters are written as if by repeated calls to sputc(). Writing stops when either count characters are written or a call to sputc() would have returned Traits::eof().
const char*
Почему printf не выводит переменные?
printf("%s", "Znachenie", &p);
printf("%s %f", "Znachenie", p);
printf("Znachenie %f", p);
не могу найти ошибку
int y = n/2;
...
&& (y > (n-1))
всегда false.Программа в каждом случае выдаёт 0.
int deadEnds = 0;
...
100*deadEnds/trials == 0
0/n = 0#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
auto fx = [](int x){
int r = 0;
switch(x % 3)
{
case 0:
r = x * x;
break;
case 1:
r = x;
break;
default:
r = x / 3;
break;
}
return r;
};
auto calculate = [](const vector<int>& vx, auto fx){
vector<int> calcValues(vx.size());
transform(vx.begin(), vx.end(), calcValues.begin(), fx);
return calcValues;
};
int main()
{
cout << "Введи кол-во чисел: ";
int n = 0;
cin >> n;
cout << "Введи через пробел " << n << " натуральных чисел:\n" << "$: ";
vector<int> values(n);
copy_n(istream_iterator<int>(cin), n, values.begin());
cout << "Результат твоих расчетов:\n";
copy_n(calculate(values, fx).begin(), n, ostream_iterator<int>(cout, "\n"));
}
Даны натуральные числа
Оператор == проверяет ссылки, а не значения
В Java сравнение строк equals проверяет исходное содержимое строки. Он возвращает true, если параметр — это объект String, который представляет собой ту же строку символов, что и объект...
#include <iostream>
#include <set>
#include <utility>
#include <string>
using namespace std;
int main()
{
multiset<pair<string, string>> pss{
{"one", "one"}, {"two", "two"}, {"two", "two"},
{"three", "three"}, {"three", "three"}, {"three", "three"}
};
auto cnt = pss.count({"three", "three"});
cout << R"(pss.count({"three", "three"}))" << " == " << cnt << endl;
}
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
size_t n = 4;
string s = "42 54 35 76";
istringstream is(s);
vector<int> v;
copy_n(istream_iterator<int>(is), n, back_inserter(v));
/*******
** vector<int> v2(n);
** copy_n(istream_iterator<int>(is), n, v.begin());
*******/
copy_n(v.begin(), n, ostream_iterator<int>(cout, " "));
}
#include<stdio.h>
int main(int argc, char* argv[])
{
if(argc > 0)
{
for(int i = 0; i != argc; ++i)
printf("%s\n", argv[i]);
}
}
#include<iostream>
#include<filesystem>
#include<string>
using namespace std;
namespace fs = filesystem;
auto getDirectorySize(const fs::path& p)
{
uintmax_t size = 0;
if(fs::is_directory(p))
{
for(const auto& f : fs::directory_iterator(p))
{
size += f.file_size();
}
}
return size;
}
int main()
{
string directory{ "C:\\TEMP" };
fs::path dp{ directory };
auto size{ getDirectorySize(dp) };
cout << "size of " << directory
<< " " << size
<< " bytes" << endl;
}
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
size_t getFileSize(const string& filename)
{
ifstream ifs(filename);
size_t size = 0;
if(ifs)
{
ifs.seekg(0, ios_base::end);
size = ifs.tellg();
}
return size;
}
int main()
{
vector<string> filenames{
"C:\\TEMP\\aaa.txt", "C:\\TEMP\\bbb.txt", "C:\\TEMP\\ccc.txt"
};
size_t size = 0;
for(const string& fn : filenames)
{
size += getFileSize(fn);
}
cout << "Size: " << size << endl;
}
развернуть
// LEFT --> [127 ... 0] --> [32 ... 4095]
//
// RIGHT --> [129 ... 255] --> [32 ... 4095]
int calc_speed(int value)
{
int speed = 0; // для наглядности без ? :
if(value > 128)
{
speed = 4095 / 127 * (value - 128);
}
else
{
speed = 4095 / 127 * (128 - value);
}
return speed;
}
void drive_forward(int speed)
{
MSS.analogWrite(15, 0);
MSS.analogWrite(14, speed);
}
void drive_backward(int speed)
{
MSS.analogWrite(14, 0);
MSS.analogWrite(15, speed);
}
void stop()
{
MSS.analogWrite(14, 0);
MSS.analogWrite(15, 0);
}
void move()
{
int ds = ps2x.Analog(PSS_LX);
if(ds > 128)
{
drive_forward(calc_speed(ds));
}
else if(ds < 128)
{
drive_backward(calc_speed(ds));
}
else
{
stop();
}
}
гуглил, что-то не выходит понять
но почему она не возвращает значения сразу , а только в конце? каким образом происходит сравнение?
template<class ForwardIt, class Compare>
ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp)
{
if (first == last) return last;
ForwardIt smallest = first;
++first;
for (; first != last; ++first) { // не возвращает значения сразу
if (comp(*first, *smallest)) { // каким образом происходит сравнение
smallest = first;
}
}
return smallest; // а только в конце
}
написал код чтобы легче было ориентироваться
#include<cmath>
// ...
int result = *min_element(array.begin(), array.end(), [](int a, int b) { return abs(a) < abs(b); });
// ...
while (!(cin >> x) or cin.get() != '\n')
пока( не (прочитать из буфера ввода целое) или прочитанный из буфера символ не равен '\n')
не понимаю как работает второй while.
while (cin.get() != '\n');
пока(прочитанный из буфера символ не равен '\n') nop
string s;
getline(cin, s);
istringstream is(s);
while(is >> s)
{
int i = 0;
try
{
i = stoi(s);
}
catch(exception& e)
{
cout << "Ошибка: " << e.what() << " " << s << "\n";
continue;
}
cout << "i == " << i << "\n";
}
string msg = "Съешь ещё этих мягких французских булок";
ostringstream os;
os << "Съешь ещё этих мягких французских булок\n"
<< "Съешь ещё этих мягких французских булок\n"
<< "Съешь ещё этих м"
<< "ягких французских булок\n"
<< "Съешь ещё этих мягких французских булок\n";
istringstream is(os.str());
string line;
while(is)
{
getline(is, line);
if(is.fail())
{
os.str("");
os << line;
break;
}
cout << "line: " << line << "\n";
}
float i, a, x = 0;
float i;
float a;
float x = 0;
Подскажите пожалуйста, где я ошибаюсь..
float y = ((i + x) / (2.5 * i + pow(x, i)) ) + a * pow(sin(x), i + 1);
float y = x / 1;
С чем это связано?
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
// ...
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned = null;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
Oct 2 23:39:48 dvrh systemd-resolved[562]: Server returned er....
#include <iostream>
#include <string>
#include <fstream>
#include <sys/utsname.h>
std::string getTimestamp(const std::string& line)
{
auto pos = line.rfind(' ');
return line.substr(pos + 1, line.size() - pos);
}
int main(int argc, char* argv[])
{
if(argc < 3)
{
std::cerr << "usage: file timestamp timestamp\n/var/log/syslog 11:00:00 12:00:00\n";
exit(EXIT_FAILURE);
}
struct utsname uts;
if(uname(&uts) == -1)
{
exit(EXIT_FAILURE);
}
if(std::ifstream flog(argv[1]); flog)
{
std::string start{argv[2]};
std::string stop {argv[3]};
std::string line;
while(getline(flog, line))
{
std::string header = getTimestamp(line.substr(0, line.find(uts.nodename) - 1));
if(header >= start && header <= stop)
{
std::cout << line << "\n";
}
}
}
else
{
std::cerr << "Cannot open file: " << argv[1];
}
}
Я так понимаю такая функция есть в MySQL.h
#ifdef WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#endif
accept(int, int, int)
#include<WinSock2.h>
#include<WS2tcpip.h>
#undef WIN32_LEAN_AND_MEAN
#include "MySQL.h"