Bootstrap

vector的二分查找

int Search(vector<string> &rvecValue, const string &rstrSearch)
{
	if (rvecValue.size() == 0)
		return -1;

	int n = 0, nLow = 0, nHigh = rvecValue.size();

	while (nLow <= nHigh)
	{
		int nMid = (nLow + nHigh) / 2;
		
		if (rstrSearch == rvecValue[nMid])
			return nMid;
		else if (rstrSearch < rvecValue[nMid])
			nHigh = nMid - 1;
		else
			nLow = nMid + 1;
	}

	return -1;
}

void main(int argc, char **argv)
{
	vector<string> vecStr;

	vecStr.push_back("aaaa");
	vecStr.push_back("bbb");
	vecStr.push_back("ccc");
	vecStr.push_back("ddd");
	vecStr.push_back("eee");

	int ret = Search(vecStr, "ccc");

	cout << ret << endl;
}

如果vector中存储的是顺序内容,则可以使用二分查找。



;