[英]Comparing string* in C++
Let a
and b
be given positive integers.让
a
和b
被赋予正整数。 Consider the following C++17 code:考虑以下 C++17 代码:
string* first;
first = new string[a];
//some definitions
string* second;
second = new string[b];
//some definitions
By saying a string first[i]
is undefined, I mean no definition is ever made to the string first[i]
after the creation code given above.通过说一个字符串
first[i]
是未定义的,我的意思是在上面给出的创建代码之后没有对字符串first[i]
进行任何定义。
I define first
and second
to be equal if:如果满足以下条件,我将
first
和second
定义为相等:
a==b
. a==b
。first[i]
and second[i]
are equivalent for every non-negative integer i<a
, in the following sense: if first[i]
is undefined, then so is second[i]
; first[i]
和second[i]
对于每个非负 integer i<a
都是等价的,在以下意义上:如果first[i]
未定义,那么second[i]
也是如此; if first[i]
has length l
(where l
is a non-negative integer), then second[i]
has length l
and first[i][j]
is the same char as second[i][j]
for every non-negative integer j<l
.first[i]
的长度为l
(其中l
是一个非负整数),则second[i]
的长度为l
并且first[i][j]
与second[i][j]
的每个非-负 integer j<l
。 In short, I want the most ordinary string equality with the emphasis on comparing the contents rather than the pointers.简而言之,我想要最普通的字符串相等,重点是比较内容而不是指针。 What is the most appropriate way to do this in C++17?
在 C++17 中执行此操作的最合适方法是什么? I tried multiple answers and none of them works.
我尝试了多个答案,但没有一个有效。
I'm assuming string
is std::string
.我假设
string
是std::string
。
The real solution here would be to use std::vector<std::string>
rather than managing your own dynamic memory:这里真正的解决方案是使用
std::vector<std::string>
而不是管理自己的动态 memory:
std::vector<std::string> first;
//some definitions
std::vector<std::string> second;
//some definitions
bool equal = (first == second); // does what you want
If, for some reason, you cannot use std::vector
, the C-style approach would look something like如果由于某种原因,您不能使用
std::vector
,则 C 风格的方法看起来像
bool are_equal(std::string* first, std::size_t first_size, std::string* second, std::size_t second_size) {
if (first_size != second_size) return false;
for (std::size_t idx = 0; idx != first_size; ++idx) {
if (first[idx] != second[idx]) return false;
}
return true;
}
int main() {
string* first = new string[a];
//some definitions
string* second = new string[b];
//some definitions
bool equal = are_equal(first, a, second, b);
return 0;
}
With C++20, prefer using std::span
here对于 C++20,更喜欢在此处使用
std::span
bool are_equal(std::span<const std::string> first, std::span<const std::string> second) {
if (first.size() != second.size()) return false;
for (std::size_t idx = 0; idx != first.size(); ++idx) {
if (first[idx] != second[idx]) return false;
}
return true;
}
int main() {
string* first = new string[a];
//some definitions
string* second = new string[b];
//some definitions
bool equal = are_equal({first, a}, {second, b});
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.