std::find 类型为 T** 与 T*[N]
我更喜欢使用 std::string ,但我喜欢找出这里出了什么问题。
我无法理解为什么 std::find
对于类型 T**
不能正常工作,即使指针算术可以正确地处理它们。就像 -
std::cout << *(argv+1) << "\t" <<*(argv+2) << std::endl;
但对于 T*[N]
类型来说,它工作得很好。
#include <iostream>
#include <algorithm>
int main( int argc, const char ** argv )
{
std::cout << *(argv+1) << "\t" <<*(argv+2) << std::endl;
const char ** cmdPtr = std::find(argv+1, argv+argc, "Hello") ;
const char * testAr[] = { "Hello", "World" };
const char ** testPtr = std::find(testAr, testAr+2, "Hello");
if( cmdPtr == argv+argc )
std::cout << "String not found" << std::endl;
if( testPtr != testAr+2 )
std::cout << "String found: " << *testPtr << std::endl;
return 0;
}
通过的参数:Hello World
输出:
世界你好
未找到字符串
找到字符串:你好
谢谢。
I prefer to work with std::string
but I like to figure out what is going wrong here.
I am unable to understand out why std::find
isn't working properly for type T**
even though pointer arithmetic works on them correctly. Like -
std::cout << *(argv+1) << "\t" <<*(argv+2) << std::endl;
But it works fine, for the types T*[N]
.
#include <iostream>
#include <algorithm>
int main( int argc, const char ** argv )
{
std::cout << *(argv+1) << "\t" <<*(argv+2) << std::endl;
const char ** cmdPtr = std::find(argv+1, argv+argc, "Hello") ;
const char * testAr[] = { "Hello", "World" };
const char ** testPtr = std::find(testAr, testAr+2, "Hello");
if( cmdPtr == argv+argc )
std::cout << "String not found" << std::endl;
if( testPtr != testAr+2 )
std::cout << "String found: " << *testPtr << std::endl;
return 0;
}
Arguments passed: Hello World
Output:
Hello World
String not found
String found: Hello
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
比较 char const* 的类型相当于指向地址。
"Hello"
的地址保证是不同的,除非您将它与字符串文字"Hello"
的另一个地址进行比较(在这种情况下,指针可能< /em> 比较相等)。您的compare()
函数会比较所指向的字符。Comparing types of
char const*
amounts to pointing to the addresses. The address of"Hello"
is guaranteed to be different unless you compare it to another address of the string literal"Hello"
(in which case the pointers may compare equal). Yourcompare()
function compares the characters being pointed to.在第一种情况下,您比较的是指针值本身,而不是它们所指向的内容。并且常量“Hello”与 argv 的第一个元素的地址不同。
尝试使用:
std::string
知道比较内容而不是地址。对于数组版本,编译器可以将所有文字折叠为一个文字,因此每次在整个代码中看到“Hello”时,它实际上都是同一个指针。因此,比较 in 的相等性
会产生正确的结果
In the first case, you're comparing the pointer values themselves and not what they're pointing to. And the constant "Hello" doesn't have the same address as the first element of
argv
.Try using:
std::string
knows to compare contents and not addresses.For the array version, the compiler can fold all literals into a single one, so every time "Hello" is seen throughout the code it's really the same pointer. Thus, comparing for equality in
yields the correct result