Reputation: 196
I have a char* t
, that I want to find it in a vector of strings.
For example, the char *t
points to "abc"
, and my vector has the same "abc"
as a string
.
Upvotes: 1
Views: 8313
Reputation: 490128
This isn't really a new answer in itself, just some demo code for what @Luchian posted:
#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;
}
At least when I run this, it appears to find the string (it prints out 3
).
Upvotes: 1
Reputation: 258608
Use std::find
- it will implicitly convert the char*
to a std::string
.
auto foundIterator = std::find(vec.begin(), vec.end(), t);
If the element is not in the vector, then foundIterator
will be equal to vec.end()
.
Upvotes: 3