I am trying to use iterators to go through 2D vector and replace a specific symbol with another symbol. If you take a look at the first code bellow you will notice that there is no problem to replace '.' with '+' (in standard vector), However: if I try the same approach with a 2D vector the compiler shows me the following error: vec.at(col - row->begin()) = '+';
Compiler Error C2679 binary 'operator': no operator found which takes a right-hand operand of type 'type' (or there is no acceptable conversion)
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<char> myints{ '.', '.','!','.' };
vector<char>::iterator p;
p = find(begin(myints), end(myints), '!');
if (p != end(myints)) {
myints.at(p - begin(myints)) = '+';
}
for (auto i : myints) {
cout << i << " ";
}
return 0;
}
and the following:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void readVector(vector< vector<char> >& vec)
{
vector< vector<char> >::iterator row;
vector<char>::iterator col;
for (row = vec.begin(); row != vec.end(); ++row)
{
for (col = row->begin(); col != row->end(); ++col) {
if (*col == '!') {
vec.at(col - row->begin()) = '+';
}
}
}
}
int main()
{
// Initializing 2D vector "vect" with
// values
vector<vector<char> > vect{ { '.', '.', '.' },
{ '!', '.', '.' },
{ '!', '.', '!' } };
readVector(vect);
}
Thanks a lot in advance!
Modify offending line to
row->at(col - row->begin()) = '+';
You've addressing the index of a row
and not in the original vec
.
On a side note your first program can be simplified to be used with many different containers with this change, no just random access containers.
p = find(begin(myints), end(myints), '!');
if (p != end(myints)) {
*p = '+';
}
The same goes to the offending line:
if (*col == '!') {
*col = '+';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.