【发布时间】: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 元素数组的索引从0到7。所以“结束”迭代器是inputs1 + 8。此外,你甚至不需要那些数组,你可以直接初始化向量:std::vector<int> 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<int> v1{1,2,3,4,5,6,7,8};。类似地,对于代码下方的字符串数组。 C++11 以后的初始化列表允许直接填充标准容器。 -
您的第一个
mismatch呼叫将在v2结束时运行,因为您将它们两个设置为相同的大小,然后在第二个开始时领先2 个。我假设您并不是要使它们具有相同的大小,但这是直接初始化它们的另一个原因。
标签: c++