Как передать двумерный массив в возвращаемую функцию?
#include<iostream>
#include<limits>
#include<algorithm>
const int size = 3;
auto maxElemUnderD()
{
return [](double(&mtx)[size][size]){
double maxelm = std::numeric_limits<double>::min();
for(auto const& row : mtx)
{
double max = *std::max_element(std::cbegin(row), std::cend(row));
if(max > maxelm) maxelm = max;
}
return maxelm;
};
}
int main()
{
double matric[size][size] =
{
{2, -1, 3},
{-1, 4, 2},
{3, 2, 5}
};
double maxElem = maxElemUnderD()(matric);
std::cout << maxElem << std::endl;
}
void writeBinary(ostream& os, structBook const& book)
{
ostringstream ss;
ss << book.bookId
<< book.bookName.size() << book.bookName
<< book.bookAuthorName.size() << book.bookAuthorName
<< book.bookAuthorSurname.size() << book.bookAuthorSurname
<< book.year << book.pages << book.onplace
<< book.genre.size() << book.genre
<< book.section.size() << book.section;
os.write(reinterpret_cast<char*>(ss.str().size()), sizeof(decltype(ss.str().size())));
os.write(ss.str().data(), ss.str().size());
}
// ...
for(auto const& b : vecStructBook)
{
writeBinary(bookDatabase, b);
}
Нужна функция сортировки
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string src;
getline(cin, src);
string dst;
copy_if(src.begin(), src.end(), back_inserter(dst), ::isdigit);
cout << dst;
}
Мне нужно вывести в консоль строку с файла.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
string extract(string const& s, char first, char last)
{
auto lpos = s.find(first) + 1;
auto rpos = s.find(last, lpos);
return s.substr(lpos, rpos - lpos);
}
void print_if_contains(string const& s, char lp, string const& pattern, char rp)
{
if(extract(s, lp, rp) == pattern)
{
cout << s << "\n";
}
}
void print_if_contains(string const& s, char lp, double d, char rp)
{
if(stod(extract(s, lp, rp)) == d)
{
cout << s << "\n";
}
}
int main()
{
ifstream file("my.txt");
// ...
string line;
while(getline(file, line))
{
print_if_contains(line, '(', "0.0", ')');
print_if_contains(line, '(', 0.0, ')');
}
// ...
}
знаю,что прога корявая;)
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<algorithm>
#include<iterator>
#include<iomanip>
#include<sstream>
using namespace std;
struct Book
{
string name;
int year = 0;
int circulation = 0;
};
istream& operator>>(istream& is, Book& book)
{
string line;
getline(is, line);
istringstream head(line);
getline(head, book.name, ':');
head >> book.year >> book.circulation;
return is;
}
vector<Book> getBooksList(istream& source)
{
return{ istream_iterator<Book>{source}, {} };
}
// Пришел в библиотеку - дайте мне немного книг, любых.
// А тебе говорят - сам возьми, вон там две полки - нижняя и верхняя.
// А да, забыли предупридить - ВЫХОД платный!
enum class input_type : int {Console, File, None};
input_type get_input()
{
if(!cin)
{
system(" ");
cout << "\n\x1b[1;31mА вот и не угадал! Играй по правилам!\x1b[0m\n\n"
"Правило первое - никаких правил ;)\n\n";
cin.clear();
}
cout << "Жми откуда брать: \n [0] -- (консоль)\n [1] -- (файл)\n\n"
"[Ctrl + Z] -- (Извините ошибся дверью)\n\n$: ";
int inp = 0;
if(cin >> inp && inp == 0)
{
system(" ");
cout << "Вводи \x1b[1;31m [ Название : Год Тираж ]\n\n"
<< "Пример:"
<< "\t\x1b[0;40;36mЗолотой ключик, или Приключения Буратино : 1936 50000\n\n"
<< "\x1b[0mНе забудь \x1b[1;33mCtrl + Z\x1b[0m означает конец ввода.\n\n";
}
return static_cast<input_type>(inp);
}
// Не Аквафор
vector<Book> filter(vector<Book> const& books, int from, int to)
{
vector<Book> filtered;
copy_if(books.cbegin(), books.cend(), back_inserter(filtered), [=](auto const& b){
return b.year >= from && b.year <= to;
});
return filtered;
}
// Что я прочитал за это лето
void print_table(vector<Book> const& books)
{
auto max_width_elm = max_element(books.cbegin(), books.cend(), [](auto const& a, auto const& b){
return a.name.size() < b.name.size();
});
if(max_width_elm == books.cend())
{
cout << "Ничего, бывает...\n";
return;
}
size_t max_width = max_width_elm->name.size();
// А какая у вас машина? - Зеленая O_o
system(" ");
cout << "\x1b[1;32m"
<< setw(8 + max_width)
<< left << "Название"
<< setw(12) << "Год"
<< setw(12) << "Тираж" << "\n"
<< "\x1b[0m";
for(auto[name, year, circul] : books)
{
cout << setw(8 + max_width)
<< left << name
<< setw(12) << year
<< setw(12) << circul << "\n";
}
}
enum class sort_field { Name, Year, Circul };
auto sort_by = [](sort_field field, auto& container){
sort(container.begin(), container.end(), [=](const auto& a, const auto& b){
bool result = false;
switch(field)
{
case sort_field::Year:
result = a.year < b.year;
break;
case sort_field::Circul:
result = a.circulation < b.circulation;
break;
default:
result = a.name < b.name;
break;
}
return result;
});
};
int main()
{
setlocale(LC_ALL, "");
//типа файл
const string test_data = "book10 : 2010 10000\n"
"book09 : 2009 9000\n"
"book19 : 2019 19000\n"
"book03 : 2003 3000\n"
"book84 : 1984 84000\n"
"book42 : 2042 42000";
istringstream is(test_data);
vector<Book> books;
input_type input = input_type::None;
while(input == input_type::None)
{
input = get_input();
switch(input)
{
case input_type::Console:
books = getBooksList(cin);
break;
case input_type::File:
books = getBooksList(is);
break;
default:
system(" ");
cout << "\n\x1b[1;33mВыбери 0 или 1 ЧеГо НеПоНяТнОгО?\x1b[0m \n";
input = input_type::None;
break;
}
}
sort_by(sort_field::Year, books);
print_table(filter(books, 2000, 2010));
system("pause");
}
Помогите пожалуйста написать код функции (fun.....она уже сто раз написана,переписана,закомментирована)
заранее спасибо!!!)
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<Windows.h>
using namespace std;
struct book
{
string name;
unsigned year;
unsigned circulation;
};
int count_if(book* b, int sz, int from, int to)
{
int cn = 0;
for(int i = 0; i < sz; ++i)
{
if(b[i].year >= from && b[i].year <= to)
{
++cn;
}
}
return cn;
}
book* get_books_list(book* arr, int n, int from, int to, int& out_sz)
{
out_sz = count_if(arr, n, from, to);
if(out_sz == 0)
{
return nullptr;
}
book* array = new book[out_sz];
int idx = 0;
for(int i = 0; i < n; ++i)
{
if(arr[i].year >= from && arr[i].year <= to)
{
array[idx].name = arr[i].name;
array[idx].year = arr[i].year;
array[idx].circulation = arr[i].circulation;
++idx;
}
}
return array;
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
string kng = "TextFile1.txt";
int N;
book *arr;
int otkr;
cout << "ВЫБЕРИТЕ СПОСОБ ВВОДА. 0 - С КЛАВИАТУРЫ, 1 - ИЗ ФАЙЛА \n";
cin >> otkr;
if(otkr == 0)
{
cout << "введите размер массива \n";
cin >> N;
arr = new book[N];
for(int i = 0; i < N; ++i)
{
cout << "Введите название книги\n";
cin >> arr[i].name;
cout << "Введите тираж \n";
cin >> arr[i].circulation;
cout << "Введите год издания \n";
cin >> arr[i].year;
}
for(int i = 0; i < N; ++i)
{
cout << arr[i].name << " " << arr[i].circulation << " " << arr[i].year << endl;
}
}
else
{
fstream knigi;
knigi.open("TextFile1.txt");
knigi >> N;
arr = new book[N];
for(int i = 0; i < N; i++)
{
knigi >> arr[i].name >> arr[i].circulation >> arr[i].year;
}
}
int sz = 0;
book* books = get_books_list(arr, N, 2000, 2010, sz);
delete[] arr;
if(books)
{
cout << "НАЗВАНИЕ И ТИРАЖ КНИГ С ИЗДАННЫХ С 2000-2010 ГГ:\n";
for(int i = 0; i < sz; ++i)
{
cout << books[i].name << " " << books[i].circulation << "\n";
}
delete[] books;
}
else
{
cout << "ТАКИХ НЕТ.";
}
system("pause");
}
#include<iostream>
#include<filesystem>
#include<string>
using namespace std;
namespace fs = filesystem;
auto listFilesRecursively = [](auto const& dir, string const& mask = {}){
if(!fs::is_directory(dir))
{
cerr << dir << " is not dir";
throw "is not dir!";
}
for(auto const& file : fs::recursive_directory_iterator(dir))
{
if(fs::is_regular_file(file))
{
if(mask.empty() || file.path().extension().string() == mask)
{
// Здесь твоя функция вывода инфы
cout << file.path().string() << " #size: " << file.file_size() << "\n";
}
}
else if(fs::is_directory(file))
{
cout << "\n****** dir ****** [" << file.path().string() << "]\n";
}
else
{
cout << "\n***** other... ******[" << file.path().filename().string() << "]\n";
}
}
};
int main()
{
const string start_dir = R"(C:\Program Files)";
try
{
listFilesRecursively(start_dir, ".dll");
}
catch(exception& e)
{
cerr << e.what();
}
}
#include<iostream>
#include<algorithm>
#include<sstream>
#include<string>
#include<vector>
#include<numeric>
#include<iomanip>
using namespace std;
auto avg = [](istream& is, int n){
vector<double> avgPerLine;
generate_n(back_inserter(avgPerLine), n, [&](){
string line;
getline(is, line);
auto words = istringstream(line);
int words_count = 0;
int words_length = 0;
while(words >> line)
{
words_count++;
words_length += line.length();
}
return words_count ? static_cast<double>(words_length) / words_count : 0.0;
});
return accumulate(avgPerLine.cbegin(), avgPerLine.cend(), 0.0) / avgPerLine.size();
};
void print(const string& msg, double value)
{
cout << setprecision(2)
<< msg << "\n"
<< "avg == " << value << endl;
}
int main()
{
setlocale(LC_ALL, "");
string test_str = "one two three\nfour five six\nseven eight nine";
string test_str2 = "word1\nword2\nword3";
auto test = istringstream(test_str);
auto test2 = istringstream(test_str2);
print(test_str, avg(test, 3));
print(test_str2, avg(test2, 3));
cout << "Введи три предложения, по одному в строке:\n";
cout << "avg == " << avg(cin, 3) << endl;
system("pause");
void print(int* a, int size, int pos = -1)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int i = 0;
SetConsoleTextAttribute(hConsole, (WORD)((0 << 8) | 15));
for(; i < pos; ++i) cout << a[i] << " ";
if(pos != -1)
{
SetConsoleTextAttribute(hConsole, (WORD)((0 << 4) | 4));
cout << a[i] << " " << a[i + 1] << " ";
SetConsoleTextAttribute(hConsole, (WORD)((0 << 8) | 15));
i += 2;
}
for(; i < size; ++i) cout << a[i] << " ";
cout << endl;
}
void massiv(int* x, int n)//функция заполнения и изменения
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
for(int i = 0; i < n; i++)//заполнение массива
{
x[i] = rand() % 10;
}
print(x, n);
int id = 0; // id - первый элемент пары, дающей максимальную разность
for(int i = 0; i < n - 1; i++)
{
if(abs(x[i] - x[i + 1]) > abs(x[id] - x[id + 1]))
{
id = i;
}
}
SetConsoleTextAttribute(hConsole, (WORD)((0 << 4) | 4));
cout << abs(x[id + 1] - x[id]) << "\n";
print(x, n, id);
}
int* x = new int[n]; //динамическая переменная выделение памяти
но на месте Int может ничего не быть как это считать?
#include<iostream>
#include<sstream>
#include<string>
#include<optional>
#include<tuple>
using namespace std;
auto try_parse(const string& s) -> tuple<string, optional<int>>
{
string sval;
optional<int> ival;
auto is = istringstream(s);
is >> sval;
if(isdigit(s.back()))
{
int i = 0;
is >> i;
ival = i;
}
return {sval, ival};
}
int main()
{
string line;
getline(cin, line);
auto [sval, ival] = try_parse(line);
cout << "string value:\t" << sval << "\n";
if(ival != nullopt)
{
cout << "int value:\t" << ival.value() << "\n";
}
cin.get();
}
Пару часов уже копаюсь в просторах сети и кроме стандартных ничего дельного не нахожу.
Графические и мат
if(mode == "move") {
move(files[i], dir, newDir);
}
if(dirFile[dirFile.size() - 1] != '\\')
dirFile.back() != '\\'
#include<filesystem>
#include<iostream>
#include<vector>
#include<string>
#include<iterator>
using namespace std;
namespace fs = experimental::filesystem;
vector<string> getFilenamesFromDir(const string& dir)
{
vector<string> filenames;
if(fs::exists(dir))
{
for(auto& entry : fs::directory_iterator(dir))
{
if(!fs::is_directory(entry.path()))
{
filenames.push_back(entry.path().filename().string());
}
}
}
return filenames;
}
int main()
{
string dirname;
cout << "Enter directory: ";
getline(cin, dirname);
auto files = getFilenamesFromDir(dirname);
if(!files.empty())
{
sort(files.begin(), files.end());
copy(files.cbegin(), files.cend(), ostream_iterator<string>(cout, "\n"));
}
cin.get();
}
scanf("%f", &epsilon);
int res1 = 0;
for(i = 0; i <= n; i++) {
res1 = res1 * i;
}
int res1 = 0
...
res1 = 0 * i;
float an = (3 * factorial())/X3factorial();
while (an > epsilon)
...
int n = 1;
float sum = 0;
...
int n = n++; // ???
Почему программа на C++ не выводит результат?
#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*