如何在结构中正确使用const字符串指针?

时间:2014-03-16 21:36:46

标签: c++

你好我有一个带有const字符串指针的结构:

struct something{
    something(const string & a, const string &b)
    {
        first=&a;
        second=&b;
    }
    const string * first;
    const string * second;
    int somethingelse;
};

我有指针,因为我不想创建字符串的本地副本,我的问题是如何正确使用这些字符串的值,我需要做比较字符串等操作。我试着这样做:

vector<something> myvec;
something tmp1("hello","world");
something tmp2("hello","world");
myvec.push_back(tmp1);
myvec.push_back(tmp2);
cout << *myvec[0].first;
if((*(myvec[0].first)+*(myvec[0].second))==(*(myvec[1].first)+*(myvec[1].second)))
 cout << '1';

但它并没有真正起作用,而且valgrind有很多问题。 对任何建议都会感激不尽。

修改:----------------&GT;

好的家伙,所以你可能是对的,我真的需要制作字符串的本地副本。我实际上发现在我的程序中制作本地副本并不是真正的问题。问题是字符串之间的比较。 我得到了一个排序算法,包括很多比较:

if(((myvec[0].first)+(myvec[0].second))==((myvec[1].first)+(myvec[1].second)))

if(((myvec[0].first)+(myvec[0].second))<(string1+string2))
是什么造成了很多临时子串并且使程序变得非常困难。我修复了将字符串链接到一个字符串的问题,这使得比较速度明显加快。

struct something{
    something(const string & a, const string &b)
    {
        firstsecond=a+'|'+b;
    }
    string firstsecond;
    int somethingelse;
};

感谢btw的建议。

1 个答案:

答案 0 :(得分:3)

  

我有指针,因为我不想创建字符串的本地副本,我的问题是如何正确使用这些字符串的值。

老实说,在这种情况下使用指针会很麻烦。主要是因为指针并不像人们想象的那样容易使用。只需看看你现在的代码。它的错误是因为,例如,something的默认构造函数将复制指针,有效地在两个something对象之间共享字符串。

我建议完全放弃指针,忘掉这个&#34;表现&#34;问题,直到你确实证明你的应用程序的瓶颈在于复制字符串:

struct something {
    something(const string & a, const string &b)
    {
        first = a;
        second = b;
    }
    const string first;
    const string second;
    int somethingelse;
};