Home c++ find doesn't work for C++ vector

find doesn’t work for C++ vector

Author

Date

Category

I’m writing an interesting script now, stuck on a topic where you need to open a file (opened), read it and write it, in this case in a vector (made), but I can’t use the find method, I need to find the word “Processor” in the resulting vector, it seems to have made equality with a new variable, which should indicate equal to the result of find, when I try to output via cout (check if it has found) the error C2679 flies Binary “& lt; & lt;”: operator not found …
Here is the code, please support:

# include & lt; iostream & gt;
#include & lt; fstream & gt;
#include & lt; string & gt;
#include & lt; algorithm & gt;
#include & lt; vector & gt;
using namespace std;
void show_vector (vector & lt; char & gt; & amp; a)
{
  for (auto it = a.begin (); it! = a.end (); ++ it)
    cout & lt; & lt; * it;
}
int main ()
{
  int x = 0;
  cout & lt; & lt; "Hello World! \ N";
  ifstream dsdtF ("./ files / dsdt.dsl", ios :: in | ios :: binary | ios :: ate);
  if (dsdtF.is_open ()) {
    cout & lt; & lt; "File opened successfully! \ N";
    const ifstream :: pos_type file_size = dsdtF.tellg ();
    vector & lt; char & gt; dsdtVector (file_size);
    dsdtF.seekg (0, ios :: beg);
    dsdtF.read (& amp; dsdtVector [0], file_size);
    char toFind [] = "Processor";
    auto pos = find (dsdtVector.begin (), dsdtVector.end (), toFind [0]);
    cout & lt; & lt; pos;
  }
  else {
    cout & lt; & lt; "Failed to open the file! \ N";
  }
  dsdtF.close ();
  cin & gt; & gt; x;
  cout & lt; & lt; "\ n \ n \ nPress any key to exit ... \ n";
  cin.get ();
  return 0;
}

Answer 1

You are trying to output an iterator.

If you want to display the position of the found letter P , then output

cout & lt; & lt; distance (dsdtVector.begin (), pos);

P.S. I would recommend

string dsdtVector (file_size, '');
  dsdtF.seekg (0, ios :: beg);
  dsdtF.read (dsdtVector.data (), file_size);
  char toFind [] = "Processor";
  auto pos = dsdtVector.find (toFind);
  cout & lt; & lt; pos;

Answer 2

You need to find a sequence of characters (search word) in a container (in this case, a vector) of characters. There is the std :: search algorithm for this. In this case, you can use it like this:

auto It = std :: search (dsdtVector.begin (), dsdtVector.end (),
           toFind, toFind + strlen (toFind));
if (It == dsdtVector.end ())
  cout & lt; & lt; "not found";
else
  cout & lt; & lt; It - dsdtVector.begin ();

But it’s easier to read into a std :: string object (you can read lines at once), and then find a word with its own method std :: string :: find_first_of

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions