-
Notifications
You must be signed in to change notification settings - Fork 17
STL
kerogen-pezy edited this page Jun 21, 2017
·
1 revision
不多说,见代码:
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
int a1[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int a2[ 10 ] = { 1, 2, 3, 4, 9, 6, 7, 8, 9, 10 };
std::vector< int > v1( a1, a1 + 10 );
std::vector< int > v2( a1, a1 + 10 );
std::vector< int > v3( a2, a2 + 10 );
std::ostream_iterator< int > output( cout, " " );
cout << "Vector v1 contains: ";
std::copy( v1.begin(), v1.end(), output );
cout << "\nVector v2 contains: ";
std::copy( v2.begin(), v2.end(), output );
cout << "\nVector v3 contains: ";
std::copy( v3.begin(), v3.end(), output );
std::pair< std::vector< int >::iterator, std::vector< int >::iterator > location;
location = std::mismatch( v1.begin(), v1.end(), v3.begin() );
cout << "\nThere is a mismatch between v1 and v3 at location "
<< ( location.first - v1.begin() ) << "\nwhere v1 contains "
<< *location.first << " and v3 contains " << *location.second;
return 0;
}输出结果:
Vector v1 contains: 1 2 3 4 5 6 7 8 9 10
Vector v2 contains: 1 2 3 4 5 6 7 8 9 10
Vector v3 contains: 1 2 3 4 9 6 7 8 9 10
There is a mismatch between v1 and v3 at location 4
where v1 contains 5 and v3 contains 9若v1 与v2 相同,那么location 的first 和second 将分别指向v1.end() 和v2.end()。若遇到不同处,则分别指向其不同处的迭代器。
从套接字中接收的buf 往往是unsigned char* 类型,当把它赋值给std::string 的时候,往往会被默认截断。尤其是在buf 中存在空字符时。
例如:std::string my_string("a\0b");
可以很容易的看到 my_string 仅仅会包含a。那么如何让my_string 包含后续的全部字符呢?
std::string x("pq\0rs",5); // 5 Characters as the input is now a char array with 5 characters.这种方式叫做以char 数组的形式构造std::string 。而我们通常用的方式,其实是按照C-String 的方式构造std::string。
如回车、空格、Tab键等
示例代码如下:
#include <algorithm>
#include <string>
#include <iostream>
#include <cctype>
int main()
{
std::string str2 = "Text\n with\tsome \t whitespaces\n\n";
str2.erase(std::remove_if(str2.begin(),
str2.end(),
[](char x){return std::isspace(x);}),
str2.end());
std::cout << str2 << '\n';
}// 十进制 -> 二进制
std::string binary = std::bitset<8>(128).to_string(); // 10000000
// 二进制 -> 十进制
unsigned long decimal = std::bitset<8>(binary).to_ulong(); // 128references: C++ - Decimal to binary converting
对于小于2G的文件,都可以考虑下述解决思路:
- 读取全部文件到内存
- 解析内存字符串
- 释放内存
仅记录常规步骤:
#include <iostream>
#include <fstream>
#include <sstream>
int main()
{
std::ifstream is("data.txt", std::ifstream::in);
if (is)
{
// read into memory
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char *buffer = new char[length];
is.read(buffer, length);
is.close();
// parse buffer.
delete [] buffer;
}
return 0;
}参考我的这个答案。