std流
如果想调用一个封装好的函数而不想让这个函数输出cout等到屏幕,可以使将cout流重新定向到文件流:
# include <fstream>
ofstream of("out.txt");
// 获取cout流缓冲区指针
streambuf*coutBuf = cout.rdbuf();
// 获取文件流缓冲区指针
streambuf* fileBuf = of.rdbuf();
//设置cout流缓冲区指针为文件流的缓冲区指针
cout.rdbuf(fileBuf);
func();
// 恢复cout指针
of.flush();
of.close();
cout.rdbuf(coutBuf);
编译
.a 是静态库 .so是动态库。其中静态库在编译的时候需要链接,运行时不需要。而动态库在编译和运行时都需要链接。
ldd main #查看可执行文件main依赖的动态库
#打包
# 静态库
g++ -c main.cpp -o main.o
ar -r libmain.a main.o
#动态库
gcc -c -fPIC main.c -o main.o
gcc -shared main.o -o libmain.so
g++ main.cpp -o main -I ../include -L ../libs -lgdal
使用pkg-config:
–cflags和–libs分别指定头文件和库文件
`pkg-config opencv --libs --cflags`
文件流
// c
#include <stdio.h>
// 基本读写https://www.runoob.com/cprogramming/c-file-io.html
FILE* fp = fopen(filename,mode);
// 文件指针移动函数:int fseek(FILE * stream, long offset, int whence);
fseek(fp, offset, 1);
//将文件指针从现在位置向后移动offset个字节
//如果whence是0则代表从文件开头开始向后移动
//如果是1则代表从文件结尾向前移动
tinyxml
#include "tinyxml.h"
TiXmlDocument doc;
if(!doc.LoadFile("a.xml"))
{
cerr << doc.ErrorDesc() << endl;
return FAILURE;
}
TiXmlElement* root = doc.FirstChildElement();
if(root == NULL)
{
cerr << "Failed to load file: No root element." << endl;
doc.Clear();
return FAILURE;
}
/*
TiXmlElement* ::
FirstChildElement()
NextSiblingElement()
SetAttribute(string name, attribute)
FirstAttribute() //获取属性
Value()
GetText()
TiXmlNode* :: (对应于DOM结构中的节点)
FirstChild()
TiXmlAttribute* ::
Next()
*/
C与C++
char与string转换
string text = "hello";
char text_c[] = text.c_str();
string text_cpp = text_c;
vector
声明
vector<int> a;
vector<int> a = {1,2,3};
int m = 10; //the max vol of vector a
vector<int> a(m);
int init = 1;
vector<int> a(m,init);
int i[] ={1,2,3,4,5};
vector<int> a(i,i+3); //将i[0:3]数组初始化给a
多维声明
vector<vector<int>> a;
int m = 10, n = 100; //2 dimension vec a size:10x100
int init = 1;
vector<vector<int>> a(10,vector<int>(n, init));
vector<vector<int>> arr;
vector<int> a={1,2,3};
for(int i=0;i<4;i++)
{
arr.push_back(a);
}
基本操作
vector<int> a;
int val = 5; // a value
a.push_back(val); // 末尾插入变量
sort(a.begin(), a.end()); // 正序排序
reverse(a.begin(), a.end()); // 翻转
vector<int> a_reverse(m);
reverse_copy(a.begin(), a.end(), a_reverse.begin()); // 不改变a
vector < int >::interator it = find(a.begin() , a.end,val) ; //查找
val = *it;
a.erase(it); //删除
a.erase(a.begin()+5);
// 需要注意的是,a.begin()是a[0]的地址, 而a.end()是a[m]的地址,所以sort也可以写为:
sort(&a[0], &a[m]);
// 如果只对部分排序:
sort(&a[start], &a[final+1]);