Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a vector member's value?

I was trying to use vector svec to store some string values. But when compiling at Dev C++ 5.6.1, the compiler reported an error of "no match for operator=". Why is there this error and how to fix it? Thanks.

    #include<vector>
    #include<iostream>
    #include<string>
    using namespace std;
    int main() {
        vector<string> svec[100];
        for (int i = 0; i < 100; ++i) {
            svec[i] = "ABC";
        }
        return 0;
    }

[Error] no match for 'operator=' (operand types are 'std::vector >' and 'const char [4]')

edit: The problem is in vector svec[100]; Things go well after changing it to vector svec(100);

edit2: I'm curious what the compiler regards this following declaration. Is svec still declared as a vector?

vector<string> svec[100];
like image 594
Zining Zhu Avatar asked Jun 12 '26 22:06

Zining Zhu


2 Answers

vector<string> svec[100]; is creating an array with 100 elements of std::vector<std::string>. That's valid syntax although it's a rather odd thing to do.

In its current form, svec[i] therefore refers to a std::vector<std::string>. Assigning "ABC" to that is not possible. That's why you get the error.

What you mean to write is vector<string> svec(100);. This is calling one of the vector constructors which pre-sizes the vector to have 100 elements.

It just happens that std::vector overloads the [] operator to give you element access. (A rather convenient analogue to pure arrays.) If you make the change, svec[i] will refer to a string which you can set in the way that you currently do.

like image 106
Bathsheba Avatar answered Jun 14 '26 10:06

Bathsheba


Change this statement

vector<string> svec[100];

to

vector<string> svec( 100 );

That is instead of an array of 100 vectors you should define a vector of 100 elements.:)

Or you could write simply

    vector<string> svec;
    // svec.reserve( 100 );
    for (int i = 0; i < 100; ++i) {
        svec.push_back( "ABC" );
    }

And the most simplest way is the following

int main() {
        vector<string> svec( 100, "ABC" );
        return 0;
    }
like image 43
Vlad from Moscow Avatar answered Jun 14 '26 10:06

Vlad from Moscow