【问题标题】:no operator "=" matches these operands error没有运算符“=”匹配这些操作数错误
【发布时间】:2021-06-21 05:58:17
【问题描述】:

我已经尝试过这段代码。我收到了错误

no operator "=" matches these operands -- operand types are:
std::pair<__gnu_cxx::__normal_iterator<const char *,
std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char>>>, __gnu_cxx::__normal_iterator<char *,
std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char>>>> = std::pair<std::__cxx11::string *,
std::__cxx11::string *>

代码:

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;

bool cmp_string(std::string i , std::string j)
{
    return ( i.size() == j.size() );
}

int main()
{
int inputs1[] = {1,2,3,4,5,6,7,8};
int inputs2[] = {-1,2,1,2,3,4,6,7,8,9};

vector<int> v1(inputs1 ,inputs1+9);
vector<int> v2(inputs2 ,inputs2+9);

pair<vector<int>::iterator, vector<int>::iterator>  position;
/* defining a pair of iterator to the vector of integer */

position = mismatch(v1.begin(), v1.end(), v2.begin()+2) ;

/* now position.first is an iterator pointing 
to the 5th element in the vector v1 and position.second 
points to the 7th element in the vector v2 */

/* use of compare function */
string s1[] = {"abc", "def", "temp", "testing"};
string s2[] = {"xyz", "emp", "res", "testing"};

pair<string::iterator, string::iterator> position1;

position1 = mismatch(s1, s1+4, s2, cmp_string);
  /* now position2.first is an iterator pointing
to the 3rd element in s1 and position2.second points 
to the 3rd element in the s2 */
return 0;

}

【问题讨论】:

  • inputs1+9 距离 8 元素数组的末尾 步。请记住,数组索引是从零开始的,一个 8 元素数组的索引从 07。所以“结束”迭代器是inputs1 + 8。此外,你甚至不需要那些数组,你可以直接初始化向量:std::vector&lt;int&gt; v1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
  • s1 和 s2 是字符串数组,这些数组的迭代器是 string*,而不是 string::iterator。最好使用 auto position1 = ...
  • 顺便我建议你了解一下 C++ 变量定义的自动类型推导,这样可以很容易地解决这里的问题:auto position1 = mismatch(s1, s1 + 4, s2, cmp_string);
  • 您是否有理由不直接填充向量?即std::vector&lt;int&gt; v1{1,2,3,4,5,6,7,8};。类似地,对于代码下方的字符串数组。 C++11 以后的初始化列表允许直接填充标准容器。
  • 您的第一个mismatch 呼叫将在v2 结束时运行,因为您将它们两个设置为相同的大小,然后在第二个开始时领先2 个。我假设您并不是要使它们具有相同的大小,但这是直接初始化它们的另一个原因。

标签: c++


【解决方案1】:

@S.M. 发现了直接问题,position1 不是正确的类型。您还应该考虑其他代码改进:

  1. 使用自动类型扣除。 @Someprogrammerdude 建议使用 auto position1 ...,它在 C++11 及更高版本中可用。
  2. @Evg 建议您使用std::begin()std::end() 而不是x, x+size 对。这会删除显式的大小参数,因此会降低程序员出错的可能性,因为编译器或运行时代码会为您确定大小。
  3. 正如 @Someprogrammerdude 和我所建议的,您可以在 C++11 及更高版本中使用初始化列表,以便直接填充 std::vector
  4. 不要在代码中使用笼统的using namespace std; 语句。在全局命名空间中引入过多可能会导致大型代码库中的名称冲突。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多