#include<iostream>
#include<fstream>
#include<algorithm> // copy
#include<string>
#include<vector>
#include<array>
#include<memory> // unique_ptr
#include<cstdio>
#include<iterator>
using namespace std;
using pipe = unique_ptr<FILE, decltype(&_pclose)>;
auto getCmdOutput = [](const string& command)
{
pipe fp{_popen(command.c_str(), "r"), &_pclose};
vector<string> result;
array<char, 512> buf;
if(fp)
{
while(fgets(buf.data(), buf.size(), fp.get()))
{
result.emplace_back(buf.data());
buf.fill(0);
}
}
return result;
};
auto writeToFile = [](const string& fname, const vector<string>& info)
{
ofstream ofs(fname);
if(info.empty() || !ofs)
{
// put error ...
return false;
}
copy(info.cbegin(), info.cend(), ostream_iterator<string>{ofs});
return true;
};
int main()
{
if(writeToFile("D:\\ipconfig.cfg", getCmdOutput("ipconfig")))
{
cout << "Success!" << endl;
}
else
{
cout << "Failure!" << endl;
}
}
Как применять алгоритмы STL в Qt
To iterate over a list, you can either use index positions or QList's Java-style and STL-style iterator types:
Слишком много литературы есть по С++
Т.е. не обучение языку, а обучение бытовому программированию
В частности интересует: Обработка данных, Абстрактное программирование, Шаблоны
Я хочу иметь “шпаргалку”
какие типы переменных инициируются нулями?
#include<iostream>
#include<algorithm>
#include<iterator>
#include<string>
using namespace std;
string getOneStr(istream& is)
{
string result;
copy(++istreambuf_iterator<char>(is), {}, back_inserter(result));
return result;
}
int main()
{
cout << "Enter the line (Win Ctrl+Z or Lin Ctrl+D end)\n$: ";
string s = getOneStr(cin);
cout << s << endl;
}
аналог Map из JavaScript
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
template<typename Key, typename Val>
class Map
{
map<Key, Val> values;
vector<Key> index;
public:
// ...
auto operator[](int i)
{
return values[index[i]];
}
// ...
void insert(const pair<Key, Val>& val)
{
values[val.first] = val.second;
index.push_back(val.first);
}
// ...
};
int main()
{
Map<int, string> mp;
mp.insert({3, "three"});
mp.insert({42, "forty two"});
mp.insert({2, "two"});
mp.insert({4, "four"});
for(int i = 0; i < 4; ++i)
{
cout << mp[i] << "\n";
}
}
Каким образом это можно осуществить на C++?
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <experimental/iterator>
using namespace std;
template<size_t N>
auto doit = [](const auto& s)
{
string result;
auto p = s.begin();
while(p != s.end())
{
copy_n(p, N, back_inserter(result));
result += '\n';
p += N;
}
result.pop_back();
return result;
};
int main()
{
ifstream in("D:\\in.txt");
ofstream out("D:\\out.txt");
if(!in || !out)
{
return EXIT_FAILURE;
}
transform(istream_iterator<string>(in), {},
ostream_iterator<string>(out), doit<7>);
out.close();
ifstream rin("D:\\out.txt");
copy(istream_iterator<string>(rin), {},
experimental::make_ostream_joiner(cout, "\n"));
}
Вопрос довольно короток. Есть ли смысл изучать сначала С, а потом С++?
Чем лучше программист знает С, тем труднее будет для него при программировании на С++ отойти от
стиля программирования на С.
Для изучения С++ не обязательно знать С. Программирование на С способствует усвоению приемов и
даже трюков, которые при программировании на С++ становятся просто ненужными.
Тем не менее, хорошие программы на языке С по сути являются
программами на С++. Например, все программы из классического описания С (K&R) являются
программами на С++. В процессе изучения С++ будет полезен опыт работы с любым языком со
статическими типами.
#include <iostream>
#include <string>
#include <algorithm>
#include <windows.h>
void prepare(std::string& value, char a, char b)
{
size_t sz = value.size();
if(sz % 2)
value.insert(0, 1, b);
else
value.insert(sz / 2, 1, a);
}
auto shift = [](const char c, const char a)
{
return (c != 'Ё')
? (c != 'Е')
? a + ((c - a + 1) % 32)
: 'Ё'
: 'Ж';
};
std::string& process(std::string& s, const char a, const char b, int repeat)
{
if(!repeat) return s;
prepare(s, a, b);
std::transform(s.begin(), s.end(), s.begin(),
[&](char c){return shift(c, a);
});
return process(s, a, b, repeat - 1);
};
int main()
{
SetConsoleOutputCP(1251);
std::string one("ВРМ");
std::string two("ТОР");
std::cout << process(one, 'А', 'Б', 1) << "\n" // ВГСН
<< process(two, 'А', 'Б', 2) << std::endl; // ГФБРТ
}
почему сделано так
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
bool inRange(int value, int a, int b)
{
return value >= a && value <= b;
}
int main()
{
string value;
while(true)
{
cout << "Enter value [0, 10]: ";
getline(cin, value);
int result = 0;
try
{
result = stoi(value);
if(inRange(result, 0, 10))
{
cout << "Okay Goodbye Good Boy" << endl;
break;
}
throw invalid_argument("Bad Boy!");
}
catch (exception& e)
{
cout << e.what() << " - try agian!" << endl;
}
}
}
#include <stdio.h>
int index(char[], char[]);
int main()
{
char* str = "foo bar baz";
char* str2 = "barz";
if(index(str, str2) != -1)
printf("found");
else
printf("not found");
return 0;
}
int index(char s[], char t[])
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++)
{
for (j = i, k = 0; t[k] != '\0' && s[k] == t[k]; j++, k++)
;
if(t[k] == '\0')
return i;
}
return -1;
}
Учебник нужен не столько мне, сколько моему коллеге, который ещё новичок не выше intern'а.
Но для первичного обучения она тоже не подходит. Слишком коротко, и термины такие, которые непосвященный не сможет правильно понять: "std::map - отсортированный контейнер " - что значит отсортированный? Что в нем отсортировано? В нем же еще нет данных...
#include<locale>
//...
locale loc(".1251");
if(!isalpha(c, loc) && !isspace(c, loc))
{
//...
}
Где найти материалы на русском языке связанные с opencv.
Как установить opencv на visual studio, и надо ли?
Каким образом opencv находит обьекты, как привязать камеру или что либо еще.
Как люди создают балансборды и объидиняют с Arduino.
Гуглом пользоваться умею, но нормальной инфы нет,только как установить...
opencv_world410d.lib
The names of the libraries are as follow:
opencv_(The Name of the module)(The version Number of the library you use)d.lib
For the purposes of this example, we will make reference to IplImage and cvLoadImge(), both constructs
from the ancient pre–version 2.1 interface that are now deprecated. We won’t really cover them in detail in
this book, but all you need to know for this example is that IplImage is the old data structure for images, and
cvLoadImage() was the old function to get an image from disk and return a pointer to the resulting image
structure.