copy algorithm:segmentation fault error appears

U

utab

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using std::cout;
using std::vector;
using std::string;
using std::endl;
using std::copy;
using std::back_inserter;

int main(){

vector<string> str;
vector<string>::iterator iterb = str.begin(),iter=str.begin();
vector<string>::iterator itere = iterb+11;
vector<string>::size_type i = 0;
vector<string> dest;

while(iter!=itere){

*(iter)="string";

iter++;
}

copy(iterb,itere,back_inserter(dest));

while(i!=dest.size()){

cout << dest;
i++;
}

return 0;

}

Why?
 
B

Ben Pope

utab said:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using std::cout;
using std::vector;
using std::string;
using std::endl;
using std::copy;
using std::back_inserter;

int main(){

vector<string> str;
vector<string>::iterator iterb = str.begin(),iter=str.begin();
vector<string>::iterator itere = iterb+11;
vector<string>::size_type i = 0;
vector<string> dest;

while(iter!=itere){

*(iter)="string";

iter++;
}

OK, itere points to the 11th element of str, which is an empty vector.
It has no 11th element, nor a first.

Use a for loop counting between 0 and 11, and use use push_back within it.

After that, initialise itere with str.end().
copy(iterb,itere,back_inserter(dest));

while(i!=dest.size()){

cout << dest;
i++;
}


Instead you can use copy (as above), and an ostream_iterator.
return 0;

}

Why?

Assigning to elements in the vector that have not been allocated.

Techniques to fix that:
1) Don't declare variables until you can properly initialise them (see
itere, which should be initialised as str.end())
2) Don't create random offsets of iterators if you don't need to. (the 11)

Read up on push_back and ostream_iterator.

Post the code you end up with here again, and we'll have another look.

Ben Pope
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top