如何存储数组中匹配的数字?

时间:2015-01-19 10:52:07

标签: c++

我想将与arrayOfNumbers匹配的numToMatch索引添加到数组中。不知道该怎么做。我是C ++的新手。任何帮助都将受到赞赏。

int numToMatch[4] = {1,2,3,4};
int arrayOfNumbers[7] = {0, 1, 2, 3, 4, 5, 6};
int IndexThatMatched[4]; // Want to add to this Array.
int main()
{
    for(int i = 0; i < 4; i++)
    {
        for(int j = 0; j < 7; j++)
        {
            if(numToMatch[i] == arrayOfNumbers[j]) 
            {
                cout << "Num " << numToMatch[i] << " ";
                cout << "matches " << arrayOfNumbers[j];
                cout << endl;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

只添加了两行。

int numToMatch[4] = {1,2,3,4};
int arrayOfNumbers[7] = {0, 1, 2, 3, 4, 5, 6};
int IndexThatMatched[4]; // Want to add to this Array.
int main()
{
    for(int i = 0; i < 4; i++)
    {
        IndexThatMatched[i] = -1;
        for(int j = 0; j < 7; j++)
        {
            if(numToMatch[i] == arrayOfNumbers[j]) 
            {
                cout << "Num " << numToMatch[i] << " ";
                cout << "matches " << arrayOfNumbers[j];
                cout << endl;
                IndexThatMatched[i] = j;
            }
        }
    }
}

如果numToMatch[k]没有匹配,则IndexThatMatched[k]将为-1。

在您的示例中,IndexThatMatched将是:{1, 2, 3, 4} 这是因为numToMatch的元素位于arrayOfNumbers的索引1-4中。

此外,在该运行之后,对于安全范围内的任何k:
numToMatch[k] == arrayOfNumbers[IndexThatMatched[k]]

答案 1 :(得分:0)

如果你真的想学习C ++,那就是C风格的数组并开始用容器练习。如果您将它们与<algorithm&gt;中的功能结合使用你可以这样写:

std::vector<int> MatchNums{1,2,3,4};
std::vector<int> NumsToMatch{0, 1, 2, 3, 4, 5, 6};
std::vector<int> MatchedNums;

for ( auto Number:NumsToMatch )
{
    auto Match = std::find( MatchNums.begin(), MatchNums.end(), Number );
    if ( Match != MatchNums.end() )
    {
        MatchedNums.push_back( *Match );
    }
}

for ( auto i:MatchedNums )
{   //Print out the found numbers:
    std::cout << i << std::endl;
}

通过组合不同的算法,还有更多的方法可以做到这一点,我鼓励您尽可能多地考虑并尝试全部。