我有char* t
,我希望在字符串向量中找到它。
例如,char *t
指向"abc"
,而我的向量与"abc"
具有相同的string
。
答案 0 :(得分:3)
使用std::find
- 它会隐式将char*
转换为std::string
。
auto foundIterator = std::find(vec.begin(), vec.end(), t);
如果元素不在向量中,则foundIterator
将等于vec.end()
。
答案 1 :(得分:1)
这本身并不是一个新的答案,只是@Luchian发布的一些演示代码:
#include <string>
#include <algorithm>
#include <sstream>
#include <iostream>
int main() {
std::vector<std::string> data;
for (int i=0; i<10; i++) {
std::ostringstream b;
b << "String " << i;
data.push_back(b.str());
}
auto pos = std::find(data.begin(), data.end(), "String 3");
std::cout << pos-data.begin();
return 0;
}
至少在我运行时,它似乎找到了字符串(它打印出3
)。