Menu

Problem with unique_copy

2002-10-11
2012-09-26
  • Nobody/Anonymous

    This program (for an exercise in Stroustup's The C++ Programming Language) compiles fine, but crashes when it gets to unique copy.

    #include <iostream>
    #include <stdlib.h>
    #include <vector>
    #include <string>
    #include <algorithm>

    using namespace std;

    int main()
    {
        vector<string> words;
        vector<string> uniquewords;
        string input;
       
        do
        {
          cin >> input;
          if (input != "quit")
          {
             words.push_back(input);
          }
          else
          {
              break;
          }
        }while(input != "quit");
       
        cout << endl << endl;
       
        unique_copy(words.begin(), words.end(), uniquewords.begin());
       
        for (int loop=0; loop<uniquewords.size(); loop++)
        {
            cout << uniquewords[loop] << endl;
        }
       
        cout << endl << endl;
        system("PAUSE");
        return 0;
    }

     
    • Nobody/Anonymous

      Your problem is with cin

      Learn more about it.

      BlakJak  :]

       
    • Nobody/Anonymous

      Indeed?

      As far as I can see cin is doing it's job.

      words contains a valid vector of words.

       
      • Nobody/Anonymous

        What is unique_copy doing???

        BlakJak    :]

         
    • Nobody/Anonymous

      What is it doing?

      Crashing: Unhandled acception -  access violation

      What is it supposed to do?

      As far as I am aware it is supposed to copy elements from one container to another, ensuring that only one instance of any element occurs in the destination container.

       
    • Nobody/Anonymous

      I've got it.

      Should have been:

      unique_copy(words.begin(), words.end(), back_inserter(uniquewords));

      instead of:

      unique_copy(words.begin(), words.end(), uniquewords.begin());

      This version would only have worked if there had already been something in uniquewords to overwrite.

       

Log in to post a comment.