vector

This is a discussion on vector within the C++ Programming forums, part of the General Programming Boards category; I have three questions. Is this code actually inserting the text into each vector containers? If so, is there a ...

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    90

    vector

    I have three questions.

    Is this code actually inserting the text into each vector containers?

    If so, is there a faster way fill the containers?

    I have a loop commented out because what I tried to do with it did not work. Could someone help me to correct this code?

    Thanks in advance


    Code:
    #include<iostream>
    #include <sstream>
    #include <fstream>
    #include <vector>
    #include <iterator>
    #include <algorithm>
    
    using namespace std;
    
              vector<int> line_1;
              vector<int> line_2;
              vector<int> line_3;
    
    
    void InsertLine( ifstream& ifs, vector<int>& v )
         {
         string s;
         getline( ifs, s );
         istringstream iss( s );
         copy( istream_iterator<int>( iss ), 
               istream_iterator<int>(),
               back_inserter( v ) );
               cout  << s  ;
               }
    
    //     {
    //     for (int i = 0; i < v.size(); ++i)
    //     {
    //     cout << "  " << v[i] << endl;    }   }
    
    
    int main()
              {
              ifstream ifs( "Data.txt" );
    
              InsertLine( ifs, line_1 );
              InsertLine( ifs, line_2 );
              InsertLine( ifs, line_3 );
      
              cout<<"\n\n";
    
       system("pause");
       system ("CLS");
       return main();
    }
    Data.txt
    Code:
    111
    222
    yes
    no

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,762
    InsertLine will only work for the first two lines of data.txt just because of the types of vector and istream_iterators you have.

    I think it's apparent you need a more flexible approach, so why don't you just do it in a way you understand? Copying it is only really great when you have one kind of data to read, like a list of only integers.

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    whiteflags, like a lot of other things vector is all new to me (4 days old) and after all these days of reading, searching and re-building non-working examples out of hundreds not a single one works to insert data from a text file into "separate" containers. Actually 99.9% of all single fill vectors examples I found on the NET did not work from 2004 to date. I had 40 windows open in my Opera browser all pointing to C++ Vector searches, 24/7. I am not happy
    Code:
             InsertLine( ifs, line_1 );
             InsertLine( ifs, line_2 );
             InsertLine( ifs, line_3 );   That's sad!
    You can write a million separate containers (lines) for vector strings in the program but you can only read in 2 lines. *#2!*&$###. I got one more idea,. I'll hard code it in pure C and FASM someday unless you pull a rabbit out the hat
    Code:
        vector<string> str1(1000000000);
        str1[0] = "sing_C++";
        str1[1] = "sing";
        str1[2] = "Sing_C++";
    And VERY FEW if any even came close to this:
    How to replace external file with internal string Array ?

    Thanks whiteflags for breaking the new or I'll still be at it. I never quit. I went nuts about Vector strings all in a day but after this experience I'm sure I'll end up down in the dungeon of cboard department C, forever, hard coding Vector with Pelle's C and FASM, forsure

  4. #4
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,762
    Woah... if you want a vector for each line, there's an easy way to do that. I still wouldn't copy it in there (although you could).

    Code:
    typedef std::vector<std::string> StringArray;
    
    std::vector<StringArray> lines;
    
    std::ifstream ifs;
    std::string oneline;
    
    // open ifs ...
    
    while ( getline( ifs, oneline ) ) {
       lines.push_back( StringArray( 1, oneline ) );
    }
    
    // Use lines[x][y] ...
    Easy things are hard anyway, so if you want to be slick, be slick for a reason. Of course, saying that, I don't know why you need a vector for each line as opposed to simply a string for each line.
    Last edited by whiteflags; 02-23-2011 at 03:14 AM. Reason: swapped getline's arguments

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,806
    Code:
    int main()
    {
        ...
        return main();
    }
    Don't do that! You should just return 0. What you are doing there is recursively calling main... which is bad.



    Code:
    system("pause");
    system ("CLS");
    Technically, you should be including the cstdlib header if you're using the system function. Also, calls to system should be avoided in general. The pause can be safely replaced with a call to cin.get().
    Last edited by hk_mp5kpdw; 02-23-2011 at 07:33 AM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    Code:
    system("pause");
    system ("CLS");
    return main();
    I just do that when it don't cause any issues when I need to re-test a program... It just simply start over again with-out having to close and restart a program. I would not leave it in an final application.

    I just learn about using cin.get() last night. It will stop the program closing. Everyday we find a lots of C++ examples on the INTERNET and many of them will immediately close after execution. cin.get() will take control. But Thanks for the additional information about why not hk_mp5kpdw ... I did not know most of that.

    Thanks again whiteflags,
    I finally got some sleep and is ready for C++ vector, iterator and multi-maps again.
    I still wouldn't copy it in there (although you could)
    I will try anything for those three functions because I just want to understand how everything can work and latter decide what to use and not use. Some people don't like vector because it's slow but I saw benchmarks that prove it is just as fast or a little slower than C++ array if you code using it correctly. That's why I'm hook on learning all I can about it. Got to have something to love when it come to coding. That way it never will be a chore.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,012
    You must not recursively call main. Not just in your release program, but in any code. Things can go wrong if you do. Therefore, you should use a loop instead.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    How do I do this with vector strings?

    Code:
    /* unsorted.txt:  Create a text file named unsorted
    CC
    BB
    AA
    DD
    */
    
     /* sorted.txt:  This file should be created and save. 
    AA
    BB
    CC
    DD
    */
    Code:
    #include<iostream>
    #include<string>
    #include<fstream>
    #include<sstream>
    #include <vector>
    
    using namespace std;
     
    int main() 
               {
               vector<string> v_S;
               ifstream in("unsorted.txt");
               string word;
     
               while(in >> word)
                     v_S.push_back(word);
      
              cout << "\n Success, words are sorted from a textfile:" << "\n\n";
              sort( v_S.begin(), v_S.end() );
              for(int i = 0; i < v_S.size(); ++i)
              cout << v_S[i] <<  "\n";  
    
              cout << "\n\n ... but how do I save it to a textfile?" << "\n";
    
    //  This don't work!
    //	ofstream out("sorted.txt");
    //	cin.getline(word, sizeof(word));
    //	out << word;
    //	out.close();
    			
     
      cin.get();
      return 0;
    }
    Also,
    Therefore, you should use a loop instead.
    How would I add one to this code?
    ...

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,012
    Well, there are theoretically several ways...
    One would be:
    Code:
    for (auto it = vec.begin(); it != vec.end(); ++it)
        outstream << *it;
    Another might be to use std::copy to copy the contents of the vector to an output stream. You would just need an ostream iterator, though I am too lazy to find the exact code for that right now.

    As for loops...
    Code:
    int main()
    {
        while (!done)
        {
              // ...
         }
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    As for loops...
    Thanks Elysia, works like a charm. No more <<return main()>> for me. Also as you see my indentation is improving

    Code:
    for (auto it = vec.begin(); it != vec.end(); ++it)
        outstream << *it;
    How do I use it? Where do it connect to my code? I also tried using the ostream iterator for DAYS but I could not get it to work and that was what force me to post this question which has never be ask on the WWW. Anyway, with my code being so tiny, would it against the forum rule to ask someone to include the fix if one is known?

    Using ostream iterator been my goal for days, but now I be happy with anything that works. Strange to me that this is not a common thing to do. I found not a single thread that done it and 5000 docs tells me nothing.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,012
    Here is an example:
    Code:
    #include <vector>
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main() 
    {
    	vector<string> v_S;
    	//ifstream in("unsorted.txt");
    	//string word;
    
    	//while(in >> word)
    		//v_S.push_back(word);
    
    	v_S.push_back("Success");
    	v_S.push_back("words");
    	v_S.push_back("are");
    	v_S.push_back("sorted");
    	v_S.push_back("from");
    	v_S.push_back("a");
    	v_S.push_back("textfile:\n\n");
    
    	//cout << "\n Success, words are sorted from a textfile:" << "\n\n";
    	//sort( v_S.begin(), v_S.end() );
    	//for(int i = 0; i < v_S.size(); ++i)
    		//cout << v_S[i] <<  "\n"; 
    
    	v_S.push_back("\n\n ... ");
    	v_S.push_back("but");
    	v_S.push_back("how");
    	v_S.push_back("do");
    	v_S.push_back("I");
    	v_S.push_back("save");
    	v_S.push_back("it");
    	v_S.push_back("to");
    	v_S.push_back("a");
    	v_S.push_back("textfile?");
    	//cout << "\n\n ... but how do I save it to a textfile?" << "\n";
    
    	for (auto it = v_S.begin(), end = v_S.end(); it != end; ++it)
    		std::cout << *it;
    
    
    	//  This don't work!
    	//	ofstream out("sorted.txt");
    	//	cin.getline(word, sizeof(word));
    	//	out << word;
    	//	out.close();
    
    
    	cin.get();
    	return 0;
    }
    Note that std::cout is an outstream, just like files! So you can replace std::cout with the name of your ofstream and it should work.
    Last edited by Elysia; 02-26-2011 at 05:00 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,762
    Quote Originally Posted by sharris View Post
    Thanks Elysia, works like a charm. No more <<return main()>> for me. Also as you see my indentation is improving

    Code:
    for (auto it = vec.begin(); it != vec.end(); ++it)
        outstream << *it;
    How do I use it? Where do it connect to my code? I also tried using the ostream iterator for DAYS but I could not get it to work and that was what force me to post this question which has never be ask on the WWW. Anyway, with my code being so tiny, would it against the forum rule to ask someone to include the fix if one is known?

    Using ostream iterator been my goal for days, but now I be happy with anything that works. Strange to me that this is not a common thing to do. I found not a single thread that done it and 5000 docs tells me nothing.
    I think part of the problem is that you are trying to learn like three things at once. If you have no idea what the iterator concept is -- basically applying pointer semantics to anything remotely like traversing a range -- then you're not going to understand how iterators work with the STL. For example, there are lots of different kinds of iterator concepts derived from the iterator concept. The std::copy algorithm depends on OutputIterator and InputIterator to work.

    Stream iterators basically must model InputIterator or OutputIterator. So if you wanted to read a file of integers and display it on the screen, you could do this:
    Code:
    #include <fstream>
    #include <iostream>
    #include <ostream>
    #include <istream>
    #include <iterator>
    #include <algorithm>
    using namespace std;
    
    int main()
    {
        ifstream fin ( "ints.txt" );
        if ( fin.is_open() ) {
            copy( istream_iterator<int>(fin), istream_iterator<int>(), ostream_iterator<int>(cout, " ") );
        }
        return 0;
    }
    The pre-requisite knowledge for writing a program like this is understanding the iterators involved. I would look at the differences between istream_* and ostream_iterator here, and supplement it with the knowledge on OutputIterator and InputIterator available here or any similar reference. That last page is a really good place to find info on any iterators you may be using, since it looks at the iterator concept as a whole.

    Equally though, it's important to know that because of the limitations of stream iterators, mainly:
    • that they can only ever do a single pass over a sequence
    • that they can only store one type T
    • that the type T has a working operator>> OR operator<< to do storage operations OR extraction operations

    that you simply cannot and shouldn't try to do all file processing with stream iterators.

    The FIRST program that you actually posted in this thread tries to read a file and push_back the contents into a vector of integers through the back_insert_iterator type. You used the back_insert_iterator well enough, but the file itself (and thus any other stream you turned it into such as a stringstream) failed to work with the second limitation of stream iterators. So copying the contents into a vector wasn't really going to work.

    You've done other things wrong too but I don't have time to cover them right now, sorry. I hope I helped, anyway.

  13. #13
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    Elysia, very nice but your code does not compile and it's not like the original code that actually read an external file into vector strings. Dimensioning vector is next runner up but right now it's about vector strings. I had to drop the dimension thing for a minute.

    How about this... I been very close it seems... This is what I been trying to do when using the iterator, but it keeps dumping the iterator template on me as an error at this block of code.
    Code:
      template<typename _InputIterator, typename _OutputIterator>
        inline _OutputIterator
        __copy_aux2(_InputIterator __first, _InputIterator __last,
    		_OutputIterator __result, __false_type)
        { return std::__copy(__first, __last, __result,
    			 std::__iterator_category(__first)); }
    Code:
    #include<iostream>
    #include<string>
    #include<fstream>
    #include<sstream>
    #include <vector>
    #include <iterator>
    using namespace std;
     
    int main() 
               {
               vector<string> v_S;
               ifstream in("unsorted.txt");
               string word;
     
               while(in >> word)
                     v_S.push_back(word);
      
              cout << "\n Success, words are sorted from a textfile:" << "\n\n";
    
              sort( v_S.begin(), v_S.end() );
              for(int i = 0; i < v_S.size(); ++i)
              cout << v_S[i] <<  "\n";  
    
              cout << "\n\n ... but how do I save it to a textfile?" << "\n";
    
    
              ofstream outfile("sorted.txt", ios::out | ios::binary); //  < =====
              ostream_iterator<char> I_O(outfile, '\0');
              copy(v_S.begin(), v_S.end(), I_O);
        
     
      cin.get();
      return 0;
    }

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,012
    Quote Originally Posted by sharris View Post
    Elysia, very nice but your code does not compile and it's not like the original code that actually read an external file into vector strings. Dimensioning vector is next runner up but right now it's about vector strings. I had to drop the dimension thing for a minute.
    Oh, sorry. I thought I compiled it, but I guess it slipped my mind.
    And yes, I am aware it does not read from a file, but I didn't want to create a file to read from and I wanted some output.
    You can substitute that manual push to your code, which should work.

    Code:
    #include <vector>
    #include <iostream>
    #include <algorithm>
    #include <string>
    
    using namespace std;
    
    int main() 
    {
    	vector<string> v_S;
    	//ifstream in("unsorted.txt");
    	//string word;
    
    	//while(in >> word)
    		//v_S.push_back(word);
    
    	v_S.push_back("Success ");
    	v_S.push_back("words ");
    	v_S.push_back("are ");
    	v_S.push_back("sorted ");
    	v_S.push_back("from ");
    	v_S.push_back("a ");
    	v_S.push_back("textfile:\n\n");
    
    	//cout << "\n Success, words are sorted from a textfile:" << "\n\n";
    	//sort( v_S.begin(), v_S.end() );
    	//for(int i = 0; i < v_S.size(); ++i)
    		//cout << v_S[i] <<  "\n"; 
    
    	v_S.push_back("\n\n ... ");
    	v_S.push_back("but ");
    	v_S.push_back("how ");
    	v_S.push_back("do ");
    	v_S.push_back("I ");
    	v_S.push_back("save ");
    	v_S.push_back("it ");
    	v_S.push_back("to ");
    	v_S.push_back("a ");
    	v_S.push_back("textfile?");
    	//cout << "\n\n ... but how do I save it to a textfile?" << "\n";
    
    	for (auto it = v_S.begin(), end = v_S.end(); it != end; ++it)
    		std::cout << *it;
    
    
    	//  This don't work!
    	//	ofstream out("sorted.txt");
    	//	cin.getline(word, sizeof(word));
    	//	out << word;
    	//	out.close();
    
    
    	cin.get();
    	return 0;
    }
    EDIT:
    Here is another example:
    Code:
    #include <string>
    #include <fstream>
    #include <vector>
    #include <iterator>
    #include <iostream>
    #include <algorithm>
    
    int main() 
    {
    	std::vector<std::string> v_S;
    
    	v_S.push_back("Success ");
    	v_S.push_back("words ");
    	v_S.push_back("are ");
    	v_S.push_back("sorted ");
    	v_S.push_back("from ");
    	v_S.push_back("a ");
    	v_S.push_back("textfile:\n\n");
    
    	v_S.push_back("\n\n ... ");
    	v_S.push_back("but ");
    	v_S.push_back("how ");
    	v_S.push_back("do ");
    	v_S.push_back("I ");
    	v_S.push_back("save ");
    	v_S.push_back("it ");
    	v_S.push_back("to ");
    	v_S.push_back("a ");
    	v_S.push_back("textfile?");
    
    	std::ofstream outfile("sorted.txt"); //  < =====
    	std::ostream_iterator<std::string> I_O(outfile, " ");
    	std::copy(v_S.begin(), v_S.end(), I_O);
    	outfile.close();
    
    	std::ifstream infile("sorted.txt");
    	std::istream_iterator<std::string> in_it(infile);
    	std::istream_iterator<std::string> end;
    	std::ostream_iterator<std::string> out_it(std::cout, " ");
    	std::copy(in_it, end, out_it);
    
    	std::cin.get();
    	return 0;
    }
    Basically, the type for the iterator shall be the type that you are going to copy and read from the file. Since the vector saves std::string, that's what you'll want to use.
    Last edited by Elysia; 02-26-2011 at 06:06 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,762
    How about this... I been very close it seems... This is what I been trying to do when using the iterator, but it keeps dumping the iterator template on me as an error at this block of code.
    You're not going to like the answer, but I don't think you can use copy to do this. operator>> and operator<< are not really for binary file processing.

    If you want, you could try to join the elements of the vector of strings into one string made with vector<char> (since string is only contiguous after C++0x I believe, and that's important because of the way write() works). Then, take the vector<char> and copy that to the file. But again, we're trying to be cool for no real reason. I really hope you take that to heart. And I can't guarantee it works.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 09:36 PM
  2. syntax help?
    By scoobygoo in forum C++ Programming
    Replies: 1
    Last Post: 08-07-2007, 11:38 AM
  3. Vector class
    By Desolation in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2007, 06:44 PM
  4. Need some help/advise for Public/Private classes
    By nirali35 in forum C++ Programming
    Replies: 8
    Last Post: 09-23-2006, 01:34 PM
  5. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 01:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21