ZC: 网上查到, 使用 vector 时, 只要将 find 到的 iterator(itX) 减去 vector::begin() 就可以得到 itX 的序号.
1, 需求: 得到 某个 iterator 在 vector 中是第几个 (即 获取序号)
2, 测试代码:(Win7x64,vs08x86)
- #include <stdio.h>
- #include <stdlib.h>
- #include <Windows.h>
- #include <io.h>
- #include <map>
- #include <math.h>
- #include <list>
- #include <string>
- #include <sstream>
- #include <algorithm>// std::find(...)
- #include <vector>
- using namespace std;
- //#include "stdafx.h"
- #include <iostream>
- #include <Windows.h>
- #include <math.h>
- using namespace std;
- /*
ZC: 网上查到, 使用 vector 时, 只要将 find 到的 iterator(itX) 减去 vector::begin() 就可以得到 itX 的序号.
ZC: 但是, 原理不明白...
ZC: 可靠性 也未有验证, 能看到 高手的留言 或者 源码的查证?
ZC: vector<string>::iterator 的结构不明, iterator 的相减到底是什么样的操作, 需要看 STL 源码??
- //*/
- // ZC: 估计是 iterator 中 有重载 减号操作符? 使得 在用于 vector 的时候, 详见能够得到 序号?
- #pragma warning(disable:4996)
- #pragma warning(disable:4786)// ZC: 貌似 VC6 使用 map 的时, 在 build 的时候会报很多 warning, 用这个 禁止显示这些 warning
- #include <map>
- #include <string>
- #include <algorithm>// std::find(...)
- #include <vector>
- using namespace std;
- void main()
- {
- vector<string> vtr;
- vtr.push_back("8");
- vtr.push_back("2");
- vtr.push_back("6");
- vtr.push_back("7");
- vtr.push_back("1");
- printf("%d\n", sizeof(string));
- // ZC: 这里想用地址 来看看: 是否 两个 iterator 的地址之差 和 idx 有什么联系, 但是 没找到什么联系, 估计还是得看源码 或者 别人的解释
- vector<string>::iterator itBegin = vtr.begin();
- vector<string>::iterator itEnd = vtr.end();
- printf("0x%08X - 0x%08X\n", itBegin, itEnd);
- int* piBegin = (int*)&itBegin;
- int* piEnd = (int*)&itEnd;
- printf("0x%08X - 0x%08X\n", *piBegin, *piEnd);
- vector<string>::iterator it = std::find(vtr.begin(), vtr.end(), "6");
- if (it == vtr.end())
- printf("it == vtr.end()\n");
- else
- {
- printf("it != vtr.end()\n");
- printf("it : %s\n", it->c_str());
- }
- printf("0x%08X - 0x%08X\n",
- it->c_str(),
- vtr.begin()->c_str() );// ZC: 这里相差 64(十进制)
- printf("0x%08X - 0x%08X = %d(10 进制)\n",
- it, itBegin, (it-itBegin) );// ZC: 这里相差 40(十进制)
- int iIdx = it - vtr.begin();
- printf("iIdx : %d, it-it0: %d\n", iIdx, (it-itBegin));
- iIdx = iIdx / sizeof(string);
- printf("iIdx : %d\n", iIdx);
- printf("%d : %s\n", iIdx, vtr.at(iIdx).c_str());
- //*/
- system("pause");
- }
- 3,
- 4,
- 5,
来源: http://www.bubuko.com/infodetail-2873446.html