-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.cpp
89 lines (80 loc) · 2.05 KB
/
common.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* =====================================================================================
*
* Filename: common.cpp
*
* Description: some useful functions
*
* Version: 1.0
* Created: 02/19/2014 10:21:42 PM
* Revision: none
* Compiler: g++
*
* Author: Xinyun Ma
* Organization: Tsinghua University
*
* =====================================================================================
*/
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <unistd.h> // parsing argument
#include <sys/stat.h> // mkdir and access
#include "common.h"
using namespace std;
bool output_with_time(ostream& out, const string & s)
{
time_t cur_time;
time(&cur_time);
string str_time(ctime(&cur_time));
out << "[" << str_time.substr(4, 15) << "]: " << s;
}
//delimeter
vector<string> delimiter(const string & str, const char deli){
vector<string> t;
size_t l_ind = 0;
size_t r_ind = 0;
while(str[r_ind] != '\0'){
if(str[r_ind] != deli){
r_ind++;
}
else{
t.push_back(str.substr(l_ind, r_ind - l_ind));
r_ind++;
l_ind = r_ind;
}
}
if(r_ind != l_ind){
t.push_back(str.substr(l_ind, r_ind - l_ind));
}
return t;
}
// if user know that there are N fields, then the vector can be initialized by size N. Maybe could speed up.
// if there are more than N fields, it will return the first N fields
// return by reference, to speed up
void delimiter_ret_ref(const string & str, const char deli, const int N, vector<string> & t){
size_t l_ind = 0;
size_t r_ind = 0;
size_t cur_field = 0;
while(str[r_ind] != '\0'){
if(str[r_ind] != deli){
r_ind++;
}
else{
if(cur_field >= N){
return;
}
t[cur_field++] = str.substr(l_ind,r_ind-l_ind);
r_ind++;
l_ind = r_ind;
}
}
if(r_ind != l_ind){
if(cur_field >= N){
return;
}
t[cur_field++] = str.substr(l_ind,r_ind-l_ind);
}
return;
}